@code-partner/codepipe 0.1.137-dev.64.g8fe83af → 0.1.137-dev.67.g38523e5

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 +108 -101
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,35 +1,35 @@
1
1
  #!/usr/bin/env node
2
- var pe="0.1.137-dev.64.g8fe83af",ve="https://hub.dev.codepipe.dev";var Se=4,ql=4;function _r(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=ql&&t<=Se}var Ce=".codepipe-context.yaml",ir=".devpipe-context.yaml",Qn=[{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",Ce]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Ce]}];function Or(t=2){return`# CodePipe Context Repo format version.
2
+ var me="0.1.137-dev.67.g38523e5",ve="https://hub.dev.codepipe.dev";var Se=4,Zl=4;function Or(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Zl&&t<=Se}var Ce=".codepipe-context.yaml",sr=".devpipe-context.yaml",ri=[{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",Ce]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Ce]}];function Nr(t=2){return`# CodePipe Context Repo format version.
3
3
  # Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
4
4
  template_version: ${t}
5
- `}function Zn(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 ei(t,e=Qn){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 ti(t,e=Qn){return e.filter(r=>r.version>t)}function ct(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var lt=/^[a-z][a-z0-9-]{1,30}$/,Yl="-codepipe-ctx";function Ne(t){return`${t}${Yl}`}var Vl=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}];function Nr(t){for(let e of Vl){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var sr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function vt(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 ut="x-bitbucket-api-token-auth";function Ur(t){switch(t){case sr.gitlab:return"oauth2";case sr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var ri=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Xg}from"commander";import{homedir as ai}from"node:os";import{mkdirSync as nu,readFileSync as iu,writeFileSync as su,existsSync as Lo}from"node:fs";import{dirname as li,join as Br,resolve as au}from"node:path";import{fileURLToPath as cu}from"node:url";import{existsSync as Lr,readFileSync as ni,readdirSync as Jl,writeFileSync as Xl}from"node:fs";import{dirname as Ql,join as Ke}from"node:path";import{parse as Zl}from"yaml";import{existsSync as oi,renameSync as zl}from"node:fs";function pt(t,e,r=o=>console.error(o)){if(oi(e)||!oi(t))return!1;try{return zl(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 Te=".codepipe",Uo=".devpipe";function eu(t=process.cwd()){let e=t;for(;;){if(Lr(Ke(e,Te,"project.yaml")))return e;if(Lr(Ke(e,Uo,"project.yaml")))return pt(Ke(e,Uo),Ke(e,Te))&&ru(e),e;let r=Ql(e);if(r===e)return null;e=r}}function tu(t){let e=Ke(t,Te);return Lr(e)?e:Ke(t,Uo)}function ru(t){let e=Ke(t,".gitignore");if(!Lr(e))return;let r=ni(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&&Xl(e,o)}function de(t=process.cwd()){let e=eu(t);if(!e)return null;let r=tu(e),o=ou(ni(Ke(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function ii(t,e,r){return Jl(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 Dr(t,e=process.cwd()){try{let r=de(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function ou(t){let e=Zl(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),o=String(e.name??r),n=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of n){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,f=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:o,repos:i}}function si(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 ci=au(li(cu(import.meta.url)),"..");function ui(t){let e=Br(ci,".env");if(Lo(e)&&process.loadEnvFile(e),t){let r=Br(ci,"profiles",t,".env");Lo(r)&&process.loadEnvFile(r)}}function St(t){let e=L("CONFIG");return e||(t?Br(ai(),".codepipe","profiles",t,"config.json"):Br(ai(),".codepipe","config.json"))}function we(t){let e=St(t);if(!Lo(e))return null;let r=iu(e,"utf-8");return JSON.parse(r)}function Ue(t,e){let r=St(e);nu(li(r),{recursive:!0}),su(r,JSON.stringify(t,null,2)+`
7
- `,{mode:384})}function Mr(t){if(t)return{cfg:fe(t),profile:t};let e;try{e=de()?.spec.projectId||void 0}catch{}if(e){let r=we(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:fe(void 0),profile:void 0}}function fe(t){let e=we(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 ${St(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as pi}from"node:os";import{join as di}from"node:path";function fi(){pt(di(pi(),".devpipe"),di(pi(),".codepipe"))}import{homedir as mi}from"node:os";import{existsSync as gi,mkdirSync as hi,readFileSync as yi,writeFileSync as wi}from"node:fs";import{dirname as ki,join as bi}from"node:path";function Gr(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,K(o),"pinned")}function $i(t,e){let r=U(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],K(r),!0):!1}function Re(t){return bi(mi(),".codepipe","secrets",`${t}.json`)}function U(t){let e=Re(t);return gi(e)?JSON.parse(yi(e,"utf-8")):null}function K(t){let e=Re(t.projectId);hi(ki(e),{recursive:!0}),wi(e,JSON.stringify(t,null,2)+`
8
- `,{mode:384})}function Fr(){return bi(mi(),".codepipe","shared.json")}function Do(){let t=Fr();return gi(t)?JSON.parse(yi(t,"utf-8")):null}function xi(t){let e=Fr();hi(ki(e),{recursive:!0}),wi(e,JSON.stringify(t,null,2)+`
9
- `,{mode:384})}function Ct(t){let e=U(t)?.claude?.oauthToken;return e||Do()?.claude?.oauthToken}function ar(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 Tt(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function vi(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=we(e);r&&!t.force&&(console.error(`already configured at ${St(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");Ue({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...U(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};K(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${St(e)}`)}import{homedir as mn}from"node:os";import{join as wr}from"node:path";import{appendFileSync as lu,existsSync as Si,mkdirSync as uu,renameSync as Ci,statSync as pu,unlinkSync as du}from"node:fs";import{Writable as fu}from"node:stream";import{join as mu}from"node:path";var Ti={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Rt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&uu(e.dir,{recursive:!0}),this.currentPath=mu(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 oi(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 ni(t,e=ri){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 ii(t,e=ri){return e.filter(r=>r.version>t)}function lt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var ut=/^[a-z][a-z0-9-]{1,30}$/,eu="-codepipe-ctx";function Le(t){return`${t}${eu}`}var tu=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}];function Ur(t){for(let e of tu){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var ar={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function St(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let o=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return o?o[1]??null:null}var pt="x-bitbucket-api-token-auth";function Lr(t){switch(t){case ar.gitlab:return"oauth2";case ar.bitbucket:return"x-token-auth";default:return"x-access-token"}}var si=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as mh}from"commander";import{homedir as pi}from"node:os";import{mkdirSync as pu,readFileSync as du,writeFileSync as fu,existsSync as Do}from"node:fs";import{dirname as fi,join as Mr,resolve as mu}from"node:path";import{fileURLToPath as gu}from"node:url";import{existsSync as Dr,readFileSync as ci,readdirSync as ou,writeFileSync as nu}from"node:fs";import{dirname as iu,join as qe}from"node:path";import{parse as su}from"yaml";import{existsSync as ai,renameSync as ru}from"node:fs";function dt(t,e,r=o=>console.error(o)){if(ai(e)||!ai(t))return!1;try{return ru(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 Re=".codepipe",Lo=".devpipe";function au(t=process.cwd()){let e=t;for(;;){if(Dr(qe(e,Re,"project.yaml")))return e;if(Dr(qe(e,Lo,"project.yaml")))return dt(qe(e,Lo),qe(e,Re))&&lu(e),e;let r=iu(e);if(r===e)return null;e=r}}function cu(t){let e=qe(t,Re);return Dr(e)?e:qe(t,Lo)}function lu(t){let e=qe(t,".gitignore");if(!Dr(e))return;let r=ci(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&&nu(e,o)}function se(t=process.cwd()){let e=au(t);if(!e)return null;let r=cu(e),o=uu(ci(qe(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function li(t,e,r){return ou(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=se(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function uu(t){let e=su(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),o=String(e.name??r),n=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of n){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,d=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:d,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 ui(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 di=mu(fi(gu(import.meta.url)),"..");function mi(t){let e=Mr(di,".env");if(Do(e)&&process.loadEnvFile(e),t){let r=Mr(di,"profiles",t,".env");Do(r)&&process.loadEnvFile(r)}}function Ct(t){let e=L("CONFIG");return e||(t?Mr(pi(),".codepipe","profiles",t,"config.json"):Mr(pi(),".codepipe","config.json"))}function ue(t){let e=Ct(t);if(!Do(e))return null;let r=du(e,"utf-8");return JSON.parse(r)}function De(t,e){let r=Ct(e);pu(fi(r),{recursive:!0}),fu(r,JSON.stringify(t,null,2)+`
7
+ `,{mode:384})}function Gr(t){if(t)return{cfg:ge(t),profile:t};let e;try{e=se()?.spec.projectId||void 0}catch{}if(e){let r=ue(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:ge(void 0),profile:void 0}}function ge(t){let e=ue(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Ct(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as gi}from"node:os";import{join as hi}from"node:path";function yi(){dt(hi(gi(),".devpipe"),hi(gi(),".codepipe"))}import{homedir as wi}from"node:os";import{existsSync as ki,mkdirSync as bi,readFileSync as $i,writeFileSync as xi}from"node:fs";import{dirname as vi,join as Si}from"node:path";function Fr(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,K(o),"pinned")}function Ci(t,e){let r=U(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],K(r),!0):!1}function Te(t){return Si(wi(),".codepipe","secrets",`${t}.json`)}function U(t){let e=Te(t);return ki(e)?JSON.parse($i(e,"utf-8")):null}function K(t){let e=Te(t.projectId);bi(vi(e),{recursive:!0}),xi(e,JSON.stringify(t,null,2)+`
8
+ `,{mode:384})}function Hr(){return Si(wi(),".codepipe","shared.json")}function Bo(){let t=Hr();return ki(t)?JSON.parse($i(t,"utf-8")):null}function Ri(t){let e=Hr();bi(vi(e),{recursive:!0}),xi(e,JSON.stringify(t,null,2)+`
9
+ `,{mode:384})}function Rt(t){let e=U(t)?.claude?.oauthToken;return e||Bo()?.claude?.oauthToken}function cr(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 Tt(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Ti(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=ue(e);r&&!t.force&&(console.error(`already configured at ${Ct(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");De({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...U(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};K(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${Ct(e)}`)}import{homedir as gn}from"node:os";import{join as kr}from"node:path";import{appendFileSync as hu,existsSync as Ii,mkdirSync as yu,renameSync as ji,statSync as wu,unlinkSync as ku}from"node:fs";import{Writable as bu}from"node:stream";import{join as $u}from"node:path";var Pi={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},It=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&yu(e.dir,{recursive:!0}),this.currentPath=$u(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
- `;lu(this.currentPath,r,"utf-8")}asWritable(){return new fu({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||!Si(this.currentPath)||pu(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;Si(o)&&(r>=this.cfg.maxFiles?du(o):Ci(o,`${this.currentPath}.${r+1}`))}Ci(this.currentPath,`${this.currentPath}.1`)}}};function Hr(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=gu(process.env[`${t}_MAX_BYTES`]??String(Ti.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Ti.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function gu(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 Kr(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(hu(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 hu(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:yu(n)).join(" ");return`${r} ${t} ${o}`}function yu(t){try{return JSON.stringify(t)}catch{return String(t)}}import{existsSync as ba,rmSync as Cd}from"node:fs";import{join as yr}from"node:path";import{simpleGit as Td}from"simple-git";import"ws";import{createHash as wu}from"node:crypto";import{existsSync as ku,readFileSync as bu}from"node:fs";import{homedir as $u,hostname as Bo}from"node:os";import{join as xu}from"node:path";function Ri(t){return wu("sha256").update(t).digest("hex").slice(0,12)}function vu(){let t=L("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=xu($u(),".claude","credentials.json");if(!ku(e))return;let r=JSON.parse(bu(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 Ii(t){let e=vu(),r=L("ACCOUNT_ID")?.trim(),o=L("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=Ct(t);return n?{accountId:`acct-${Ri(n)}`,label:o||Bo(),...e?{email:e}:{}}:{accountId:`acct-${Ri(`host:${Bo()}`)}`,label:o||Bo(),...e?{email:e}:{}}}import{existsSync as Su}from"node:fs";import{join as Cu}from"node:path";import{simpleGit as Tu}from"simple-git";async function ji(t,e){if(!Su(Cu(t,".git")))return{status:"skipped"};let r=Tu(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${Ru(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 Ru(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Mo,readFileSync as Pi,readdirSync as Iu,watch as ju}from"node:fs";import{join as Go}from"node:path";var Wr=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(Mo(this.contextDir))try{this.watcher=ju(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=Go(this.contextDir,e);if(!Mo(r))return null;try{return Pi(r,"utf-8")}catch{return null}}readPrompts(){let e=Go(this.contextDir,"prompts"),r={};if(!Mo(e))return r;let o;try{o=Iu(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=Pi(Go(e,n),"utf-8")}catch{}}return r}};import{existsSync as Li,readFileSync as Di,readdirSync as Bu}from"node:fs";import{join as Bi}from"node:path";import{simpleGit as Mu}from"simple-git";import{existsSync as _u,mkdirSync as Ou,writeFileSync as _i}from"node:fs";import{dirname as Nu,isAbsolute as Uu,join as Ni,normalize as qo}from"node:path";import{simpleGit as Ui}from"simple-git";import{existsSync as We,mkdirSync as Ei,readFileSync as Fo,writeFileSync as It}from"node:fs";import{homedir as Pu}from"node:os";import{join as Ie}from"node:path";import{simpleGit as Eu}from"simple-git";var jt=["project.yaml","regimen.yaml"];function cr(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=Ie(t,n);We(s)||(It(s,i),r.push(n))}return r}function dt(t,e,r){let o=Ie(Pu(),".codepipe","profiles",t,"context-config");return Ei(o,{recursive:!0}),It(Ie(o,"project.yaml"),e.projectYaml),It(Ie(o,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${o}`),o}function qr(t,e,r){if(We(e))for(let o of jt){let n=Ie(e,o),i=Ie(t,o);if(!(!We(n)||We(i)))try{It(i,Fo(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 Au=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function Pt(t){let e=Ie(t,".gitignore"),r=We(e)?Fo(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(jt.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
11
+ `;hu(this.currentPath,r,"utf-8")}asWritable(){return new bu({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||!Ii(this.currentPath)||wu(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;Ii(o)&&(r>=this.cfg.maxFiles?ku(o):ji(o,`${this.currentPath}.${r+1}`))}ji(this.currentPath,`${this.currentPath}.1`)}}};function Kr(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=xu(process.env[`${t}_MAX_BYTES`]??String(Pi.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Pi.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function xu(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 Wr(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(vu(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 vu(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:Su(n)).join(" ");return`${r} ${t} ${o}`}function Su(t){try{return JSON.stringify(t)}catch{return String(t)}}import{existsSync as Sa,rmSync as Ad}from"node:fs";import{join as wr}from"node:path";import{simpleGit as _d}from"simple-git";import"ws";import{createHash as Cu}from"node:crypto";import{existsSync as Ru,readFileSync as Tu}from"node:fs";import{homedir as Iu,hostname as Mo}from"node:os";import{join as ju}from"node:path";function Ei(t){return Cu("sha256").update(t).digest("hex").slice(0,12)}function Pu(){let t=L("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=ju(Iu(),".claude","credentials.json");if(!Ru(e))return;let r=JSON.parse(Tu(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 Ai(t){let e=Pu(),r=L("ACCOUNT_ID")?.trim(),o=L("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=Rt(t);return n?{accountId:`acct-${Ei(n)}`,label:o||Mo(),...e?{email:e}:{}}:{accountId:`acct-${Ei(`host:${Mo()}`)}`,label:o||Mo(),...e?{email:e}:{}}}import{existsSync as Eu}from"node:fs";import{join as Au}from"node:path";import{simpleGit as _u}from"simple-git";async function _i(t,e){if(!Eu(Au(t,".git")))return{status:"skipped"};let r=_u(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${Ou(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 Ou(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Go,readFileSync as Oi,readdirSync as Nu,watch as Uu}from"node:fs";import{join as Fo}from"node:path";var qr=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(Go(this.contextDir))try{this.watcher=Uu(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=Fo(this.contextDir,e);if(!Go(r))return null;try{return Oi(r,"utf-8")}catch{return null}}readPrompts(){let e=Fo(this.contextDir,"prompts"),r={};if(!Go(e))return r;let o;try{o=Nu(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=Oi(Fo(e,n),"utf-8")}catch{}}return r}};import{existsSync as Gi,readFileSync as Fi,readdirSync as qu}from"node:fs";import{join as Hi}from"node:path";import{simpleGit as Yu}from"simple-git";import{existsSync as Mu,mkdirSync as Gu,writeFileSync as Li}from"node:fs";import{dirname as Fu,isAbsolute as Hu,join as Bi,normalize as Yo}from"node:path";import{simpleGit as Mi}from"simple-git";import{existsSync as Ye,mkdirSync as Ni,readFileSync as Ho,writeFileSync as jt}from"node:fs";import{homedir as Lu}from"node:os";import{join as Ie}from"node:path";import{simpleGit as Du}from"simple-git";var Pt=["project.yaml","regimen.yaml"];function lr(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=Ie(t,n);Ye(s)||(jt(s,i),r.push(n))}return r}function ft(t,e,r){let o=Ie(Lu(),".codepipe","profiles",t,"context-config");return Ni(o,{recursive:!0}),jt(Ie(o,"project.yaml"),e.projectYaml),jt(Ie(o,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${o}`),o}function Yr(t,e,r){if(Ye(e))for(let o of Pt){let n=Ie(e,o),i=Ie(t,o);if(!(!Ye(n)||Ye(i)))try{jt(i,Ho(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 Bu=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function Et(t){let e=Ie(t,".gitignore"),r=Ye(e)?Ho(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Pt.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
12
12
  `)?"":`
13
- `;return It(e,r+i+Au.join(`
13
+ `;return jt(e,r+i+Bu.join(`
14
14
  `)+`
15
- `),!0}async function Ai(t,e){try{if(!We(Ie(t,".git")))return;let r=Eu(t),o=(await r.raw(["ls-files","--",...jt])).split(`
16
- `).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;Pt(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 Wo(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 Ho(t){let e=new Map;for(let r of jt){let o=Ie(t,r);We(o)&&e.set(r,Fo(o))}return e}function Ko(t,e){Ei(t,{recursive:!0});for(let[r,o]of e){let n=Ie(t,r);We(n)||It(n,o)}}var Oi=3,Lu=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function Et(t,e,r){if(!_u(Ni(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=qe(t,i.path);Ou(Nu(s),{recursive:!0}),i.encoding==="base64"?_i(s,Buffer.from(i.content,"base64")):_i(s,i.content)}let o=Ui(t);await o.add(["-A","--","."]),await o.raw(["reset","-q","--",...jt]).catch(()=>{}),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await Wo(t))}async function Wo(t){let e=Ui(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=Oi;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 Du(e);if(i.length>0&&i.every(s=>Lu.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 ${Oi} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Du(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
- `).map(r=>r.trim()).filter(Boolean)}function qe(t,e){if(Uu(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=qo(Ni(t,e)),o=qo(t+"/");if(r!==qo(t)&&!r.startsWith(o))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Gu=/^(\d{4})-(.+)\.md$/,Fu="0000-template.md";function Hu(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 Ku(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
19
- `),a=s.findIndex(b=>b.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],f="",p=null,g=a>=0?a+1:0;for(let b=g;b<s.length;b++){let y=(s[b]??"").trim();if(y===""){g=b+1;continue}let w=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!w)break;let x=(w[1]??"").trim().toLowerCase(),O=(w[2]??"").trim(),j=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);j&&(p=parseInt(j[1]??"",10)),x==="tasks"&&(f=O),l.has(x)||u.push(y),g=b+1}let d=f?f.includes(o)?f:`${f}, ${o}`:o,h=s.slice(g).join(`
20
- `).replace(/^\n+/,""),S=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${n}`,`- **Tasks:** ${d}`,...u,"",h].join(`
15
+ `),!0}async function Ui(t,e){try{if(!Ye(Ie(t,".git")))return;let r=Du(t),o=(await r.raw(["ls-files","--",...Pt])).split(`
16
+ `).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;Et(t),await r.raw(["rm","--cached","--quiet","--",...o]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await qo(t),e.info(`[config] migrated ${o.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function Ko(t){let e=new Map;for(let r of Pt){let o=Ie(t,r);Ye(o)&&e.set(r,Ho(o))}return e}function Wo(t,e){Ni(t,{recursive:!0});for(let[r,o]of e){let n=Ie(t,r);Ye(n)||jt(n,o)}}var Di=3,Ku=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function At(t,e,r){if(!Mu(Bi(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Ve(t,i.path);Gu(Fu(s),{recursive:!0}),i.encoding==="base64"?Li(s,Buffer.from(i.content,"base64")):Li(s,i.content)}let o=Mi(t);await o.add(["-A","--","."]),await o.raw(["reset","-q","--",...Pt]).catch(()=>{}),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await qo(t))}async function qo(t){let e=Mi(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=Di;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 Wu(e);if(i.length>0&&i.every(s=>Ku.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 ${Di} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Wu(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
+ `).map(r=>r.trim()).filter(Boolean)}function Ve(t,e){if(Hu(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Yo(Bi(t,e)),o=Yo(t+"/");if(r!==Yo(t)&&!r.startsWith(o))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Vu=/^(\d{4})-(.+)\.md$/,zu="0000-template.md";function Ju(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 Xu(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
19
+ `),a=s.findIndex(b=>b.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],d="",p=null,g=a>=0?a+1:0;for(let b=g;b<s.length;b++){let y=(s[b]??"").trim();if(y===""){g=b+1;continue}let w=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!w)break;let x=(w[1]??"").trim().toLowerCase(),O=(w[2]??"").trim(),j=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);j&&(p=parseInt(j[1]??"",10)),x==="tasks"&&(d=O),l.has(x)||u.push(y),g=b+1}let f=d?d.includes(o)?d:`${d}, ${o}`:o,h=s.slice(g).join(`
20
+ `).replace(/^\n+/,""),S=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${n}`,`- **Tasks:** ${f}`,...u,"",h].join(`
21
21
  `);return{content:S.endsWith(`
22
22
  `)?S:S+`
23
- `,supersedes:p}}function Wu(t,e){let r=String(e).padStart(4,"0"),o=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return o===t?t.replace(/^(# .*)$/m,`$1
23
+ `,supersedes:p}}function Qu(t,e){let r=String(e).padStart(4,"0"),o=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return o===t?t.replace(/^(# .*)$/m,`$1
24
24
 
25
- - **Status:** superseded by ADR-${r}`):o}function qu(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((o,n)=>o.num-n.num)){let o=String(r.num).padStart(4,"0"),n=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${o} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${n}`)}return e.join(`
25
+ - **Status:** superseded by ADR-${r}`):o}function Zu(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 Mi(t,e,r,o=new Date().toISOString().slice(0,10)){try{await Mu(t).pull(void 0,void 0,["--rebase"])}catch{}let n=[],i=[];for(let d of r){let h=qe(t,`tasks/${e}/adr/DRAFT-${d}.md`);if(!Li(h)){i.push(d);continue}n.push({slug:d,content:Di(h,"utf-8")})}let s=Bi(t,"adr"),a=new Map;if(Li(s))for(let d of Bu(s)){let h=Gu.exec(d);!h||d===Fu||a.set(d,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:Di(Bi(s,d),"utf-8")})}let c=Math.max(0,...[...a.values()].map(d=>d.num))+1,l=new Map,u=[],f=[];for(let d of n){if([...a.entries()].find(([,x])=>x.slug===d.slug&&x.content.includes(e))){f.push(d.slug);continue}let S=c++,b=`${String(S).padStart(4,"0")}-${d.slug}.md`,{content:y,supersedes:w}=Ku(d.content,S,d.slug,e,o);if(l.set(b,y),a.set(b,{num:S,slug:d.slug,content:y}),u.push(`adr/${b}`),w!==null){let x=[...a.keys()].find(O=>O.startsWith(`${String(w).padStart(4,"0")}-`));if(x&&x!==b){let O=Wu(l.get(x)??a.get(x).content,S);l.set(x,O),a.set(x,{...a.get(x),content:O})}}}if(u.length===0)return{promoted:u,skipped:f,missing:i};let p=[...a.entries()].map(([d,h])=>({num:h.num,file:d,header:Hu(h.content)}));l.set("INDEX.md",qu(p));let g=[...l.entries()].map(([d,h])=>({path:`adr/${d}`,content:h}));return await Et(t,g,`adr(${e}): promote ${n.map(d=>d.slug).join(", ")}`),{promoted:u,skipped:f,missing:i}}import{existsSync as Gi,readFileSync as Vu}from"node:fs";import{join as Fi}from"node:path";function zu(t){for(let e of[Ce,ir]){let r=Fi(t,e);if(Gi(r))try{return Zn(Vu(r,"utf-8"))}catch{return 0}}return 0}function Ju(t,e,r,o=2){let n=e<o,i=n?ei(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function Yr(t,e){return Ju(e,zu(t),r=>Gi(Fi(t,r)))}import{existsSync as qi,mkdirSync as pp,mkdtempSync as dp,rmSync as Yi,writeFileSync as Vi}from"node:fs";import{tmpdir as fp}from"node:os";import{dirname as mp,join as zr}from"node:path";import{simpleGit as Xo}from"simple-git";var ft=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function Hi(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
28
- `+t.slice(t.length-e)}async function Ye(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 Vr(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 Ve(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 Xu(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 Xu(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ze(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 Wi(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 Yo=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 ft(`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()}`)}},Vo=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 ft(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let f of u.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let f of l.filter(p=>p.conclusion&&i.includes(p.conclusion))){let p=await fetch(`${n}/actions/runs/${f.id}/jobs?per_page=50`,{headers:o});if(!p.ok)continue;let g=(await p.json()).jobs??[];for(let d of g.filter(h=>h.conclusion==="failure")){let h=await fetch(`${n}/actions/jobs/${d.id}/logs`,{headers:o});if(!h.ok)continue;let S=await h.text();u.push(`### CI job: ${d.name}
27
+ `}async function Ki(t,e,r,o=new Date().toISOString().slice(0,10)){try{await Yu(t).pull(void 0,void 0,["--rebase"])}catch{}let n=[],i=[];for(let f of r){let h=Ve(t,`tasks/${e}/adr/DRAFT-${f}.md`);if(!Gi(h)){i.push(f);continue}n.push({slug:f,content:Fi(h,"utf-8")})}let s=Hi(t,"adr"),a=new Map;if(Gi(s))for(let f of qu(s)){let h=Vu.exec(f);!h||f===zu||a.set(f,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:Fi(Hi(s,f),"utf-8")})}let c=Math.max(0,...[...a.values()].map(f=>f.num))+1,l=new Map,u=[],d=[];for(let f of n){if([...a.entries()].find(([,x])=>x.slug===f.slug&&x.content.includes(e))){d.push(f.slug);continue}let S=c++,b=`${String(S).padStart(4,"0")}-${f.slug}.md`,{content:y,supersedes:w}=Xu(f.content,S,f.slug,e,o);if(l.set(b,y),a.set(b,{num:S,slug:f.slug,content:y}),u.push(`adr/${b}`),w!==null){let x=[...a.keys()].find(O=>O.startsWith(`${String(w).padStart(4,"0")}-`));if(x&&x!==b){let O=Qu(l.get(x)??a.get(x).content,S);l.set(x,O),a.set(x,{...a.get(x),content:O})}}}if(u.length===0)return{promoted:u,skipped:d,missing:i};let p=[...a.entries()].map(([f,h])=>({num:h.num,file:f,header:Ju(h.content)}));l.set("INDEX.md",Zu(p));let g=[...l.entries()].map(([f,h])=>({path:`adr/${f}`,content:h}));return await At(t,g,`adr(${e}): promote ${n.map(f=>f.slug).join(", ")}`),{promoted:u,skipped:d,missing:i}}import{existsSync as Wi,readFileSync as tp}from"node:fs";import{join as qi}from"node:path";function rp(t){for(let e of[Ce,sr]){let r=qi(t,e);if(Wi(r))try{return oi(tp(r,"utf-8"))}catch{return 0}}return 0}function op(t,e,r,o=2){let n=e<o,i=n?ni(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function Vr(t,e){return op(e,rp(t),r=>Wi(qi(t,r)))}import{existsSync as Ji,mkdirSync as wp,mkdtempSync as kp,rmSync as Xi,writeFileSync as Qi}from"node:fs";import{tmpdir as bp}from"node:os";import{dirname as $p,join as Jr}from"node:path";import{simpleGit as Qo}from"simple-git";var mt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function Yi(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
28
+ `+t.slice(t.length-e)}async function ze(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let i=(await o.json()).login??"ok",s=o.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(c.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function zr(t,e,r){let o=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,n;try{n=await fetch(o,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(n.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!n.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${n.status} ${n.statusText}`);if((await n.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function Je(t,e,r){let o=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",n;try{n=await fetch(o,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(n.ok)return t;if(n.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await np(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 np(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Xe(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(o){throw new Error(`cannot reach gitlab.com (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function zi(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 Vo=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!o.ok)throw new Error(`bitbucket pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.links?.html?.href??"",number:n.id}}async findOpenPrByBranch(e,r){let o=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${o}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let s=(await n.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let o=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(n.status===404)throw new mt(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,o,n){let i=o==="squash"?"squash":o==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:n})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:o}})});if(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!n.ok)throw new Error(`bitbucket decline PR #${r}: ${n.status} ${await n.text()}`)}},zo=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!o.ok)throw new Error(`github pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.html_url,number:n.number}}async findOpenPrByBranch(e,r){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let i=(await o.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let o=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(n.status===404)throw new mt(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let d of u.check_runs??[])l=!0,d.status!=="completed"?a=!0:d.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(d.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let d of l.filter(p=>p.conclusion&&i.includes(p.conclusion))){let p=await fetch(`${n}/actions/runs/${d.id}/jobs?per_page=50`,{headers:o});if(!p.ok)continue;let g=(await p.json()).jobs??[];for(let f of g.filter(h=>h.conclusion==="failure")){let h=await fetch(`${n}/actions/jobs/${f.id}/logs`,{headers:o});if(!h.ok)continue;let S=await h.text();u.push(`### CI job: ${f.name}
29
29
 
30
- ${Hi(S,8e3)}`)}}return u.length===0?void 0:Hi(u.join(`
30
+ ${Yi(S,8e3)}`)}}return u.length===0?void 0:Yi(u.join(`
31
31
 
32
- `),16e3)}catch{return}}async mergePR(e,r,o,n){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:o})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(n){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!n.ok)throw new Error(`github close PR #${r}: ${n.status} ${await n.text()}`)}},zo=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 ft(`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=Qu(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,o,n){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:o==="squash",should_remove_source_branch:n,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!n.ok)throw new Error(`gitlab close MR !${r}: ${n.status} ${await n.text()}`)}};function Qu(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 Jo=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(Ki(e,r,"merge"))}async closePR(e,r,o){throw new Error(Ki(e,r,"close"))}};function Ki(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 Le(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Vo(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Yo(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new zo(e)}return new Jo}function At(t,e,r,o){return[{path:"README.md",content:cp(t,e)},{path:".gitignore",content:op()},{path:"CLAUDE.md",content:ip(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:np()},{path:"knowledge/README.md",content:sp()},{path:"knowledge/build.yaml",content:ap()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:rp()},{path:"adr/README.md",content:Zu()},{path:"adr/0000-template.md",content:ep()},{path:"adr/INDEX.md",content:tp()},{path:Ce,content:Or()}]}function Zu(){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()}`)}},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 mt(`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=ip(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,o,n){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:o==="squash",should_remove_source_branch:n,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!n.ok)throw new Error(`gitlab close MR !${r}: ${n.status} ${await n.text()}`)}};function ip(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 Xo=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(Vi(e,r,"merge"))}async closePR(e,r,o){throw new Error(Vi(e,r,"close"))}};function Vi(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 Be(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new zo(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Vo(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Jo(e)}return new Xo}function _t(t,e,r,o){return[{path:"README.md",content:gp(t,e)},{path:".gitignore",content:up()},{path:"CLAUDE.md",content:dp(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:pp()},{path:"knowledge/README.md",content:fp()},{path:"knowledge/build.yaml",content:mp()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:lp()},{path:"adr/README.md",content:sp()},{path:"adr/0000-template.md",content:ap()},{path:"adr/INDEX.md",content:cp()},{path:Ce,content:Nr()}]}function sp(){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 ep(){return`# ADR-NNNN: <title>
60
+ `}function ap(){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 tp(){return`# ADR index
82
+ `}function cp(){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 rp(){return`# Audit
87
+ `}function lp(){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 je(t,e,r,o){return{projectYaml:lp(t,r,o),regimenYaml:up(t.automationLevel,e)}}function op(){return`# codepipe project config is local to each member's workspace
96
+ `}function je(t,e,r,o){return{projectYaml:hp(t,r,o),regimenYaml:yp(t.automationLevel,e)}}function up(){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 np(){return`# Index prompt
103
+ `}function pp(){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 ip(t){return`# Project context for the CodePipe agent
160
+ `}function dp(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 sp(){return`# Knowledge
188
+ `}function fp(){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 ap(){return`# BUILD phase config. Discovered & maintained by the agent.
205
+ `}function mp(){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 cp(t,e){return`# ${e.name}
221
+ `}function gp(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 lp(t,e,r){let o=e?`
247
+ `}function hp(t,e,r){let o=e?`
248
248
  tracker_url: ${e}`:`
249
249
  # tracker_url: https://your.youtrack.cloud`,n=r?`require_assignee: true
250
250
  assignee: ${r}`:`require_assignee: false
@@ -310,7 +310,7 @@ branch:
310
310
 
311
311
  repos:
312
312
  ${s}
313
- `}function up(t,e){let r=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
313
+ `}function yp(t,e){let r=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
314
314
  automation:
315
315
  level: ${t}
316
316
 
@@ -425,32 +425,32 @@ parallelism:
425
425
  # # the previous task's branch (auto-merge without reworking the
426
426
  # # tail of the chain).
427
427
  # mode: parallel
428
- `}function gp(t){return`codepipe/context-migration-v${t}`}function hp(t){let e=ti(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 \`${Ce}\` stamp (renamed from \`${ir}\``,"when the legacy file is present). Hand-edited files are never touched.","","## Format changes",""];for(let o of e){r.push(`- **v${o.version}** \u2014 ${o.summary}`);for(let n of o.addedPaths)r.push(` - \`${n}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
429
- `)}async function zi(t,e,r,o){let n=Xo(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Yr(t,e);if(!i.outdated)return i;let s=gp(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 yp(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=Le(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return o.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let f=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:hp(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 yp(t,e,r,o,n,i,s){let a=Xo(t),c=dp(zr(fp(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",n,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map(At(l,u).map(h=>[h.path,h.content])),p=0;for(let h of o.missingPaths){if(h===Ce)continue;let S=f.get(h);if(S==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let b=zr(c,h);qi(b)||(pp(mp(b),{recursive:!0}),Vi(b,S),p++)}Vi(zr(c,Ce),Or(o.currentVersion)),p++;let g=zr(c,ir);qi(g)&&(Yi(g,{force:!0}),p++);let d=Xo(c);await d.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await d.commit(`chore(context): migrate format v${o.templateVersion} -> v${o.currentVersion}`),await d.push(["-u","origin",n]),s.info(`[ctx] migration branch ${n} pushed (${p} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Yi(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{existsSync as wp,readFileSync as kp,writeFileSync as bp}from"node:fs";import{homedir as $p}from"node:os";import{join as Ji}from"node:path";import{parseDocument as xp}from"yaml";function vp(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function Sp(t,e){let r=xp(t);return r.set("repos",e.map(vp)),r.toString()}function Cp(t,e){let r=[Ji($p(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Ji(e,"project.yaml")),r}function lr(t,e,r){let o=[],n=[];for(let i of Cp(t,r))if(wp(i))try{let s=kp(i,"utf-8"),a=Sp(s,e);a!==s&&(bp(i,a),o.push(i))}catch(s){n.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:o,errors:n}}import{homedir as Tp}from"node:os";import{existsSync as Rp,mkdirSync as Ip}from"node:fs";import{join as Qo}from"node:path";import{simpleGit as Zi}from"simple-git";var Xi=t=>console.log(t);function Qi(t){Xi=t}function ur(t,e="info"){Xi(t,e)}function ke(t,e,r){let o=r??Qo(Tp(),".codepipe","repos");return Qo(o,t,e)}async function Jr(t,e,r={}){let o=ke(t,e.name,r.baseDir),n=r.cloneUrlOverride??Zo(e);if(!Rp(Qo(o,".git"))){Ip(o,{recursive:!0});let a=Zi();ur(`[git] clone ${n} \u2192 ${o}`);try{await a.clone(n,o)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${n}
430
- ${l.trim()}`)}}let i=Zi(o);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${o}
431
- ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function pr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var es=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function Xr(t,e){let{contextRepoCloneUrl:r,deliveryRef:o,deliverySha:n,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${o}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();n&&a!==n&&ur(`[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 pr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await pr(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([...es,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function ts(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await pr(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await pr(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 rs(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:f}=r,p=await ts(t,i,()=>Xr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let g=`origin/${c}`;if(await pr(t,g)||(g=`origin/${u??c}`),(await t.revparse([g])).trim()===s)await t.raw(["branch","-f",a,p]),await t.checkout(a);else{await t.checkout(["-B",a,g]);try{await t.raw([...es,"cherry-pick",p])}catch(b){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=b instanceof Error?b.message:String(b);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
432
- ${y.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),S=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(S),await t.push([o,"--delete",n]).catch(()=>{}),{commit:h}}async function os(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await ts(t,i,()=>Xr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function ns(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 Zo(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{createCipheriv as jp,createDecipheriv as Pp,createHash as Ep,createPrivateKey as Ap,createPublicKey as en,diffieHellman as is,generateKeyPairSync as ss,hkdfSync as as,randomBytes as _p}from"node:crypto";var cs=Buffer.from("devpipe-sealedbox-v1","utf-8");function Qr(){let{publicKey:t,privateKey:e}=ss("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Pe(t){let e=Buffer.from(t,"base64");return(Ep("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function _t(t,e){let r=en({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=ss("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=is({privateKey:n,publicKey:r}),c=Buffer.from(as("sha256",a,Buffer.concat([i,s]),cs,32)),l=_p(12),u=jp("aes-256-gcm",c,l),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,p=Buffer.concat([u.update(f),u.final()]),g=u.getAuthTag(),d={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:g.toString("base64"),ct:p.toString("base64")};return Buffer.from(JSON.stringify(d),"utf-8").toString("base64")}function Zr(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=Ap({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=en({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=en(o).export({type:"spki",format:"der"}),a=is({privateKey:o,publicKey:n}),c=Buffer.from(as("sha256",a,Buffer.concat([i,s]),cs,32)),l=Pp("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 Op(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 ls(t,e,r,o){let n=Op(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=Gr(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=_t(a.publicKey,i)}catch(u){o.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}import{X509Certificate as ds}from"node:crypto";import{readFileSync as Np}from"node:fs";import Je from"node:tls";var fs=typeof Je.getCACertificates=="function"&&typeof Je.setDefaultCACertificates=="function",us=!1,ps=new Map,ms=t=>console.warn(t);function Up(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function gs(t=ms){if(us)return;us=!0;let e=L("EXTRA_CA_FILE");if(!(!e||!fs))try{let r=Up(Np(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Je.setDefaultCACertificates([...Je.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 hs(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 Lp(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
433
- `)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function Dp(t,e,r){return new Promise((o,n)=>{let i=Je.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 ds(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function tn(t,e,r){return new Promise(o=>{let n=Je.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 Bp(t){try{let e=await fetch(t);return e.ok?new ds(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function ys(t,e=443,r=ms){let o=`${t}:${e}`,n=ps.get(o);if(n)return n;let i=Mp(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return ps.set(o,i),i}async function Mp(t,e,r){if(!fs)return!1;let o=8e3;if(await tn(t,e,o))return!0;let n=await Dp(t,e,o),i=Je.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=Lp(n);if(!c)break;let l=await Bp(c);if(!l)break;if(s.push(l.toString()),Je.setDefaultCACertificates([...i,...s]),await tn(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 tn(t,e,o)}function De(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function me(t,e,r){gs();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(hs(s)&&await ys(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var ws=t=>new Promise(e=>setTimeout(e,t));function Gp(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Fp(){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 $s(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=Fp(),a=null;for(let c=1;c<=n;c++){let l=null;try{l=await me(t,r,o)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<n&&Gp(l.status,u)){await ws(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<n){await ws(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Xe(t){let e;try{e=await me(t,"/api/users/me?fields=login,fullName")}catch(o){throw new Error(`cannot reach ${t.baseUrl} (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function xs(t){try{let e=await me(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var dr="Stage",ks=new Map;async function Hp(t,e,r,o){let n=`${e.split("-")[0]}:${o}:${r}`,i=ks.get(n);if(i)return i;let s=await me(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===o);if(!c)throw new Error(`yt: issue ${e} has no ${o} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${o} bundle for ${e}`);return ks.set(n,l.id),l.id}async function vs(t,e,r,o=dr){let n=await Hp(t,e,r,o);await $s(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:o,$type:"StateIssueCustomField",value:{id:n,$type:"StateBundleElement"}}]})})}async function Ss(t,e,r){return await(await $s(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var bs=new Map;async function Cs(t,e){let r=bs.get(e);if(r)return r;let o=await me(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!o.ok)throw new Error(`yt resolveProjectId: ${o.status} ${await o.text()}`);let i=(await o.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return bs.set(e,i.id),i.id}async function Ts(t,e,r,o,n,i=dr){let s=await Cs(t,e),a=await me(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:o,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:n,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Rs(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await me(t,"/api/commands",{method:"POST",body:JSON.stringify({query:n,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${n} on ${e}): ${i.status} ${await i.text()}`)}var Is="attachments(id,name,url,size,mimeType)",Kp="links(direction,linkType(name),issues(idReadable))",js=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Is},${Kp}`,Wp=`id,text,created,author(login),${Is}`;function Ps(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 Es(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 As(t,e){let r=e.stageField??dr,o=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");o.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);o.push(`updated: ${c} .. *`)}e.assignee?o.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&o.push("has: Assignee");let n=o.join(" "),i=`/api/issues?query=${encodeURIComponent(n)}&fields=${js}&$top=200`,s=await me(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Ns(c,r))}async function _s(t,e,r=dr){let o=`/api/issues/${encodeURIComponent(e)}?fields=${js}`,n=await me(t,o);if(n.status===404)return null;if(!n.ok)throw new Error(`yt getIssue ${e}: ${n.status} ${await n.text()}`);return Ns(await n.json(),r)}async function Os(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Wp}&$top=500`,n=await me(t,o);if(!n.ok)throw new Error(`yt listComments ${e}: ${n.status} ${await n.text()}`);return(await n.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Ps(s.attachments);return c&&(a.attachments=c),a})}function qp(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 Ns(t,e=dr){let r=t.customFields??[],o=r.find(l=>l.name===e),n=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:o?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),n?.value?.login&&(s.assignee=n.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Ps(t.attachments);a&&(s.attachments=a);let c=qp(t.links);return c&&(s.links=c),s}async function Us(t,e){let r=await Yp(t,e);return r.length>0?r:Vp(t,e)}async function Yp(t,e){let r=await Cs(t,e),o=await me(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!o.ok)return[];let n=await o.json(),i=[];for(let s of n)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:Ls(s.bundle)});return i}async function Vp(t,e){let r=`project: ${e}`,o=await me(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!o.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${o.status} ${await o.text()}`);let n=await o.json(),i=[];for(let s of n[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:Ls(s.projectCustomField?.bundle)});return i}function Ls(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function be(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Ds(t,e){let r=U(t),o=[],n=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Xe({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:be(c)}),n.push({kind:"youtrack",present:!0,ok:!1,detail:be(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 Ye(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:be(c)}),n.push({kind:"github",present:!0,ok:!1,detail:be(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 Ve(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:be(c)}),n.push({kind:"bitbucket",present:!0,ok:!1,detail:be(c),checkedAt:i()})}}else n.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await ze(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:be(c)}),n.push({kind:"gitlab",present:!0,ok:!1,detail:be(c),checkedAt:i()})}}else n.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await Vr(c,u.owner,u.repoName),o.push({name:`repo:${u.name}`,ok:!0})}catch(f){o.push({name:`repo:${u.name}`,ok:!1,detail:be(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Vr(c,l.owner,l.name),o.push({name:"context-repo",ok:!0})}catch(u){o.push({name:"context-repo",ok:!1,detail:be(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Vr(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:be(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=Ct(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 rn(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 rn(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 fr(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 mr(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 gr(t,e=process.env){if(!t)return!1;let r=`https://${ut}:${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 on(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 Bs(t,e=process.env){return on(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>fr(t,e),e)}function Ms(t,e=process.env){return on(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>mr(t,e),e)}function Gs(t,e=process.env){return on(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${ut}:${encodeURIComponent(t)}@bitbucket.org/`,()=>gr(t,e),e)}function Fs(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=Qr();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},K(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Pe(e.sealKey.publicKey)}}async function Hs(t,e,r,o){let n;try{n=JSON.parse(Zr(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 Ye(n.token);return i.github={token:n.token},Ot(i,()=>{process.env.GH_TOKEN=n.token,Bs(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await ze(n.token);return i.gitlab={token:n.token},Ot(i,()=>{process.env.GITLAB_TOKEN=n.token,Ms(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 Ve(n.email,n.apiToken);return i.bitbucket={email:n.email,apiToken:n.apiToken},Ot(i,()=>{process.env.BITBUCKET_EMAIL=n.email,process.env.BITBUCKET_API_TOKEN=n.apiToken,Gs(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 Xe({baseUrl:s,token:n.token});return i.youtrack={url:s,token:n.token},Ot(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 rn(n.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:n.token},Ot(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return n.token?(i.contextWrite={token:n.token},Ot(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 Ot(t,e){K(t),e()}import{existsSync as zp,readFileSync as Jp,statSync as Ks}from"node:fs";var Ws=2*1024*1024;function Xp(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function qs(t,e){let r=qe(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!zp(r)||!Ks(r).isFile())throw new Error(`file not found: ${e}`);let{size:o}=Ks(r);if(o>Ws)throw new Error(`file too large: ${e} is ${o} bytes (limit ${Ws})`);let n=Jp(r);return Xp(n)?{content:n.toString("utf-8"),encoding:"utf8",sizeBytes:n.length}:{content:n.toString("base64"),encoding:"base64",sizeBytes:n.length}}import{existsSync as Qp,readFileSync as Zp,writeFileSync as ed}from"node:fs";import{join as td}from"node:path";import{parseDocument as rd}from"yaml";var Ys=64;async function Vs(t,e){if(!Number.isInteger(e)||e<1||e>Ys)throw new Error(`maxJobs must be an integer in [1, ${Ys}], got ${e}`);let r=td(t,"regimen.yaml");if(!Qp(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=rd(Zp(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),ed(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as nn,readFileSync as sn,writeFileSync as od}from"node:fs";import{join as eo}from"node:path";import{parseDocument as an}from"yaml";async function zs(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=eo(t,"project.yaml");if(!nn(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=an(sn(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=eo(t,"regimen.yaml");if(!nn(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=an(sn(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)od(eo(t,i.path),i.content);return{files:r.map(i=>i.path)}}function cn(t){if(!t)return"Stage";try{let e=eo(t,"project.yaml");if(!nn(e))return"Stage";let o=an(sn(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof o=="string"&&o.trim().length>0?o.trim():"Stage"}catch{return"Stage"}}var to=new Map;async function ln(t,e){let o=(to.get(t)??Promise.resolve()).catch(()=>{}).then(e);to.set(t,o);try{return await o}finally{to.get(t)===o&&to.delete(t)}}async function Js(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;ur(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await Jr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ke(i,r.name,t.baseDir),{commit:c}=await rs(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 oe({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 q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await Jr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ke(i,r.name,t.baseDir),{commit:c,pushed:l}=await os(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return oe({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return q("no repo spec");let i=Le(r),s=await i.createPullRequest(r,e);return oe({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return q("no repo spec");let i=Le(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return oe({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return q("no repo spec");let i=Le(r);return await i.closePR(r,e.prNumber,e.comment),oe({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await Jr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ke(i,r.name,t.baseDir),{mergedSha:c}=await ns(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return oe({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return oe({stub:!0});case"tracker_status":{let i=De();return i?t.trackerIssueId?(await vs(i,t.trackerIssueId,e.newStatus,cn(t.contextDir)),oe({issueId:t.trackerIssueId,newStatus:e.newStatus})):q("no tracker_issue_id provided"):q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=De();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return q("no tracker_issue_id provided");let s=await Ss(i,t.trackerIssueId,e.body);return oe({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=De();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return q("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Ts(i,e.projectKey,e.title,e.body,e.targetStatus,cn(t.contextDir));return oe({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=De();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Rs(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return q(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return oe({applied:s})}case"set_parallelism":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await Vs(t.contextDir,e.maxJobs);return oe({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await zs(t.contextDir,e);return oe({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),oe({reported:!0})):q("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return q("no context repo clone on this CLI");let i=await t.refreshContextStatus();return oe({outdated:i.outdated,templateVersion:i.templateVersion})}case"read_context_file":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=qs(t.contextDir,e.path);return oe({path:e.path,...i})}default:return q(`unsupported action type: ${e.type}`)}}catch(i){return q(i instanceof Error?i.message:String(i))}}function oe(t){return{status:"done",result:t}}function q(t){return{status:"failed",error:t}}import{existsSync as pa,readFileSync as da}from"node:fs";import{join as fa}from"node:path";import{homedir as nd}from"node:os";import{existsSync as id,mkdirSync as sd,readFileSync as ad,writeFileSync as cd}from"node:fs";import{dirname as ld,join as ud}from"node:path";function un(){return L("FARM_PINS")??ud(nd(),".codepipe","farm-pins.json")}function Xs(){let t=un();if(!id(t))return{};try{return JSON.parse(ad(t,"utf-8"))}catch{return{}}}function pd(t){let e=un();sd(ld(e),{recursive:!0}),cd(e,JSON.stringify(t,null,2)+`
434
- `,{mode:384})}function dd(t){return Xs()[t]}function ro(t,e){let r=Xs();r[t]=e,pd(r)}function oo(t,e){let r=Pe(e),o=dd(t);if(o&&o!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${o}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${un()}.`);return r}import fd from"ws";function no(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new fd(r)}var A=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function Qe(t,e,r){return Be(t,e,"/projects",r)}async function Qs(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 io(t,e,r,o){return Be(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function Zs(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new A(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function so(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 ea(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 hr=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function ta(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 hr(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function ra(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 oa(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 na(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 ia(t,e,r,o){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function sa(t,e,r,o,n){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function aa(t,e,r,o,n){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function ca(t,e,r,o,n){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function ao(t,e,r,o){return Be(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function pn(t,e,r,o){await Be(t,e,`/projects/${encodeURIComponent(r)}/init-status`,o)}async function la(t,e,r,o){return Be(t,e,`/projects/${encodeURIComponent(r)}/repos`,o)}async function ua(t,e,r,o){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(o)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}async function G(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function Be(t,e,r,o){let n=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}async function ma(t,e,r,o){let n=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return n(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=Pe(e.farmPublicKey);if(i!==e.fingerprint)return n("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");oo(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 G(t.hubUrl,t.cliToken,t.projectId),c;if(r){let p=fa(r,"project.yaml"),g=fa(r,"regimen.yaml");pa(p)&&pa(g)?c={projectYaml:da(p,"utf-8"),regimenYaml:da(g,"utf-8")}:o.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=_t(e.farmPublicKey,JSON.stringify(l));ro(e.farmId,i),o.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await io(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:n(f.error??"farm provisioning failed")}catch(i){return n(i instanceof Error?i.message:String(i))}}var co=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=Le(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 ft){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=Le(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=md(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function md(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}import{existsSync as ga,readFileSync as gd,readdirSync as hd}from"node:fs";function yd(t,e,r){let o=[];for(let n of r){let i=n.issue.key,s=$d(t,i,n.attachments);o.push({path:`tasks/${i}/task.md`,content:wd(n.issue,e,s)}),o.push({path:`tasks/${i}/comments.jsonl`,content:bd(kd(t,i,n.comments))});for(let a of n.attachments)o.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return o}async function ha(t,e,r){if(r.length===0)return;let o=yd(t,e,r),n=r.map(i=>i.issue.key);await Et(t,o,`sync(${n.join(", ")}): task data`)}function wd(t,e,r){let o=new Date(t.updatedAt).toISOString(),n=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${o}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){n.push("## Attachments","");for(let i of r)n.push(`- [${i}](attachments/${encodeURI(i)})`);n.push("")}return n.join(`
435
- `)}function kd(t,e,r){let o=new Map,n=qe(t,`tasks/${e}/comments.jsonl`);if(ga(n))for(let i of gd(n,"utf-8").split(`
436
- `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&o.set(a.id,a)}catch{}}for(let i of r){let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Nr(i.body);a&&(s.parsedCommand=a),o.set(i.id,s)}return[...o.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function bd(t){return t.map(e=>JSON.stringify(e)).join(`
428
+ `}function xp(t){return`codepipe/context-migration-v${t}`}function vp(t){let e=ii(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 \`${Ce}\` stamp (renamed from \`${sr}\``,"when the legacy file is present). Hand-edited files are never touched.","","## Format changes",""];for(let o of e){r.push(`- **v${o.version}** \u2014 ${o.summary}`);for(let n of o.addedPaths)r.push(` - \`${n}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
429
+ `)}async function Zi(t,e,r,o){let n=Qo(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Vr(t,e);if(!i.outdated)return i;let s=xp(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 Sp(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=Be(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return o.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let d=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:vp(i)});return o.info(`[ctx] migration PR opened: ${d.url}`),{...i,migrationPrUrl:d.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 Sp(t,e,r,o,n,i,s){let a=Qo(t),c=kp(Jr(bp(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",n,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},d=new Map(_t(l,u).map(h=>[h.path,h.content])),p=0;for(let h of o.missingPaths){if(h===Ce)continue;let S=d.get(h);if(S==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let b=Jr(c,h);Ji(b)||(wp($p(b),{recursive:!0}),Qi(b,S),p++)}Qi(Jr(c,Ce),Nr(o.currentVersion)),p++;let g=Jr(c,sr);Ji(g)&&(Xi(g,{force:!0}),p++);let f=Qo(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${o.templateVersion} -> v${o.currentVersion}`),await f.push(["-u","origin",n]),s.info(`[ctx] migration branch ${n} pushed (${p} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Xi(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{existsSync as Cp,readFileSync as Rp,writeFileSync as Tp}from"node:fs";import{homedir as Ip}from"node:os";import{join as es}from"node:path";import{parseDocument as jp}from"yaml";function Pp(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function Ep(t,e){let r=jp(t);return r.set("repos",e.map(Pp)),r.toString()}function Ap(t,e){let r=[es(Ip(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(es(e,"project.yaml")),r}function ur(t,e,r){let o=[],n=[];for(let i of Ap(t,r))if(Cp(i))try{let s=Rp(i,"utf-8"),a=Ep(s,e);a!==s&&(Tp(i,a),o.push(i))}catch(s){n.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:o,errors:n}}import{homedir as _p}from"node:os";import{existsSync as Op,mkdirSync as Np}from"node:fs";import{join as Zo}from"node:path";import{simpleGit as os}from"simple-git";var ts=t=>console.log(t);function rs(t){ts=t}function pr(t,e="info"){ts(t,e)}function ke(t,e,r){let o=r??Zo(_p(),".codepipe","repos");return Zo(o,t,e)}async function Xr(t,e,r={}){let o=ke(t,e.name,r.baseDir),n=r.cloneUrlOverride??en(e);if(!Op(Zo(o,".git"))){Np(o,{recursive:!0});let a=os();pr(`[git] clone ${n} \u2192 ${o}`);try{await a.clone(n,o)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${n}
430
+ ${l.trim()}`)}}let i=os(o);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${o}
431
+ ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function dr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var ns=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function Qr(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&&pr(`[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 dr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await dr(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([...ns,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function is(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await dr(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await dr(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 ss(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:d}=r,p=await is(t,i,()=>Qr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:l}));d&&await t.raw(["branch","-D",a]).catch(()=>{});let g=`origin/${c}`;if(await dr(t,g)||(g=`origin/${u??c}`),(await t.revparse([g])).trim()===s)await t.raw(["branch","-f",a,p]),await t.checkout(a);else{await t.checkout(["-B",a,g]);try{await t.raw([...ns,"cherry-pick",p])}catch(b){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=b instanceof Error?b.message:String(b);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
432
+ ${y.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),S=d?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(S),await t.push([o,"--delete",n]).catch(()=>{}),{commit:h}}async function as(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await is(t,i,()=>Qr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function cs(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 en(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{createCipheriv as Up,createDecipheriv as Lp,createHash as Dp,createPrivateKey as Bp,createPublicKey as tn,diffieHellman as ls,generateKeyPairSync as us,hkdfSync as ps,randomBytes as Mp}from"node:crypto";var ds=Buffer.from("devpipe-sealedbox-v1","utf-8");function Zr(){let{publicKey:t,privateKey:e}=us("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Pe(t){let e=Buffer.from(t,"base64");return(Dp("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Ot(t,e){let r=tn({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=us("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=ls({privateKey:n,publicKey:r}),c=Buffer.from(ps("sha256",a,Buffer.concat([i,s]),ds,32)),l=Mp(12),u=Up("aes-256-gcm",c,l),d=typeof e=="string"?Buffer.from(e,"utf-8"):e,p=Buffer.concat([u.update(d),u.final()]),g=u.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:g.toString("base64"),ct:p.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function eo(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=Bp({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=tn({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=tn(o).export({type:"spki",format:"der"}),a=ls({privateKey:o,publicKey:n}),c=Buffer.from(ps("sha256",a,Buffer.concat([i,s]),ds,32)),l=Lp("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 Gp(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 fs(t,e,r,o){let n=Gp(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=Fr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){o.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&o.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=Ot(a.publicKey,i)}catch(u){o.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}import{X509Certificate as hs}from"node:crypto";import{readFileSync as Fp}from"node:fs";import Qe from"node:tls";var ys=typeof Qe.getCACertificates=="function"&&typeof Qe.setDefaultCACertificates=="function",ms=!1,gs=new Map,ws=t=>console.warn(t);function Hp(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function ks(t=ws){if(ms)return;ms=!0;let e=L("EXTRA_CA_FILE");if(!(!e||!ys))try{let r=Hp(Fp(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Qe.setDefaultCACertificates([...Qe.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function bs(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 Kp(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
433
+ `)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function Wp(t,e,r){return new Promise((o,n)=>{let i=Qe.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new hs(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function rn(t,e,r){return new Promise(o=>{let n=Qe.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{n.end(),o(!0)});n.on("error",()=>o(!1)),n.setTimeout(r,()=>{n.destroy(),o(!1)})})}async function qp(t){try{let e=await fetch(t);return e.ok?new hs(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function $s(t,e=443,r=ws){let o=`${t}:${e}`,n=gs.get(o);if(n)return n;let i=Yp(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return gs.set(o,i),i}async function Yp(t,e,r){if(!ys)return!1;let o=8e3;if(await rn(t,e,o))return!0;let n=await Wp(t,e,o),i=Qe.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=Kp(n);if(!c)break;let l=await qp(c);if(!l)break;if(s.push(l.toString()),Qe.setDefaultCACertificates([...i,...s]),await rn(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 rn(t,e,o)}function Me(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function he(t,e,r){ks();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(bs(s)&&await $s(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var xs=t=>new Promise(e=>setTimeout(e,t));function Vp(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function zp(){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 Cs(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=zp(),a=null;for(let c=1;c<=n;c++){let l=null;try{l=await he(t,r,o)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<n&&Vp(l.status,u)){await xs(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<n){await xs(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Ze(t){let e;try{e=await he(t,"/api/users/me?fields=login,fullName")}catch(o){throw new Error(`cannot reach ${t.baseUrl} (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Rs(t){try{let e=await he(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var fr="Stage",vs=new Map;async function Jp(t,e,r,o){let n=`${e.split("-")[0]}:${o}:${r}`,i=vs.get(n);if(i)return i;let s=await he(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===o);if(!c)throw new Error(`yt: issue ${e} has no ${o} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${o} bundle for ${e}`);return vs.set(n,l.id),l.id}async function Ts(t,e,r,o=fr){let n=await Jp(t,e,r,o);await Cs(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:o,$type:"StateIssueCustomField",value:{id:n,$type:"StateBundleElement"}}]})})}async function Is(t,e,r){return await(await Cs(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Ss=new Map;async function js(t,e){let r=Ss.get(e);if(r)return r;let o=await he(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!o.ok)throw new Error(`yt resolveProjectId: ${o.status} ${await o.text()}`);let i=(await o.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Ss.set(e,i.id),i.id}async function Ps(t,e,r,o,n,i=fr){let s=await js(t,e),a=await he(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:o,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:n,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Es(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await he(t,"/api/commands",{method:"POST",body:JSON.stringify({query:n,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${n} on ${e}): ${i.status} ${await i.text()}`)}var As="attachments(id,name,url,size,mimeType)",Xp="links(direction,linkType(name),issues(idReadable))",_s=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${As},${Xp}`,Qp=`id,text,created,author(login),${As}`;function Os(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 Ns(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 Us(t,e){let r=e.stageField??fr,o=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");o.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);o.push(`updated: ${c} .. *`)}e.assignee?o.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&o.push("has: Assignee");let n=o.join(" "),i=`/api/issues?query=${encodeURIComponent(n)}&fields=${_s}&$top=200`,s=await he(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Bs(c,r))}async function Ls(t,e,r=fr){let o=`/api/issues/${encodeURIComponent(e)}?fields=${_s}`,n=await he(t,o);if(n.status===404)return null;if(!n.ok)throw new Error(`yt getIssue ${e}: ${n.status} ${await n.text()}`);return Bs(await n.json(),r)}async function Ds(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Qp}&$top=500`,n=await he(t,o);if(!n.ok)throw new Error(`yt listComments ${e}: ${n.status} ${await n.text()}`);return(await n.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Os(s.attachments);return c&&(a.attachments=c),a})}function Zp(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 Bs(t,e=fr){let r=t.customFields??[],o=r.find(l=>l.name===e),n=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:o?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),n?.value?.login&&(s.assignee=n.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Os(t.attachments);a&&(s.attachments=a);let c=Zp(t.links);return c&&(s.links=c),s}async function Ms(t,e){let r=await ed(t,e);return r.length>0?r:td(t,e)}async function ed(t,e){let r=await js(t,e),o=await he(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!o.ok)return[];let n=await o.json(),i=[];for(let s of n)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:Gs(s.bundle)});return i}async function td(t,e){let r=`project: ${e}`,o=await he(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!o.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${o.status} ${await o.text()}`);let n=await o.json(),i=[];for(let s of n[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:Gs(s.projectCustomField?.bundle)});return i}function Gs(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function be(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Fs(t,e){let r=U(t),o=[],n=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Ze({baseUrl:r.youtrack.url,token:r.youtrack.token});o.push({name:"youtrack",ok:!0}),n.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"youtrack",ok:!1,detail:be(c)}),n.push({kind:"youtrack",present:!0,ok:!1,detail:be(c),checkedAt:i()})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),n.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await ze(r.github.token);o.push({name:"github",ok:!0}),n.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"github",ok:!1,detail:be(c)}),n.push({kind:"github",present:!0,ok:!1,detail:be(c),checkedAt:i()})}}else n.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Je(r.bitbucket.email,r.bitbucket.apiToken);o.push({name:"bitbucket",ok:!0}),n.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"bitbucket",ok:!1,detail:be(c)}),n.push({kind:"bitbucket",present:!0,ok:!1,detail:be(c),checkedAt:i()})}}else n.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Xe(r.gitlab.token);o.push({name:"gitlab",ok:!0}),n.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"gitlab",ok:!1,detail:be(c)}),n.push({kind:"gitlab",present:!0,ok:!1,detail:be(c),checkedAt:i()})}}else n.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await zr(c,u.owner,u.repoName),o.push({name:`repo:${u.name}`,ok:!0})}catch(d){o.push({name:`repo:${u.name}`,ok:!1,detail:be(d)})}let l=e?.contextRepo;if(l?.host==="github")try{await zr(c,l.owner,l.name),o.push({name:"context-repo",ok:!0})}catch(u){o.push({name:"context-repo",ok:!1,detail:be(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await zr(r.contextWrite.token,c.owner,c.name),n.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){n.push({kind:"contextWrite",present:!0,ok:!1,detail:be(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=Rt(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 on(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 on(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function mr(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@github.com:"),n(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function gr(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@gitlab.com:"),n(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function hr(t,e=process.env){if(!t)return!1;let r=`https://${pt}:${encodeURIComponent(t)}@bitbucket.org/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@bitbucket.org:"),n(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function nn(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 Hs(t,e=process.env){return nn(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>mr(t,e),e)}function Ks(t,e=process.env){return nn(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>gr(t,e),e)}function Ws(t,e=process.env){return nn(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${pt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>hr(t,e),e)}function qs(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=Zr();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},K(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Pe(e.sealKey.publicKey)}}async function Ys(t,e,r,o){let n;try{n=JSON.parse(eo(o,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=U(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await ze(n.token);return i.github={token:n.token},Nt(i,()=>{process.env.GH_TOKEN=n.token,Hs(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Xe(n.token);return i.gitlab={token:n.token},Nt(i,()=>{process.env.GITLAB_TOKEN=n.token,Ks(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!n.email||!n.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Je(n.email,n.apiToken);return i.bitbucket={email:n.email,apiToken:n.apiToken},Nt(i,()=>{process.env.BITBUCKET_EMAIL=n.email,process.env.BITBUCKET_API_TOKEN=n.apiToken,Ws(n.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=n.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Ze({baseUrl:s,token:n.token});return i.youtrack={url:s,token:n.token},Nt(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=n.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await on(n.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:n.token},Nt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return n.token?(i.contextWrite={token:n.token},Nt(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function Nt(t,e){K(t),e()}import{existsSync as rd,readFileSync as od,statSync as Vs}from"node:fs";var zs=2*1024*1024;function nd(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Js(t,e){let r=Ve(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!rd(r)||!Vs(r).isFile())throw new Error(`file not found: ${e}`);let{size:o}=Vs(r);if(o>zs)throw new Error(`file too large: ${e} is ${o} bytes (limit ${zs})`);let n=od(r);return nd(n)?{content:n.toString("utf-8"),encoding:"utf8",sizeBytes:n.length}:{content:n.toString("base64"),encoding:"base64",sizeBytes:n.length}}import{existsSync as id,readFileSync as sd,writeFileSync as ad}from"node:fs";import{join as cd}from"node:path";import{parseDocument as ld}from"yaml";var Xs=64;async function Qs(t,e){if(!Number.isInteger(e)||e<1||e>Xs)throw new Error(`maxJobs must be an integer in [1, ${Xs}], got ${e}`);let r=cd(t,"regimen.yaml");if(!id(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=ld(sd(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),ad(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as sn,readFileSync as an,writeFileSync as ud}from"node:fs";import{join as to}from"node:path";import{parseDocument as cn}from"yaml";async function Zs(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=to(t,"project.yaml");if(!sn(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=cn(an(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=to(t,"regimen.yaml");if(!sn(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=cn(an(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)ud(to(t,i.path),i.content);return{files:r.map(i=>i.path)}}function ln(t){if(!t)return"Stage";try{let e=to(t,"project.yaml");if(!sn(e))return"Stage";let o=cn(an(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof o=="string"&&o.trim().length>0?o.trim():"Stage"}catch{return"Stage"}}var ro=new Map;async function un(t,e){let o=(ro.get(t)??Promise.resolve()).catch(()=>{}).then(e);ro.set(t,o);try{return await o}finally{ro.get(t)===o&&ro.delete(t)}}async function ea(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;pr(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return un(`${i}/${r.name}`,async()=>{let s=await Xr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ke(i,r.name,t.baseDir),{commit:c}=await ss(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 oe({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 q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return un(`${i}/${r.name}`,async()=>{let s=await Xr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ke(i,r.name,t.baseDir),{commit:c,pushed:l}=await as(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return oe({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return q("no repo spec");let i=Be(r),s=await i.createPullRequest(r,e);return oe({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return q("no repo spec");let i=Be(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return oe({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return q("no repo spec");let i=Be(r);return await i.closePR(r,e.prNumber,e.comment),oe({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return un(`${i}/${r.name}`,async()=>{let s=await Xr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ke(i,r.name,t.baseDir),{mergedSha:c}=await cs(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return oe({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return oe({stub:!0});case"tracker_status":{let i=Me();return i?t.trackerIssueId?(await Ts(i,t.trackerIssueId,e.newStatus,ln(t.contextDir)),oe({issueId:t.trackerIssueId,newStatus:e.newStatus})):q("no tracker_issue_id provided"):q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=Me();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return q("no tracker_issue_id provided");let s=await Is(i,t.trackerIssueId,e.body);return oe({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Me();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return q("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Ps(i,e.projectKey,e.title,e.body,e.targetStatus,ln(t.contextDir));return oe({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Me();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Es(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return q(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return oe({applied:s})}case"set_parallelism":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await Qs(t.contextDir,e.maxJobs);return oe({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await Zs(t.contextDir,e);return oe({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),oe({reported:!0})):q("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return q("no context repo clone on this CLI");let i=await t.refreshContextStatus();return oe({outdated:i.outdated,templateVersion:i.templateVersion})}case"read_context_file":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=Js(t.contextDir,e.path);return oe({path:e.path,...i})}default:return q(`unsupported action type: ${e.type}`)}}catch(i){return q(i instanceof Error?i.message:String(i))}}function oe(t){return{status:"done",result:t}}function q(t){return{status:"failed",error:t}}import{existsSync as ga,readFileSync as ha}from"node:fs";import{join as ya}from"node:path";import{homedir as pd}from"node:os";import{existsSync as dd,mkdirSync as fd,readFileSync as md,writeFileSync as gd}from"node:fs";import{dirname as hd,join as yd}from"node:path";function pn(){return L("FARM_PINS")??yd(pd(),".codepipe","farm-pins.json")}function ta(){let t=pn();if(!dd(t))return{};try{return JSON.parse(md(t,"utf-8"))}catch{return{}}}function wd(t){let e=pn();fd(hd(e),{recursive:!0}),gd(e,JSON.stringify(t,null,2)+`
434
+ `,{mode:384})}function kd(t){return ta()[t]}function oo(t,e){let r=ta();r[t]=e,wd(r)}function no(t,e){let r=Pe(e),o=kd(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 ${pn()}.`);return r}import bd from"ws";function io(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new bd(r)}var E=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function Ee(t,e,r){return Ge(t,e,"/projects",r)}async function ra(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new E(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function so(t,e,r,o){return Ge(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function oa(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new E(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function ao(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new E(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function na(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new E(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var yr=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function ia(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let o;try{o=(await r.json()).error}catch{}if(o==="registration_required")throw new yr(e)}if(!r.ok)throw new E(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function sa(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new E(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function aa(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new E(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function ca(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 E(n.status,null,`GET cli-task HTTP ${n.status}`);return await n.json()}async function la(t,e,r,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function ua(t,e,r,o,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function pa(t,e,r,o,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function da(t,e,r,o,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function co(t,e,r,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function dn(t,e,r,o){await Ge(t,e,`/projects/${encodeURIComponent(r)}/init-status`,o)}async function fa(t,e,r,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/repos`,o)}async function ma(t,e,r,o){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(o)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new E(n.status,s,a)}return s}async function M(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new E(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 E(n.status,s,a)}return s}async function wa(t,e,r,o){let n=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return n(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=Pe(e.farmPublicKey);if(i!==e.fingerprint)return n("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");no(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 M(t.hubUrl,t.cliToken,t.projectId),c;if(r){let p=ya(r,"project.yaml"),g=ya(r,"regimen.yaml");ga(p)&&ga(g)?c={projectYaml:ha(p,"utf-8"),regimenYaml:ha(g,"utf-8")}:o.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Ot(e.farmPublicKey,JSON.stringify(l));oo(e.farmId,i),o.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let d=await so(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return d.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...d.daemonStatus?{daemonStatus:d.daemonStatus}:{}}:n(d.error??"farm provisioning failed")}catch(i){return n(i instanceof Error?i.message:String(i))}}var lo=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=Be(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);o.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof mt){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let n=o.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===n)return;for(let s=0;s<o.length;s++){let a=o[s];if(a.ci!=="failed")continue;let c=Be(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=$d(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function $d(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}import{existsSync as ka,readFileSync as xd,readdirSync as vd}from"node:fs";function Sd(t,e,r){let o=[];for(let n of r){let i=n.issue.key,s=Id(t,i,n.attachments);o.push({path:`tasks/${i}/task.md`,content:Cd(n.issue,e,s)}),o.push({path:`tasks/${i}/comments.jsonl`,content:Td(Rd(t,i,n.comments))});for(let a of n.attachments)o.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return o}async function ba(t,e,r){if(r.length===0)return;let o=Sd(t,e,r),n=r.map(i=>i.issue.key);await At(t,o,`sync(${n.join(", ")}): task data`)}function Cd(t,e,r){let o=new Date(t.updatedAt).toISOString(),n=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${o}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){n.push("## Attachments","");for(let i of r)n.push(`- [${i}](attachments/${encodeURI(i)})`);n.push("")}return n.join(`
435
+ `)}function Rd(t,e,r){let o=new Map,n=Ve(t,`tasks/${e}/comments.jsonl`);if(ka(n))for(let i of xd(n,"utf-8").split(`
436
+ `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&o.set(a.id,a)}catch{}}for(let i of r){let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Ur(i.body);a&&(s.parsedCommand=a),o.set(i.id,s)}return[...o.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Td(t){return t.map(e=>JSON.stringify(e)).join(`
437
437
  `)+(t.length>0?`
438
- `:"")}function $d(t,e,r){let o=[],n=qe(t,`tasks/${e}/attachments`);if(ga(n))for(let i of hd(n))o.push(i);for(let i of r)o.includes(i.name)||o.push(i.name);return o}var lo=class t{constructor(e,r,o,n={contextDir:null}){this.intervalMs=e;this.send=r;this.log=o;this.options=n}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(this.running||!this.request)return;let e=De();if(!e){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn("[yt-sync] YOUTRACK_URL/YOUTRACK_TOKEN missing \u2014 poller idle. set them in cli/.env to enable YT read-sync."));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,e)}finally{this.running=!1}}async pollOnce(e,r){let o=Date.now(),n;try{let w=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await As(r,{projectKey:e.projectKey,columns:w,...e.stageField?{stageField:e.stageField}:{},...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(w){this.log.warn(`[yt-sync] listIssues failed: ${w instanceof Error?w.message:String(w)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let w of n){if(s.add(w.id),a.has(w.status))continue;let x=await wa(r,w.id,e.sinceMs,this.log);x&&i.set(w.id,x)}let c=[];for(let w of e.offBoardIssueIds){if(s.has(w))continue;let x=await wa(r,w,e.sinceMs,this.log);if(x&&x.length>0&&i.set(w,x),e.requireAssignee||x&&x.length>0){let O=await Sd(r,w,e.stageField,this.log);if(O)c.push(O);else if(x&&x.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=n.filter(w=>!a.has(w.status)),{attachmentsByIssue:u,attachmentKeys:f}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let p=[...l,...c].map(w=>({issue:w,comments:i.get(w.id)??[],attachments:u.get(w.id)??[]}));try{await ha(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let w of f)this.shippedAttachments.add(w)}catch(w){let x=w instanceof Error?w.message:String(w);this.abandonTick(`context task sync failed: ${x}`);return}let g=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[w,x]of i){let O=x.filter(v=>!g(v.id));if(O.length===0)continue;d.push({issueId:w,comments:O.map(xd)});let j=O.flatMap(v=>{let m=Nr(v.body);return m?[{commentId:v.id,author:v.author,name:m.name,args:m.args,createdAt:v.createdAt}]:[]});j.length>0&&h.push({issueId:w,commands:j})}let S={type:"youtrack_observation",projectId:e.projectId,issues:n.map(ya),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(ya)}:{},observedAtMs:o};this.send(S);let b=d.reduce((w,x)=>w+x.comments.length,0),y=h.reduce((w,x)=>w+x.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${n.length} comments=${b} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,o){let n=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let f=`${s.id}:${u.id}`;if(this.shippedAttachments.has(f))continue;let p;try{p=await Es(o,u.url)}catch(d){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${d instanceof Error?d.message:String(d)}`);continue}let g=vd(u.name);l.has(g)&&(g=`${u.id}-${g}`),l.add(g),c.push({name:g,contentBase64:p.toString("base64")}),i.push(f)}c.length>0&&n.set(s.id,c)}return{attachmentsByIssue:n,attachmentKeys:i}}};function ya(t){let{description:e,...r}=t;return r}function xd(t){let{body:e,...r}=t;return r}function vd(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 Sd(t,e,r,o){try{return await _s(t,e,r)}catch(n){return o.warn(`[yt-sync] getIssue ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}async function wa(t,e,r,o){try{return await Os(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var dn="npm i -g @code-partner/codepipe@latest";function uo(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${pe} (protocol ${Se})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&Ai(n.contextDir,r);let i=ka("CLI_TRACKING_POLL_INTERVAL_SEC"),s=ka("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,l=!1,u=new Set,f=new Set,p=g();function g(){let d=no(t.hubUrl,t.cliToken),h=null,S=new co(i,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r),b=new lo(s,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r,{contextDir:n?.contextDir??null,isSelfComment:m=>f.has(m)}),y=null,w=async()=>{try{let m;try{let T=await G(t.hubUrl,t.cliToken,t.projectId);m={repos:T.repos,contextRepo:T.contextRepo}}catch(T){r.warn(`[readiness] could not fetch project summary for push checks: ${T instanceof Error?T.message:String(T)}`)}let R=await Ds(t.projectId,m);if(d.readyState!==d.OPEN)return;let k={type:"cli_readiness",projectId:t.projectId,ready:R.ready,checks:R.checks,creds:R.creds,checkedAt:R.checkedAt};if(d.send(JSON.stringify(k)),R.ready)r.info("[readiness] ready");else{let T=R.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${T.join(", ")}`)}}catch(m){r.warn(`[readiness] check failed: ${m instanceof Error?m.message:String(m)}`)}},x=()=>{w(),y=setInterval(()=>void w(),a),typeof y.unref=="function"&&y.unref()},O=()=>{y&&(clearInterval(y),y=null)},j=n?.contextDir?new Wr(n.contextDir,t.projectId,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r):null,v=async()=>{let m=n?.contextDir;if(!m)throw new Error("no context repo clone on this CLI");let R;try{R=(await G(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let k=await zi(m,t.projectId,R,r);return d.readyState===d.OPEN&&d.send(JSON.stringify(k)),k};return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let m=Ii(t.projectId),R=L("ORIGIN")==="farm"?"farm":"local",k=L("FARM_ID"),T=t.accountEmail??m.email,I;try{let P=Fs(t.projectId);P&&(I=P.publicKey,r.info(`[cred-channel] key fingerprint: ${P.fingerprint}`))}catch(P){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${P instanceof Error?P.message:String(P)}`)}let $={type:"register",projectId:t.projectId,platformVersion:pe,protocolVersion:Se,accountId:m.accountId,accountLabel:m.label,origin:R,inFlightActionIds:[...u],...T?{accountEmail:T}:{},...R==="farm"&&k?{farmId:k}:{},...I?{sealPublicKey:I}:{}};d.send(JSON.stringify($))}),d.on("message",async m=>{let R=m.toString("utf-8");if(R==="pong"||R==="ping")return;let k;try{k=JSON.parse(R)}catch{return}if(!k||typeof k!="object")return;let T=k.type;if(T==="registered"){let $=k;if($.ok){if(r.info(`[ws] registered for project ${$.projectId}`),o({kind:"registered",projectId:$.projectId??t.projectId}),S.start(),j?.start(),x(),fn(t,n,r),n?.contextDir)try{let P=Yr(n.contextDir,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.outdated&&(r.warn(`[ctx] context format outdated: v${P.templateVersion} \u2192 v${P.currentVersion}`+(P.missingPaths.length>0?` (missing: ${P.missingPaths.join(", ")})`:"")),l||(l=!0,v().catch(()=>{})))}catch(P){r.warn(`[ctx] context-format detect failed (non-fatal): ${P instanceof Error?P.message:String(P)}`)}}else r.warn(`[ws] register rejected: ${$.reason??"unknown"}`),o({kind:"register_rejected",reason:$.reason??"unknown"}),c=!0,d.close();return}if(T==="hello"){let $=k;h=_r($.protocolVersion);let P=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${P}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${pe}, protocol ${Se}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${dn}`),o({kind:"incompatible",hubVersion:typeof $.platformVersion=="string"?$.platformVersion:null,hubProtocol:typeof $.protocolVersion=="number"?$.protocolVersion:null,updateCommand:dn}));return}if(T==="tracking_targets"){S.setTargets(k.targets);return}if(T==="youtrack_sync_request"){b.setRequest(k);return}if(T==="sync_local"){await jd(k,n,d,r);return}if(T==="provision_repo"){let $=k;r.info(`[repo] provision_repo: ${$.repo.name} (${$.repo.host}:${$.repo.owner}/${$.repo.repoName})`),await Rd(t,n,$.repo,r),await fn(t,n,r);return}if(T==="remove_repo"){let $=k;r.info(`[repo] remove_repo: ${$.repoName}${$.purge?" (purge)":""}`),await fn(t,n,r),$.purge&&Id(t,n,$.repoName,r);return}if(T==="context_write"){await Pd(k,n,d,r);return}if(T==="adr_promote"){await Ed(k,n,d,r);return}if(T==="cred_update"){let $=k,P=U(t.projectId),B=P?.sealKey?await Hs(t.projectId,$.kind,$.sealed,P.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},H={type:"cred_update_result",updateId:$.updateId,projectId:t.projectId,ok:B.ok,...B.detail?{detail:B.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(H)),B.ok?(r.info(`[cred] ${$.kind} replaced${B.detail?` \u2014 ${B.detail}`:""}`),w()):r.warn(`[cred] ${$.kind} replacement rejected: ${B.detail??"unknown"}`);return}if(T==="move_to_farm"){let $=k;r.info(`[farm-move] request to move ${t.projectId} onto farm ${$.farmName} (${$.farmId})`);let P=await ma(t,$,n?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.ok?r.info(`[farm-move] done \u2014 farm daemon ${P.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${P.error??"unknown error"}`);return}if(T==="tracker_fields_request"){let $=k,P={type:"tracker_fields_result",requestId:$.requestId,projectId:t.projectId,ok:!1},B=De();if(!B)P.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{P.fields=await Us(B,$.projectKey),P.ok=!0}catch(H){P.error=H instanceof Error?H.message:String(H)}d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.ok||r.warn(`[yt-fields] listing failed: ${P.error??"unknown"}`);return}if(T==="sandbox_keys"){let $=U(t.projectId);if(!$){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let P=Ct(t.projectId),B=ls(k,$,P,r);for(let H of B)d.readyState===d.OPEN&&d.send(JSON.stringify(H));return}if(T!=="dispatch_action")return;let I=k;if(h===!1){let $=`refused: HUB protocol incompatible with CLI v${pe} (protocol ${Se})`;d.send(JSON.stringify({type:"action_result",actionId:I.actionId,status:"failed",error:$})),r.warn(`[exec] ${I.actionId} (${I.action.type}) \u2192 REFUSED: ${$}`),r.warn(`[exec] update the CLI to clear this: ${dn}`),o({kind:"action",actionId:I.actionId,actionType:I.action.type,ok:!1,error:$});return}u.add(I.actionId);try{let $=await Js({action:I.action,repo:I.repo,trackerIssueId:I.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:j?()=>j.reportNow():void 0,refreshContextStatus:n?.contextDir?v:void 0}).catch(H=>({status:"failed",error:H instanceof Error?H.message:String(H)}));I.action.type==="tracker_comment"&&$.status==="done"&&"result"in $&&typeof $.result?.commentId=="string"&&f.add($.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:I.actionId,...$}));let P=$.status!=="failed",B=!P&&"error"in $?$.error:void 0;P?r.info(`[exec] ${I.actionId} (${I.action.type}) \u2192 done`):r.warn(`[exec] ${I.actionId} (${I.action.type}) \u2192 FAILED: ${B??"?"}`),o({kind:"action",actionId:I.actionId,actionType:I.action.type,ok:P,...B?{error:B}:{}})}finally{u.delete(I.actionId)}}),d.on("close",(m,R)=>{let k=R?.toString("utf-8")??"";if(r.info(`[ws] closed code=${m}${k?` reason=${k}`:""}`),S.stop(),b.stop(),j?.stop(),O(),k==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),o({kind:"replaced"});return}o({kind:"disconnected",code:m}),!c&&setTimeout(()=>{p=g()},2e3)}),d.on("error",m=>r.warn(`[ws] error: ${m.message}`)),d}return{stop(){c=!0,p.close()}}}async function fn(t,e,r){try{let o=await G(t.hubUrl,t.cliToken,t.projectId),{updated:n,errors:i}=lr(t.projectId,o.repos,e?.contextDir);for(let s of n)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(o){r.warn(`[repo] repo-set reconcile skipped: ${o instanceof Error?o.message:String(o)}`)}}async function Rd(t,e,r,o){let n=r.mountAs??r.name;if(n==="."){o.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?yr(e.root,n):ke(t.projectId,r.name);if(ba(yr(i,".git"))){o.info(`[repo] ${r.name} already present at ${i}`);return}try{await Td().clone(Zo(r),i),o.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){o.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function Id(t,e,r,o){let n=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?yr(e.root,n):ke(t.projectId,r);if(e&&i===e.root){o.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!ba(yr(i,".git"))){o.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Cd(i,{recursive:!0,force:!0}),o.info(`[repo] purged local clone ${i}`)}catch(s){o.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function jd(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=yr(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await ji(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 Pd(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 Et(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 Ed(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 Mi(e.contextDir,t.taskKey,t.slugs);if(o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let s=`draft file(s) missing in clone: ${i.missing.map(a=>`tasks/${t.taskKey}/adr/DRAFT-${a}.md`).join(", ")}`;o.warn(`[adr] adr_promote ${t.id}: ${s}`),n("failed",s);return}n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[adr] adr_promote ${t.id} failed: ${s}`),n("failed",s)}}function ka(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Ra,mkdirSync as Ia}from"node:fs";import{dirname as ja}from"node:path";import{simpleGit as Nt}from"simple-git";import{execFileSync as Ad}from"node:child_process";import{mkdtempSync as _d,mkdirSync as Od,readFileSync as $a,rmSync as Nd,writeFileSync as Ud}from"node:fs";import{tmpdir as Ld}from"node:os";import{dirname as Dd,join as xa}from"node:path";function va(t="codepipe-context"){let e=_d(xa(Ld(),"codepipe-ssh-")),r=xa(e,"id_ed25519");try{return Ad("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:$a(r,"utf-8"),publicKey:$a(`${r}.pub`,"utf-8").trim()}}finally{Nd(e,{recursive:!0,force:!0})}}async function Sa(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 Ca(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 Ta(t,e){Od(Dd(t),{recursive:!0});let r=e.endsWith(`
438
+ `:"")}function Id(t,e,r){let o=[],n=Ve(t,`tasks/${e}/attachments`);if(ka(n))for(let i of vd(n))o.push(i);for(let i of r)o.includes(i.name)||o.push(i.name);return o}var uo=class t{constructor(e,r,o,n={contextDir:null}){this.intervalMs=e;this.send=r;this.log=o;this.options=n}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(this.running||!this.request)return;let e=Me();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 w=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await Us(r,{projectKey:e.projectKey,columns:w,...e.stageField?{stageField:e.stageField}:{},...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(w){this.log.warn(`[yt-sync] listIssues failed: ${w instanceof Error?w.message:String(w)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let w of n){if(s.add(w.id),a.has(w.status))continue;let x=await xa(r,w.id,e.sinceMs,this.log);x&&i.set(w.id,x)}let c=[];for(let w of e.offBoardIssueIds){if(s.has(w))continue;let x=await xa(r,w,e.sinceMs,this.log);if(x&&x.length>0&&i.set(w,x),e.requireAssignee||x&&x.length>0){let O=await Ed(r,w,e.stageField,this.log);if(O)c.push(O);else if(x&&x.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=n.filter(w=>!a.has(w.status)),{attachmentsByIssue:u,attachmentKeys:d}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let p=[...l,...c].map(w=>({issue:w,comments:i.get(w.id)??[],attachments:u.get(w.id)??[]}));try{await ba(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let w of d)this.shippedAttachments.add(w)}catch(w){let x=w instanceof Error?w.message:String(w);this.abandonTick(`context task sync failed: ${x}`);return}let g=this.options.isSelfComment??(()=>!1),f=[],h=[];for(let[w,x]of i){let O=x.filter(v=>!g(v.id));if(O.length===0)continue;f.push({issueId:w,comments:O.map(jd)});let j=O.flatMap(v=>{let m=Ur(v.body);return m?[{commentId:v.id,author:v.author,name:m.name,args:m.args,createdAt:v.createdAt}]:[]});j.length>0&&h.push({issueId:w,commands:j})}let S={type:"youtrack_observation",projectId:e.projectId,issues:n.map($a),commentsBatch:f,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map($a)}:{},observedAtMs:o};this.send(S);let b=f.reduce((w,x)=>w+x.comments.length,0),y=h.reduce((w,x)=>w+x.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${n.length} comments=${b} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,o){let n=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let d=`${s.id}:${u.id}`;if(this.shippedAttachments.has(d))continue;let p;try{p=await Ns(o,u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let g=Pd(u.name);l.has(g)&&(g=`${u.id}-${g}`),l.add(g),c.push({name:g,contentBase64:p.toString("base64")}),i.push(d)}c.length>0&&n.set(s.id,c)}return{attachmentsByIssue:n,attachmentKeys:i}}};function $a(t){let{description:e,...r}=t;return r}function jd(t){let{body:e,...r}=t;return r}function Pd(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 Ed(t,e,r,o){try{return await Ls(t,e,r)}catch(n){return o.warn(`[yt-sync] getIssue ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}async function xa(t,e,r,o){try{return await Ds(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var fn="npm i -g @code-partner/codepipe@latest";function po(t,e={}){let r=e.log??{info:f=>console.log(f),warn:f=>console.warn(f)};r.info(`codepipe-cli v${me} (protocol ${Se})`);let o=f=>e.onEvent?.(f),n=e.workspace;n?.contextDir&&Ui(n.contextDir,r);let i=va("CLI_TRACKING_POLL_INTERVAL_SEC"),s=va("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let f=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(f)&&f>0?f*1e3:6e5})(),c=!1,l=!1,u=new Set,d=new Set,p=g();function g(){let f=io(t.hubUrl,t.cliToken),h=null,S=new lo(i,m=>{f.readyState===f.OPEN&&f.send(JSON.stringify(m))},r),b=new uo(s,m=>{f.readyState===f.OPEN&&f.send(JSON.stringify(m))},r,{contextDir:n?.contextDir??null,isSelfComment:m=>d.has(m)}),y=null,w=async()=>{try{let m;try{let R=await M(t.hubUrl,t.cliToken,t.projectId);m={repos:R.repos,contextRepo:R.contextRepo}}catch(R){r.warn(`[readiness] could not fetch project summary for push checks: ${R instanceof Error?R.message:String(R)}`)}let T=await Fs(t.projectId,m);if(f.readyState!==f.OPEN)return;let k={type:"cli_readiness",projectId:t.projectId,ready:T.ready,checks:T.checks,creds:T.creds,checkedAt:T.checkedAt};if(f.send(JSON.stringify(k)),T.ready)r.info("[readiness] ready");else{let R=T.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${R.join(", ")}`)}}catch(m){r.warn(`[readiness] check failed: ${m instanceof Error?m.message:String(m)}`)}},x=()=>{w(),y=setInterval(()=>void w(),a),typeof y.unref=="function"&&y.unref()},O=()=>{y&&(clearInterval(y),y=null)},j=n?.contextDir?new qr(n.contextDir,t.projectId,m=>{f.readyState===f.OPEN&&f.send(JSON.stringify(m))},r):null,v=async()=>{let m=n?.contextDir;if(!m)throw new Error("no context repo clone on this CLI");let T;try{T=(await M(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let k=await Zi(m,t.projectId,T,r);return f.readyState===f.OPEN&&f.send(JSON.stringify(k)),k};return f.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let m=Ai(t.projectId),T=L("ORIGIN")==="farm"?"farm":"local",k=L("FARM_ID"),R=t.accountEmail??m.email,I;try{let P=qs(t.projectId);P&&(I=P.publicKey,r.info(`[cred-channel] key fingerprint: ${P.fingerprint}`))}catch(P){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${P instanceof Error?P.message:String(P)}`)}let $={type:"register",projectId:t.projectId,platformVersion:me,protocolVersion:Se,accountId:m.accountId,accountLabel:m.label,origin:T,inFlightActionIds:[...u],...R?{accountEmail:R}:{},...T==="farm"&&k?{farmId:k}:{},...I?{sealPublicKey:I}:{}};f.send(JSON.stringify($))}),f.on("message",async m=>{let T=m.toString("utf-8");if(T==="pong"||T==="ping")return;let k;try{k=JSON.parse(T)}catch{return}if(!k||typeof k!="object")return;let R=k.type;if(R==="registered"){let $=k;if($.ok){if(r.info(`[ws] registered for project ${$.projectId}`),o({kind:"registered",projectId:$.projectId??t.projectId}),S.start(),j?.start(),x(),mn(t,n,r),n?.contextDir)try{let P=Vr(n.contextDir,t.projectId);f.readyState===f.OPEN&&f.send(JSON.stringify(P)),P.outdated&&(r.warn(`[ctx] context format outdated: v${P.templateVersion} \u2192 v${P.currentVersion}`+(P.missingPaths.length>0?` (missing: ${P.missingPaths.join(", ")})`:"")),l||(l=!0,v().catch(()=>{})))}catch(P){r.warn(`[ctx] context-format detect failed (non-fatal): ${P instanceof Error?P.message:String(P)}`)}}else r.warn(`[ws] register rejected: ${$.reason??"unknown"}`),o({kind:"register_rejected",reason:$.reason??"unknown"}),c=!0,f.close();return}if(R==="hello"){let $=k;h=Or($.protocolVersion);let P=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${P}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${me}, protocol ${Se}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${fn}`),o({kind:"incompatible",hubVersion:typeof $.platformVersion=="string"?$.platformVersion:null,hubProtocol:typeof $.protocolVersion=="number"?$.protocolVersion:null,updateCommand:fn}));return}if(R==="tracking_targets"){S.setTargets(k.targets);return}if(R==="youtrack_sync_request"){b.setRequest(k);return}if(R==="sync_local"){await Ud(k,n,f,r);return}if(R==="provision_repo"){let $=k;r.info(`[repo] provision_repo: ${$.repo.name} (${$.repo.host}:${$.repo.owner}/${$.repo.repoName})`),await Od(t,n,$.repo,r),await mn(t,n,r);return}if(R==="remove_repo"){let $=k;r.info(`[repo] remove_repo: ${$.repoName}${$.purge?" (purge)":""}`),await mn(t,n,r),$.purge&&Nd(t,n,$.repoName,r);return}if(R==="context_write"){await Ld(k,n,f,r);return}if(R==="adr_promote"){await Dd(k,n,f,r);return}if(R==="cred_update"){let $=k,P=U(t.projectId),B=P?.sealKey?await Ys(t.projectId,$.kind,$.sealed,P.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},H={type:"cred_update_result",updateId:$.updateId,projectId:t.projectId,ok:B.ok,...B.detail?{detail:B.detail}:{}};f.readyState===f.OPEN&&f.send(JSON.stringify(H)),B.ok?(r.info(`[cred] ${$.kind} replaced${B.detail?` \u2014 ${B.detail}`:""}`),w()):r.warn(`[cred] ${$.kind} replacement rejected: ${B.detail??"unknown"}`);return}if(R==="move_to_farm"){let $=k;r.info(`[farm-move] request to move ${t.projectId} onto farm ${$.farmName} (${$.farmId})`);let P=await wa(t,$,n?.contextDir,r);f.readyState===f.OPEN&&f.send(JSON.stringify(P)),P.ok?r.info(`[farm-move] done \u2014 farm daemon ${P.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${P.error??"unknown error"}`);return}if(R==="tracker_fields_request"){let $=k,P={type:"tracker_fields_result",requestId:$.requestId,projectId:t.projectId,ok:!1},B=Me();if(!B)P.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{P.fields=await Ms(B,$.projectKey),P.ok=!0}catch(H){P.error=H instanceof Error?H.message:String(H)}f.readyState===f.OPEN&&f.send(JSON.stringify(P)),P.ok||r.warn(`[yt-fields] listing failed: ${P.error??"unknown"}`);return}if(R==="sandbox_keys"){let $=U(t.projectId);if(!$){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let P=Rt(t.projectId),B=fs(k,$,P,r);for(let H of B)f.readyState===f.OPEN&&f.send(JSON.stringify(H));return}if(R!=="dispatch_action")return;let I=k;if(h===!1){let $=`refused: HUB protocol incompatible with CLI v${me} (protocol ${Se})`;f.send(JSON.stringify({type:"action_result",actionId:I.actionId,status:"failed",error:$})),r.warn(`[exec] ${I.actionId} (${I.action.type}) \u2192 REFUSED: ${$}`),r.warn(`[exec] update the CLI to clear this: ${fn}`),o({kind:"action",actionId:I.actionId,actionType:I.action.type,ok:!1,error:$});return}u.add(I.actionId);try{let $=await ea({action:I.action,repo:I.repo,trackerIssueId:I.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:j?()=>j.reportNow():void 0,refreshContextStatus:n?.contextDir?v:void 0}).catch(H=>({status:"failed",error:H instanceof Error?H.message:String(H)}));I.action.type==="tracker_comment"&&$.status==="done"&&"result"in $&&typeof $.result?.commentId=="string"&&d.add($.result.commentId),f.send(JSON.stringify({type:"action_result",actionId:I.actionId,...$}));let P=$.status!=="failed",B=!P&&"error"in $?$.error:void 0;P?r.info(`[exec] ${I.actionId} (${I.action.type}) \u2192 done`):r.warn(`[exec] ${I.actionId} (${I.action.type}) \u2192 FAILED: ${B??"?"}`),o({kind:"action",actionId:I.actionId,actionType:I.action.type,ok:P,...B?{error:B}:{}})}finally{u.delete(I.actionId)}}),f.on("close",(m,T)=>{let k=T?.toString("utf-8")??"";if(r.info(`[ws] closed code=${m}${k?` reason=${k}`:""}`),S.stop(),b.stop(),j?.stop(),O(),k==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),o({kind:"replaced"});return}o({kind:"disconnected",code:m}),!c&&setTimeout(()=>{p=g()},2e3)}),f.on("error",m=>r.warn(`[ws] error: ${m.message}`)),f}return{stop(){c=!0,p.close()}}}async function mn(t,e,r){try{let o=await M(t.hubUrl,t.cliToken,t.projectId),{updated:n,errors:i}=ur(t.projectId,o.repos,e?.contextDir);for(let s of n)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(o){r.warn(`[repo] repo-set reconcile skipped: ${o instanceof Error?o.message:String(o)}`)}}async function Od(t,e,r,o){let n=r.mountAs??r.name;if(n==="."){o.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?wr(e.root,n):ke(t.projectId,r.name);if(Sa(wr(i,".git"))){o.info(`[repo] ${r.name} already present at ${i}`);return}try{await _d().clone(en(r),i),o.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){o.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function Nd(t,e,r,o){let n=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?wr(e.root,n):ke(t.projectId,r);if(e&&i===e.root){o.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Sa(wr(i,".git"))){o.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Ad(i,{recursive:!0,force:!0}),o.info(`[repo] purged local clone ${i}`)}catch(s){o.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function Ud(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(l=>l.name===n.repoName),s=wr(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await _i(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 Ld(t,e,r,o){let n=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{await At(e.contextDir,t.files,t.message),o.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[ctx] context_write ${t.id} failed: ${s}`),n("failed",s)}}async function Dd(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 Ki(e.contextDir,t.taskKey,t.slugs);if(o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let s=`draft file(s) missing in clone: ${i.missing.map(a=>`tasks/${t.taskKey}/adr/DRAFT-${a}.md`).join(", ")}`;o.warn(`[adr] adr_promote ${t.id}: ${s}`),n("failed",s);return}n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[adr] adr_promote ${t.id} failed: ${s}`),n("failed",s)}}function va(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Ea,mkdirSync as Aa}from"node:fs";import{dirname as _a}from"node:path";import{simpleGit as Ut}from"simple-git";import{execFileSync as Bd}from"node:child_process";import{mkdtempSync as Md,mkdirSync as Gd,readFileSync as Ca,rmSync as Fd,writeFileSync as Hd}from"node:fs";import{tmpdir as Kd}from"node:os";import{dirname as Wd,join as Ra}from"node:path";function Ta(t="codepipe-context"){let e=Md(Ra(Kd(),"codepipe-ssh-")),r=Ra(e,"id_ed25519");try{return Bd("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Ca(r,"utf-8"),publicKey:Ca(`${r}.pub`,"utf-8").trim()}}finally{Fd(e,{recursive:!0,force:!0})}}async function Ia(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 ja(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 Pa(t,e){Gd(Wd(t),{recursive:!0});let r=e.endsWith(`
439
439
  `)?e:e+`
440
- `;return Ud(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Bd(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 Md(t,e){return e?.contextWrite?.token?{user:Ur(t),secret:e.contextWrite.token}:t===sr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===sr.bitbucket?e?.bitbucket?.apiToken?{user:ut,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function po(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await G(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=Md(vt(s.cloneUrl),r);if(a){let c=await Gd({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 Fd({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 Gd(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=Bd(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(Ra(`${r}/.git`)){let l=Nt(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Ho(r);await l.reset(["--hard",`origin/${s}`]),Ko(r,u),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Ia(ja(r),{recursive:!0}),await Nt().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Pa(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 Fd(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=Ta(i,o),a=Ca(e.cloneUrl),c=e.branch;try{if(Ra(`${r}/.git`)){let l=Nt(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=Ho(r);await l.reset(["--hard",`origin/${c}`]),Ko(r,u),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Ia(ja(r),{recursive:!0}),await Nt().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Nt(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Pa(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 Pa(t){let e=Nt(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 Ea(t={profile:void 0}){let{cfg:e,profile:r}=Mr(t.profile),o=U(e.projectId);o&&ar(o),fr(o?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),mr(o?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),gr(o?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let n=wr(mn(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Hr("CLI_LOG",i,n);if(s.enabled){let p=new Rt(s);Kr(p),console.log(`[log] file logging \u2192 ${p.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=Dr(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let p=wr(mn(),".codepipe",r?wr("profiles",r,"context"):"context");if(await pn(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await po({cfg:e,secrets:o,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),a||await pn(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let g=wr(mn(),".codepipe",r?wr("profiles",r,"context-config"):"context-config");qr(a.contextDir,g,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=uo(e,{...a?{workspace:a}:{},onEvent:p=>{p.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function f(p){u||(u=!0,console.log(`
441
- [${p}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}import{hostname as Jd}from"node:os";import{spawnSync as Hd}from"node:child_process";function Kd(){try{return Hd("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Aa(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Kd(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Ut}from"node:os";import{mkdirSync as Wd,readFileSync as _a,writeFileSync as qd,existsSync as gn}from"node:fs";import{dirname as Yd,join as Ze}from"node:path";gn(".env")&&process.loadEnvFile(".env");function Vd(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function $e(t){let e=L("SANDBOX_CONFIG");if(e)return e;let r=Ze(Ut(),".codepipe","worker");return t?Ze(r,"profiles",t,"config.json"):Ze(r,"config.json")}function Oa(){return Ze(Ut(),".devpipe-sandbox","config.json")}function fo(){pt(Ze(Ut(),".devpipe"),Ze(Ut(),".codepipe")),L("SANDBOX_CONFIG")||pt(Ze(Ut(),".devpipe-sandbox"),Ze(Ut(),".codepipe-sandbox"))}function ne(t){let e=$e(t),r=null;return gn(e)?r=JSON.parse(_a(e,"utf-8")):!t&&!L("SANDBOX_CONFIG")&&gn(Oa())&&(r=JSON.parse(_a(Oa(),"utf-8"))),r?(r.planningLane=Vd(),r):null}function Na(t,e){let r=$e(e);Wd(Yd(r),{recursive:!0}),qd(r,JSON.stringify(t,null,2)+`
442
- `,{mode:384})}import zd from"ws";var Lt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(o.signal=e);let n=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(n,o)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(o.signal=r);let n=await fetch(`${this.hubUrl}/jobs/heartbeat`,o);if(n.status===410)return"claim_lost";if(!n.ok)throw new Error(`heartbeat failed: ${n.status} ${await n.text()}`);return"ok"}async releaseJob(e,r,o){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};o&&(n.signal=o);let i=await fetch(`${this.hubUrl}/jobs/release`,n);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new zd(e)}};async function mt(t){fo();let e=ne(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${$e(t.profile)}.`),process.exit(1));let r=t.name??Jd(),o=Aa({projects:t.projects??[],llm:t.llm??null}),n=new Lt(t.hub.replace(/\/$/,"")),i=Qr(),s=Pe(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});Na({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${$e(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as Ff,readFileSync as vn,readdirSync as Hf,writeFileSync as Kf}from"node:fs";import{dirname as Wf,join as xr,resolve as qf}from"node:path";import{spawn as rf}from"node:child_process";import{existsSync as of}from"node:fs";import{spawn as Xd}from"node:child_process";var Ua=16e3,La=5e3,Da=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Qd="\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B \u0434\u0438\u0430\u043B\u043E\u0433. \u0422\u0435\u043F\u0435\u0440\u044C, \u043E\u043F\u0438\u0440\u0430\u044F\u0441\u044C \u043D\u0430 \u0432\u0441\u0451, \u0447\u0442\u043E \u043C\u044B \u043E\u0431\u0441\u0443\u0434\u0438\u043B\u0438, \u043D\u0430\u043F\u0438\u0448\u0438 \u0444\u0430\u0439\u043B DRAFT.md \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u043F\u043E \u043E\u043F\u0438\u0441\u0430\u043D\u043D\u043E\u043C\u0443 \u043A\u043E\u043D\u0442\u0440\u0430\u043A\u0442\u0443 (\u0441\u0442\u0440\u043E\u043A\u0430 1 \u2014 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u226480 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C, \u0441\u0442\u0440\u043E\u043A\u0430 2 \u043F\u0443\u0441\u0442\u0430\u044F, \u0434\u0430\u043B\u044C\u0448\u0435 \u0442\u0435\u043B\u043E \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C \u0432 Markdown) \u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0438 \u0440\u0430\u0431\u043E\u0442\u0443. \u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043F\u0438\u0448\u0438.";function hn(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Zd(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}function ef(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function gt(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function yn(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
443
- `}async function Ba(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Me;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let o=e.onActivity,n=c=>{if(o)try{o(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),u=c.type;if(u==="assistant"){let f=c.message;for(let p of f?.content??[]){let g=p.type;if(g==="text"){let d=String(p.text??"").trim();d&&n({ts:l,kind:"text",author:"agent",text:hn(d,Ua)})}else if(g==="tool_use"){let d=String(p.name??""),h=p.input?.file_path??p.input?.path,S=Zd(h,e.workspaceDir);n({ts:l,kind:"tool",author:"agent",tool:d,...S?{file:S}:{}})}}return}if(u==="user"){let f=c.message;for(let p of f?.content??[])if(p.type==="tool_result"){let g=p.is_error===!0,d=g?hn(ef(p.content),200):"";n({ts:l,kind:"tool_result",author:"agent",isError:g,...d?{text:d}:{}})}return}if(u==="result"){s=c;let f=String(c.subtype??"").trim();n({ts:l,kind:"result",author:"agent",...f?{text:f}:{}});return}if(u==="system"){let f=String(c.subtype??"").trim();f&&n({ts:l,kind:"system",author:"agent",text:f})}};return n({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let u=Xd(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let f=!1,p=!1,g=null,d=()=>{f=!0,u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),La)};e.signal?.addEventListener("abort",d,{once:!0});let h=null,S=()=>{h&&clearTimeout(h),h=setTimeout(()=>{p=!0,console.warn(`[claude:chat] idle for ${Da}ms \u2014 ending session`),u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),La)},Da)},b=()=>{g&&clearTimeout(g),h&&clearTimeout(h),e.signal?.removeEventListener("abort",d)},y=!0,w=j=>{if(!(!y||u.stdin.destroyed))try{u.stdin.write(j)}catch{}};w(yn(e.prompt)),S(),(async()=>{try{for await(let j of e.interactive.inbox){if(f||!y)break;if(S(),j.kind==="user")n({ts:Date.now(),kind:"text",author:"user",text:hn(j.text,Ua)}),w(yn(j.text));else{w(yn(Qd)),y=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let x="",O=j=>{let v;try{v=JSON.parse(j)}catch{return}a(v)};u.stdout.on("data",j=>{i.push(j),S(),x+=j;let v;for(;(v=x.indexOf(`
440
+ `;return Hd(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function qd(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 Yd(t,e){return e?.contextWrite?.token?{user:Lr(t),secret:e.contextWrite.token}:t===ar.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===ar.bitbucket?e?.bitbucket?.apiToken?{user:pt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function fo(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await M(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=Yd(St(s.cloneUrl),r);if(a){let c=await Vd({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 zd({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 Vd(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=qd(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(Ea(`${r}/.git`)){let l=Ut(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Ko(r);await l.reset(["--hard",`origin/${s}`]),Wo(r,u),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Aa(_a(r),{recursive:!0}),await Ut().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Oa(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 zd(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=Pa(i,o),a=ja(e.cloneUrl),c=e.branch;try{if(Ea(`${r}/.git`)){let l=Ut(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=Ko(r);await l.reset(["--hard",`origin/${c}`]),Wo(r,u),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Aa(_a(r),{recursive:!0}),await Ut().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ut(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Oa(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 Oa(t){let e=Ut(t);await e.raw(["config","user.email"]).then(o=>o.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}async function Na(t={profile:void 0}){let{cfg:e,profile:r}=Gr(t.profile),o=U(e.projectId);o&&cr(o),mr(o?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),gr(o?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),hr(o?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let n=kr(gn(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Kr("CLI_LOG",i,n);if(s.enabled){let p=new It(s);Wr(p),console.log(`[log] file logging \u2192 ${p.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=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 p=kr(gn(),".codepipe",r?kr("profiles",r,"context"):"context");if(await dn(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await fo({cfg:e,secrets:o,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),a||await dn(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let g=kr(gn(),".codepipe",r?kr("profiles",r,"context-config"):"context-config");Yr(a.contextDir,g,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=po(e,{...a?{workspace:a}:{},onEvent:p=>{p.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function d(p){u||(u=!0,console.log(`
441
+ [${p}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>d("SIGINT")),process.on("SIGTERM",()=>d("SIGTERM")),await new Promise(()=>{})}import{hostname as of}from"node:os";import{spawnSync as Jd}from"node:child_process";function Xd(){try{return Jd("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Ua(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Xd(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Lt}from"node:os";import{mkdirSync as Qd,readFileSync as La,writeFileSync as Zd,existsSync as hn}from"node:fs";import{dirname as ef,join as et}from"node:path";hn(".env")&&process.loadEnvFile(".env");function tf(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function $e(t){let e=L("SANDBOX_CONFIG");if(e)return e;let r=et(Lt(),".codepipe","worker");return t?et(r,"profiles",t,"config.json"):et(r,"config.json")}function Da(){return et(Lt(),".devpipe-sandbox","config.json")}function mo(){dt(et(Lt(),".devpipe"),et(Lt(),".codepipe")),L("SANDBOX_CONFIG")||dt(et(Lt(),".devpipe-sandbox"),et(Lt(),".codepipe-sandbox"))}function ne(t){let e=$e(t),r=null;return hn(e)?r=JSON.parse(La(e,"utf-8")):!t&&!L("SANDBOX_CONFIG")&&hn(Da())&&(r=JSON.parse(La(Da(),"utf-8"))),r?(r.planningLane=tf(),r):null}function Ba(t,e){let r=$e(e);Qd(ef(r),{recursive:!0}),Zd(r,JSON.stringify(t,null,2)+`
442
+ `,{mode:384})}import rf from"ws";var Dt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(o.signal=e);let n=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(n,o)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(o.signal=r);let n=await fetch(`${this.hubUrl}/jobs/heartbeat`,o);if(n.status===410)return"claim_lost";if(!n.ok)throw new Error(`heartbeat failed: ${n.status} ${await n.text()}`);return"ok"}async releaseJob(e,r,o){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};o&&(n.signal=o);let i=await fetch(`${this.hubUrl}/jobs/release`,n);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new rf(e)}};async function gt(t){mo();let e=ne(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${$e(t.profile)}.`),process.exit(1));let r=t.name??of(),o=Ua({projects:t.projects??[],llm:t.llm??null}),n=new Dt(t.hub.replace(/\/$/,"")),i=Zr(),s=Pe(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});Ba({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${$e(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as zf,readFileSync as Sn,readdirSync as Jf,writeFileSync as Xf}from"node:fs";import{dirname as Qf,join as vr,resolve as Zf}from"node:path";import{spawn as uf}from"node:child_process";import{existsSync as pf}from"node:fs";import{spawn as nf}from"node:child_process";var Ma=16e3,Ga=5e3,Fa=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),sf="\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B \u0434\u0438\u0430\u043B\u043E\u0433. \u0422\u0435\u043F\u0435\u0440\u044C, \u043E\u043F\u0438\u0440\u0430\u044F\u0441\u044C \u043D\u0430 \u0432\u0441\u0451, \u0447\u0442\u043E \u043C\u044B \u043E\u0431\u0441\u0443\u0434\u0438\u043B\u0438, \u043D\u0430\u043F\u0438\u0448\u0438 \u0444\u0430\u0439\u043B DRAFT.md \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u043F\u043E \u043E\u043F\u0438\u0441\u0430\u043D\u043D\u043E\u043C\u0443 \u043A\u043E\u043D\u0442\u0440\u0430\u043A\u0442\u0443 (\u0441\u0442\u0440\u043E\u043A\u0430 1 \u2014 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u226480 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C, \u0441\u0442\u0440\u043E\u043A\u0430 2 \u043F\u0443\u0441\u0442\u0430\u044F, \u0434\u0430\u043B\u044C\u0448\u0435 \u0442\u0435\u043B\u043E \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C \u0432 Markdown) \u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0438 \u0440\u0430\u0431\u043E\u0442\u0443. \u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043F\u0438\u0448\u0438.";function yn(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function af(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}function cf(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function ht(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function wn(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
443
+ `}async function Ha(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Fe;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let o=e.onActivity,n=c=>{if(o)try{o(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),u=c.type;if(u==="assistant"){let d=c.message;for(let p of d?.content??[]){let g=p.type;if(g==="text"){let f=String(p.text??"").trim();f&&n({ts:l,kind:"text",author:"agent",text:yn(f,Ma)})}else if(g==="tool_use"){let f=String(p.name??""),h=p.input?.file_path??p.input?.path,S=af(h,e.workspaceDir);n({ts:l,kind:"tool",author:"agent",tool:f,...S?{file:S}:{}})}}return}if(u==="user"){let d=c.message;for(let p of d?.content??[])if(p.type==="tool_result"){let g=p.is_error===!0,f=g?yn(cf(p.content),200):"";n({ts:l,kind:"tool_result",author:"agent",isError:g,...f?{text:f}:{}})}return}if(u==="result"){s=c;let d=String(c.subtype??"").trim();n({ts:l,kind:"result",author:"agent",...d?{text:d}:{}});return}if(u==="system"){let d=String(c.subtype??"").trim();d&&n({ts:l,kind:"system",author:"agent",text:d})}};return n({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let u=nf(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let d=!1,p=!1,g=null,f=()=>{d=!0,u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),Ga)};e.signal?.addEventListener("abort",f,{once:!0});let h=null,S=()=>{h&&clearTimeout(h),h=setTimeout(()=>{p=!0,console.warn(`[claude:chat] idle for ${Fa}ms \u2014 ending session`),u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),Ga)},Fa)},b=()=>{g&&clearTimeout(g),h&&clearTimeout(h),e.signal?.removeEventListener("abort",f)},y=!0,w=j=>{if(!(!y||u.stdin.destroyed))try{u.stdin.write(j)}catch{}};w(wn(e.prompt)),S(),(async()=>{try{for await(let j of e.interactive.inbox){if(d||!y)break;if(S(),j.kind==="user")n({ts:Date.now(),kind:"text",author:"user",text:yn(j.text,Ma)}),w(wn(j.text));else{w(wn(sf)),y=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let x="",O=j=>{let v;try{v=JSON.parse(j)}catch{return}a(v)};u.stdout.on("data",j=>{i.push(j),S(),x+=j;let v;for(;(v=x.indexOf(`
444
444
  `))!==-1;){let m=x.slice(0,v).trim();x=x.slice(v+1),m&&O(m)}}),u.stderr.on("data",j=>{i.push(j);for(let v of j.split(`
445
- `)){let m=v.trim();m&&console.warn(`[claude:chat:stderr] ${m}`)}}),u.on("error",j=>{b(),l(j)}),u.on("close",j=>{if(b(),f){l(new Me);return}if(p){l(new Error("chat session ended: idle for too long without a reply"));return}x.trim()&&O(x.trim()),console.log(`[claude:chat] exit code=${j}`),c({artifactPaths:[],log:i.join(""),usage:tf(s)})})})}function tf(t){let e=ct();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=gt(r.input_tokens),e.outputTokens=gt(r.output_tokens),e.cacheReadInputTokens=gt(r.cache_read_input_tokens),e.cacheCreationInputTokens=gt(r.cache_creation_input_tokens)),e.totalCostUsd=gt(t.total_cost_usd),e.numTurns=gt(t.num_turns),e.durationMs=gt(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Dt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Me=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},nf=5e3,kr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Ba(this.binary,e);if(e.signal?.aborted)throw new Me;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let d of e.addDirs??[])r.push("--add-dir",d);let o=[],n=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=d=>{if(d){if(d.type==="result"){i=d;return}if(d.type==="rate_limit_event"){let h=lf(d.rate_limit_info);h&&(!l||h.utilization>l.utilization)&&(l=h);return}if(d.type==="assistant"){let h=d.message;typeof h?.model=="string"&&(c=h.model);let S=h?.usage;S&&(a+=1,s.input+=se(S.input_tokens),s.output+=se(S.output_tokens),s.cacheRead+=se(S.cache_read_input_tokens),s.cacheCreate+=se(S.cache_creation_input_tokens))}}},f=e.role,p=e.onActivity,g=d=>{if(p)for(let h of pf(d,e.workspaceDir))try{p(h)}catch{}};return p?.({ts:Date.now(),kind:"start",text:`${f} job started`}),console.log(`[claude] spawn ${this.binary} role=${f}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((d,h)=>{let S=rf(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 b=!1,y=null,w=()=>{b=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),S.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),S.kill("SIGKILL")},nf)};e.signal?.addEventListener("abort",w,{once:!0});let x=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",w)},O="";S.stdout.on("data",j=>{o.push(j),O+=j;let v;for(;(v=O.indexOf(`
446
- `))!==-1;){let m=O.slice(0,v).trim();if(O=O.slice(v+1),m){let R=Ma(m);u(R),R&&g(R)}}}),S.stderr.on("data",j=>{o.push(j),n.push(j);for(let v of j.split(`
447
- `)){let m=v.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),S.on("error",j=>{x(),h(j)}),S.on("close",j=>{if(x(),b){h(new Me);return}if(O.trim()){let m=Ma(O.trim());u(m),m&&g(m)}let v=i?.is_error===!0;if(j!==0||v){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,R=typeof i?.subtype=="string"?i.subtype:void 0,k=typeof i?.result=="string"?i.result:void 0;h(new Dt(sf(j,i,n.join("")),{code:j,apiErrorStatus:m,subtype:R,resultText:k,retryAfterMs:af(i)}));return}console.log("[claude] exit code=0"),d({artifactPaths:[],log:o.join(""),usage:uf(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("/")&&of(o))}};function Ma(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: ${et(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=cf(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=Fa(n.content);console.log(`[claude] tool_result (error)${i?`: ${et(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)} ${et(JSON.stringify(e),200)}`),e}function sf(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(et(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(et(r.trim().split(`
445
+ `)){let m=v.trim();m&&console.warn(`[claude:chat:stderr] ${m}`)}}),u.on("error",j=>{b(),l(j)}),u.on("close",j=>{if(b(),d){l(new Fe);return}if(p){l(new Error("chat session ended: idle for too long without a reply"));return}x.trim()&&O(x.trim()),console.log(`[claude:chat] exit code=${j}`),c({artifactPaths:[],log:i.join(""),usage:lf(s)})})})}function lf(t){let e=lt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=ht(r.input_tokens),e.outputTokens=ht(r.output_tokens),e.cacheReadInputTokens=ht(r.cache_read_input_tokens),e.cacheCreationInputTokens=ht(r.cache_creation_input_tokens)),e.totalCostUsd=ht(t.total_cost_usd),e.numTurns=ht(t.num_turns),e.durationMs=ht(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Bt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Fe=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},df=5e3,br=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Ha(this.binary,e);if(e.signal?.aborted)throw new Fe;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);let o=[],n=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let h=hf(f.rate_limit_info);h&&(!l||h.utilization>l.utilization)&&(l=h);return}if(f.type==="assistant"){let h=f.message;typeof h?.model=="string"&&(c=h.model);let S=h?.usage;S&&(a+=1,s.input+=ae(S.input_tokens),s.output+=ae(S.output_tokens),s.cacheRead+=ae(S.cache_read_input_tokens),s.cacheCreate+=ae(S.cache_creation_input_tokens))}}},d=e.role,p=e.onActivity,g=f=>{if(p)for(let h of wf(f,e.workspaceDir))try{p(h)}catch{}};return p?.({ts:Date.now(),kind:"start",text:`${d} job started`}),console.log(`[claude] spawn ${this.binary} role=${d}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,h)=>{let S=uf(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 b=!1,y=null,w=()=>{b=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${d}`),S.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),S.kill("SIGKILL")},df)};e.signal?.addEventListener("abort",w,{once:!0});let x=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",w)},O="";S.stdout.on("data",j=>{o.push(j),O+=j;let v;for(;(v=O.indexOf(`
446
+ `))!==-1;){let m=O.slice(0,v).trim();if(O=O.slice(v+1),m){let T=Ka(m);u(T),T&&g(T)}}}),S.stderr.on("data",j=>{o.push(j),n.push(j);for(let v of j.split(`
447
+ `)){let m=v.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),S.on("error",j=>{x(),h(j)}),S.on("close",j=>{if(x(),b){h(new Fe);return}if(O.trim()){let m=Ka(O.trim());u(m),m&&g(m)}let v=i?.is_error===!0;if(j!==0||v){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,T=typeof i?.subtype=="string"?i.subtype:void 0,k=typeof i?.result=="string"?i.result:void 0;h(new Bt(ff(j,i,n.join("")),{code:j,apiErrorStatus:m,subtype:T,resultText:k,retryAfterMs:mf(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:o.join(""),usage:yf(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("/")&&pf(o))}};function Ka(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: ${tt(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=gf(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let o=e.message;for(let n of o?.content??[])if(n.type==="tool_result")if(n.is_error===!0){let i=qa(n.content);console.log(`[claude] tool_result (error)${i?`: ${tt(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)} ${tt(JSON.stringify(e),200)}`),e}function ff(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(tt(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(tt(r.trim().split(`
448
448
  `).slice(-5).join(`
449
- `),500)),o.join(" \u2014 ")}function af(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 Fa(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function cf(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=${et(r,80)}`}return""}function et(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function se(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function lf(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=se(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:se(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 uf(t,e,r,o){let n=ct(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=se(i.input_tokens),n.outputTokens=se(i.output_tokens),n.cacheReadInputTokens=se(i.cache_read_input_tokens),n.cacheCreationInputTokens=se(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=se(t?.total_cost_usd),n.numTurns=t&&se(t.num_turns)>0?se(t.num_turns):r,n.durationMs=se(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var Ga=200;function pf(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:et(c,Ga)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,f=df(u,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return i}if(o==="user"){let n=t.message,i=[];for(let s of n?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?et(Fa(s.content),Ga):"";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 df(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 ff,writeFileSync as Bt}from"node:fs";import{dirname as mf,join as Mt}from"node:path";function Ha(t,e,r){let o=Mt(t,e);ff(mf(o),{recursive:!0}),Bt(o,r)}var br=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},o=r.trackerIssueKey??"TASK",n=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=gf(o,n,i);Bt(Mt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Bt(Mt(e.workspaceDir,"SOLUTION.md"),hf(o,n,i,a)),s.push("SOLUTION.md"),Bt(Mt(e.workspaceDir,"QUESTIONS.md"),yf(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Ha(e.workspaceDir,"changes/sample.patch",wf(o,n,a)),s.push("changes/sample.patch"),Ha(e.workspaceDir,"diff-summary.md",kf(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Bt(Mt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${o})
450
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:ct()}}async runInteractive(e){let r=e.onActivity,o=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),o("\u041F\u0440\u0438\u0432\u0435\u0442! \u041E\u043F\u0438\u0448\u0438\u0442\u0435 \u0437\u0430\u0434\u0430\u0447\u0443, \u043A\u043E\u0442\u043E\u0440\u0443\u044E \u0445\u043E\u0442\u0438\u0442\u0435 \u0441\u0444\u043E\u0440\u043C\u0443\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C.");let n="\u0427\u0435\u0440\u043D\u043E\u0432\u0438\u043A \u0438\u0437 \u0447\u0430\u0442\u0430";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Me;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(n=i.text.trim().slice(0,80)),o(`\u041F\u043E\u043D\u044F\u043B: **${i.text.trim()}**. \u0427\u0442\u043E-\u043D\u0438\u0431\u0443\u0434\u044C \u0435\u0449\u0451 \u0443\u0442\u043E\u0447\u043D\u0438\u0442\u044C?`);else break}return Bt(Mt(e.workspaceDir,"DRAFT.md"),`${n}
449
+ `),500)),o.join(" \u2014 ")}function mf(t){if(!t)return;let e=t.retry_after;if(typeof e=="number"&&e>0)return Math.round(e*1e3);let r=typeof t.result=="string"?t.result:"",o=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(r),n=o?Number(o[1]??o[2]):NaN;return Number.isFinite(n)&&n>0?n*1e3:void 0}function qa(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function gf(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=${tt(r,80)}`}return""}function tt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function ae(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function hf(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=ae(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:ae(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:o,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(n.surpassedThreshold=e.surpassedThreshold),n}function yf(t,e,r,o){let n=lt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=ae(i.input_tokens),n.outputTokens=ae(i.output_tokens),n.cacheReadInputTokens=ae(i.cache_read_input_tokens),n.cacheCreationInputTokens=ae(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=ae(t?.total_cost_usd),n.numTurns=t&&ae(t.num_turns)>0?ae(t.num_turns):r,n.durationMs=ae(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var Wa=200;function wf(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:tt(c,Wa)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,d=kf(u,e);i.push({ts:r,kind:"tool",tool:c,...d?{file:d}:{}})}}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?tt(qa(s.content),Wa):"";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 kf(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}import{mkdirSync as bf,writeFileSync as Mt}from"node:fs";import{dirname as $f,join as Gt}from"node:path";function Ya(t,e,r){let o=Gt(t,e);bf($f(o),{recursive:!0}),Mt(o,r)}var $r=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},o=r.trackerIssueKey??"TASK",n=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=xf(o,n,i);Mt(Gt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Mt(Gt(e.workspaceDir,"SOLUTION.md"),vf(o,n,i,a)),s.push("SOLUTION.md"),Mt(Gt(e.workspaceDir,"QUESTIONS.md"),Sf(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Ya(e.workspaceDir,"changes/sample.patch",Cf(o,n,a)),s.push("changes/sample.patch"),Ya(e.workspaceDir,"diff-summary.md",Rf(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Mt(Gt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${o})
450
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:lt()}}async runInteractive(e){let r=e.onActivity,o=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),o("\u041F\u0440\u0438\u0432\u0435\u0442! \u041E\u043F\u0438\u0448\u0438\u0442\u0435 \u0437\u0430\u0434\u0430\u0447\u0443, \u043A\u043E\u0442\u043E\u0440\u0443\u044E \u0445\u043E\u0442\u0438\u0442\u0435 \u0441\u0444\u043E\u0440\u043C\u0443\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C.");let n="\u0427\u0435\u0440\u043D\u043E\u0432\u0438\u043A \u0438\u0437 \u0447\u0430\u0442\u0430";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Fe;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(n=i.text.trim().slice(0,80)),o(`\u041F\u043E\u043D\u044F\u043B: **${i.text.trim()}**. \u0427\u0442\u043E-\u043D\u0438\u0431\u0443\u0434\u044C \u0435\u0449\u0451 \u0443\u0442\u043E\u0447\u043D\u0438\u0442\u044C?`);else break}return Mt(Gt(e.workspaceDir,"DRAFT.md"),`${n}
451
451
 
452
452
  \u0421\u0444\u043E\u0440\u043C\u0438\u0440\u043E\u0432\u0430\u043D\u043E \u0432 \u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u043E\u043C \u0447\u0430\u0442\u0435 (mock runner).
453
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:ct()}}};function gf(t,e,r){return`# ${t} \u2014 Estimate
453
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:lt()}}};function xf(t,e,r){return`# ${t} \u2014 Estimate
454
454
 
455
455
  **Title:** ${e}
456
456
 
@@ -471,7 +471,7 @@ production-grade estimates.)
471
471
  ${r.split(`
472
472
  `).slice(0,8).join(`
473
473
  `).trim()||"(empty)"}
474
- `}function hf(t,e,r,o){let n=o?`
474
+ `}function vf(t,e,r,o){let n=o?`
475
475
  ## Reviewer rework instruction
476
476
 
477
477
  > ${o.split(`
@@ -500,10 +500,10 @@ TBD (mock runner does not yet inspect project code).
500
500
  ${r.split(`
501
501
  `).slice(0,8).join(`
502
502
  `).trim()||"(empty)"}
503
- `}function yf(t){return`# ${t} \u2014 Open questions
503
+ `}function Sf(t){return`# ${t} \u2014 Open questions
504
504
 
505
505
  (none \u2014 mock runner did not surface ambiguities.)
506
- `}function wf(t,e,r){let o=r?` (rework: ${r.split(`
506
+ `}function Cf(t,e,r){let o=r?` (rework: ${r.split(`
507
507
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
508
508
  index 0000000..1111111 100644
509
509
  --- a/CHANGELOG.md
@@ -514,7 +514,7 @@ index 0000000..1111111 100644
514
514
  +- mock-runner placeholder change for slice 5 testing.
515
515
  +
516
516
  # Changelog
517
- `}function kf(t,e,r){return`# ${t} \u2014 Diff summary
517
+ `}function Rf(t,e,r){return`# ${t} \u2014 Diff summary
518
518
 
519
519
  **Title:** ${e}
520
520
  ${r?`
@@ -525,88 +525,95 @@ ${r?`
525
525
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
526
526
 
527
527
  (Mock-runner output. Replace with claude-headless for production patches.)
528
- `}function Ka(t){switch(t){case"mock":return new br;case"claude-headless":return new kr;default:return null}}function Ya(t=process.env){return{maxAttempts:mo(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:mo(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:mo(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:mo(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var bf=new Set([429,500,502,503,529]),Wa=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,$f=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,xf=new Set(["error_max_turns"]);function vf(t){if(t instanceof Dt){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return $f.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&xf.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:bf.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Wa.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 Wa.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var qa=/(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 Va(t){if(t instanceof Dt){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&qa.test(o)}let e=t instanceof Error?t.message:String(t);return qa.test(e)}function Sf(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 za(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=vf(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let u=Sf(s,r.policy,c.retryAfterMs);if(Date.now()+u>n)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await o(u)}}function mo(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as Cf,rmSync as Tf,writeFileSync as Ja}from"node:fs";import{tmpdir as Rf}from"node:os";import{join as wn}from"node:path";function go(t){return`[url "https://${t}/"]
528
+ `}function Va(t){switch(t){case"mock":return new $r;case"claude-headless":return new br;default:return null}}function Xa(t=process.env){return{maxAttempts:go(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:go(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:go(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:go(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var Tf=new Set([429,500,502,503,529]),za=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,If=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,jf=new Set(["error_max_turns"]);function Pf(t){if(t instanceof Bt){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return If.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&jf.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:Tf.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:za.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 za.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var Ja=/(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 Qa(t){if(t instanceof Bt){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&Ja.test(o)}let e=t instanceof Error?t.message:String(t);return Ja.test(e)}function Ef(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 Za(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=Pf(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let u=Ef(s,r.policy,c.retryAfterMs);if(Date.now()+u>n)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await o(u)}}function go(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as Af,rmSync as _f,writeFileSync as ec}from"node:fs";import{tmpdir as Of}from"node:os";import{join as kn}from"node:path";function ho(t){return`[url "https://${t}/"]
529
529
  insteadOf = git@${t}:
530
530
  insteadOf = ssh://git@${t}/
531
- `}var If=go("github.com"),jf=go("bitbucket.org"),Pf=go("gitlab.com");function Xa(t,e){if(t.length===0)return null;let r=Cf(wn(Rf(),"devpipe-gitcreds-")),o=wn(r,"credentials"),n=wn(r,"gitconfig");return Ja(o,t.join(`
531
+ `}var Nf=ho("github.com"),Uf=ho("bitbucket.org"),Lf=ho("gitlab.com");function tc(t,e){if(t.length===0)return null;let r=Af(kn(Of(),"devpipe-gitcreds-")),o=kn(r,"credentials"),n=kn(r,"gitconfig");return ec(o,t.join(`
532
532
  `)+`
533
- `,{mode:384}),Ja(n,`[credential]
533
+ `,{mode:384}),ec(n,`[credential]
534
534
  helper = store --file=${o}
535
- `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{Tf(r,{recursive:!0,force:!0})}catch{}}}}function kn(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(If)),t.bitbucket?.apiToken&&(e.push(`https://${ut}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(jf)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Pf)),Xa(e,r)}function Qa(t,e){if(t.contextWrite?.token){let r=vt(e)??"github.com",o=Ur(r);return Xa([`https://${o}:${t.contextWrite.token}@${r}`],[go(r)])}return kn(t)}import{spawn as ec}from"node:child_process";import{existsSync as ho,mkdirSync as yo,readFileSync as Ef,rmSync as bn,symlinkSync as Af}from"node:fs";import{homedir as _f}from"node:os";import{dirname as wo,join as ht}from"node:path";function tc(){return ht(_f(),".codepipe-sandbox","repos")}var Gt=new Map;function rc(t,e){let o=(Gt.get(t)??Promise.resolve()).then(e,e),n=o.then(()=>{Gt.get(t)===n&&Gt.delete(t)},()=>{Gt.get(t)===n&&Gt.delete(t)});return Gt.set(t,n),o}function Za(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 oc(t,e,r,o,n){if(ho(ht(t,".git"))){let i=async s=>{await ee(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],n),await ee(t,["reset","--hard",`origin/${s}`],n),await ee(t,["clean","-fdx"],n)};try{return await i(r),r}catch(s){if(!o||o===r||!Za(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}ho(t)&&bn(t,{recursive:!0,force:!0}),yo(wo(t),{recursive:!0});try{return await ee(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],n),r}catch(i){if(!o||o===r||!Za(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),ho(t)&&bn(t,{recursive:!0,force:!0}),yo(wo(t),{recursive:!0}),await ee(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function nc(t){await ee(t.workspacePath,["reset","--hard",t.baseSha]),await ee(t.workspacePath,["clean","-fdx"])}var ko="CodePipe Agent",bo="codepipe@codepartner.ee";async function ic(t,e){let r=t.workspacePath;await ee(r,["add","-A"]);let o=(await Ee(r,["write-tree"])).trim(),n=(await Ee(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:ko,GIT_AUTHOR_EMAIL:bo,GIT_COMMITTER_NAME:ko,GIT_COMMITTER_EMAIL:bo};return(await Ee(r,["commit-tree",o,"-m",e],i)).trim()}async function sc(t,e,r,o,n){try{await ee(t.workspacePath,["push","--force",o,`${e}:refs/heads/${r}`],n)}catch(i){let s=i instanceof Error?i.message:String(i);throw vt(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 ac(t,e){return Ee(t.workspacePath,["diff","--binary",t.baseSha,e])}async function cc(t,e,r,o,n){await ee(t.workspacePath,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],n),await ee(t.workspacePath,["checkout","--force",r])}async function $n(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:ko,GIT_AUTHOR_EMAIL:bo,GIT_COMMITTER_NAME:ko,GIT_COMMITTER_EMAIL:bo};(await Ee(o,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ee(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 ee(o,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ee(o,["merge","--no-commit","--no-ff",`origin/${e}`],n)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Ee(o,["diff","--name-only","--diff-filter=U"])).split(`
536
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await Ee(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 ee(t,e,r){return new Promise((o,n)=>{let i=ec("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}):
537
- ${s.join("").trim()||"(no stderr)"}`))})})}function Ee(t,e,r){return new Promise((o,n)=>{let i=ec("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}):
538
- ${a.join("").trim()||"(no stderr)"}`))})})}function lc(t,e){ho(t)&&bn(t,{recursive:!0,force:!0}),yo(wo(t),{recursive:!0}),Af(e,t,"dir")}async function uc(t,e,r){await ee(t,["worktree","prune"]).catch(()=>{}),yo(wo(r),{recursive:!0}),await ee(t,["worktree","add","--detach",r,`origin/${e}`])}async function pc(t,e,r,o="worktree",n){return r.length===0?[]:rc(e,async()=>{let i=[];for(let s of r){let a=ht(tc(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await oc(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 Ee(a,["rev-parse","HEAD"])).trim(),u=ht(t,"code",s.name);o==="direct"?(lc(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await uc(a,c,u),console.log(`[git] code: worktree ${u} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:u,cachePath:a,ref:c,baseSha:l})}return i})}async function dc(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=r;return rc(e,async()=>{let s=ht(tc(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await oc(s,i.cloneUrl,i.ref,void 0,n)}catch(l){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(l instanceof Error?l.message:String(l)))}let a=ht(t,"context");o==="direct"?(lc(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await uc(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await Ee(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function fc(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await ee(r,["add","-A",...o]).catch(()=>{});let n;try{n=await Ee(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...o])}catch{return[]}let i=n.split(`
539
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Ef(ht(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as Of}from"node:fs";import{join as Nf}from"node:path";var xn=8*1024,Ft=class extends Error{},$r="meta/build-result.json";function mc(t){let e=Nf(t,$r),r;try{r=Of(e,"utf-8")}catch{throw new Ft(`BUILD produced no ${$r} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(u){throw new Ft(`${$r} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!o||typeof o!="object")throw new Ft(`${$r} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new Ft(`${$r}: "ok" must be a boolean`);let i=n.ok,a=(Array.isArray(n.steps)?n.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let f=u,p=typeof f.name=="string"?f.name:null,g=typeof f.exitCode=="number"?f.exitCode:null;if(p===null||g===null)return[];let d={name:p,exitCode:g};return typeof f.durationMs=="number"&&(d.durationMs=f.durationMs),[d]}),c=typeof n.logTail=="string"?Uf(n.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof n.failedStep=="string"&&n.failedStep)l.failedStep=n.failedStep;else if(!i){let u=a.find(f=>f.exitCode!==0);u&&(l.failedStep=u.name)}return l}function Uf(t){let e=Buffer.from(t,"utf-8");return e.length<=xn?t:`\u2026 [${e.length-xn} bytes elided] \u2026
540
- `+e.subarray(e.length-xn).toString("utf-8")}import{lstatSync as Lf,mkdtempSync as Df,readFileSync as Bf,readdirSync as hc,rmSync as gc}from"node:fs";import{tmpdir as Mf}from"node:os";import{join as $o,relative as Gf}from"node:path";var yc=new Set(["code","context"]);function wc(t){let e=Df($o(Mf(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>gc(e,{recursive:!0,force:!0}),listFiles:()=>kc(e,e),readFile:r=>Bf($o(e,r),"utf-8"),clean:()=>{for(let r of hc(e))yc.has(r)||gc($o(e,r),{recursive:!0,force:!0})}}}function kc(t,e){let r=[];for(let o of hc(e)){let n=$o(e,o),i=Lf(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&yc.has(o))continue;r.push(...kc(t,n))}else r.push(Gf(t,n))}return r}var xo=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Yf=new Set(["implement","resolve-conflict"]);function Vf(t){let e=Buffer.from(t,"utf-8");if(e.length<=xo)return t;let r=Math.floor(xo/4),o=xo-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}
535
+ `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{_f(r,{recursive:!0,force:!0})}catch{}}}}function bn(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Nf)),t.bitbucket?.apiToken&&(e.push(`https://${pt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Uf)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Lf)),tc(e,r)}function rc(t,e){if(t.contextWrite?.token){let r=St(e)??"github.com",o=Lr(r);return tc([`https://${o}:${t.contextWrite.token}@${r}`],[ho(r)])}return bn(t)}import{spawn as nc}from"node:child_process";import{existsSync as yo,mkdirSync as wo,readFileSync as Df,rmSync as $n,symlinkSync as Bf}from"node:fs";import{homedir as Mf}from"node:os";import{dirname as ko,join as yt}from"node:path";function ic(){return yt(Mf(),".codepipe-sandbox","repos")}var Ft=new Map;function sc(t,e){let o=(Ft.get(t)??Promise.resolve()).then(e,e),n=o.then(()=>{Ft.get(t)===n&&Ft.delete(t)},()=>{Ft.get(t)===n&&Ft.delete(t)});return Ft.set(t,n),o}function oc(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 ac(t,e,r,o,n){if(yo(yt(t,".git"))){let i=async s=>{await ee(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],n),await ee(t,["reset","--hard",`origin/${s}`],n),await ee(t,["clean","-fdx"],n)};try{return await i(r),r}catch(s){if(!o||o===r||!oc(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}yo(t)&&$n(t,{recursive:!0,force:!0}),wo(ko(t),{recursive:!0});try{return await ee(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],n),r}catch(i){if(!o||o===r||!oc(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),yo(t)&&$n(t,{recursive:!0,force:!0}),wo(ko(t),{recursive:!0}),await ee(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function cc(t){await ee(t.workspacePath,["reset","--hard",t.baseSha]),await ee(t.workspacePath,["clean","-fdx"])}var bo="CodePipe Agent",$o="codepipe@codepartner.ee";async function lc(t,e){let r=t.workspacePath;await ee(r,["add","-A"]);let o=(await Ae(r,["write-tree"])).trim(),n=(await Ae(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:bo,GIT_AUTHOR_EMAIL:$o,GIT_COMMITTER_NAME:bo,GIT_COMMITTER_EMAIL:$o};return(await Ae(r,["commit-tree",o,"-m",e],i)).trim()}async function uc(t,e,r,o,n){try{await ee(t.workspacePath,["push","--force",o,`${e}:refs/heads/${r}`],n)}catch(i){let s=i instanceof Error?i.message:String(i);throw St(o)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function pc(t,e){return Ae(t.workspacePath,["diff","--binary",t.baseSha,e])}async function dc(t,e,r,o,n){await ee(t.workspacePath,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],n),await ee(t.workspacePath,["checkout","--force",r])}async function xn(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:bo,GIT_AUTHOR_EMAIL:$o,GIT_COMMITTER_NAME:bo,GIT_COMMITTER_EMAIL:$o};(await Ae(o,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ee(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 ee(o,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ee(o,["merge","--no-commit","--no-ff",`origin/${e}`],n)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Ae(o,["diff","--name-only","--diff-filter=U"])).split(`
536
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await Ae(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 ee(t,e,r){return new Promise((o,n)=>{let i=nc("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}):
537
+ ${s.join("").trim()||"(no stderr)"}`))})})}function Ae(t,e,r){return new Promise((o,n)=>{let i=nc("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}):
538
+ ${a.join("").trim()||"(no stderr)"}`))})})}function fc(t,e){yo(t)&&$n(t,{recursive:!0,force:!0}),wo(ko(t),{recursive:!0}),Bf(e,t,"dir")}async function mc(t,e,r){await ee(t,["worktree","prune"]).catch(()=>{}),wo(ko(r),{recursive:!0}),await ee(t,["worktree","add","--detach",r,`origin/${e}`])}async function gc(t,e,r,o="worktree",n){return r.length===0?[]:sc(e,async()=>{let i=[];for(let s of r){let a=yt(ic(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await ac(a,s.cloneUrl,s.ref,s.defaultBranch,n)}catch(d){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let l=(await Ae(a,["rev-parse","HEAD"])).trim(),u=yt(t,"code",s.name);o==="direct"?(fc(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await mc(a,c,u),console.log(`[git] code: worktree ${u} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:u,cachePath:a,ref:c,baseSha:l})}return i})}async function hc(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=r;return sc(e,async()=>{let s=yt(ic(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await ac(s,i.cloneUrl,i.ref,void 0,n)}catch(l){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(l instanceof Error?l.message:String(l)))}let a=yt(t,"context");o==="direct"?(fc(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await mc(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await Ae(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function yc(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await ee(r,["add","-A",...o]).catch(()=>{});let n;try{n=await Ae(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...o])}catch{return[]}let i=n.split(`
539
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Df(yt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as Gf}from"node:fs";import{join as Ff}from"node:path";var vn=8*1024,Ht=class extends Error{},xr="meta/build-result.json";function wc(t){let e=Ff(t,xr),r;try{r=Gf(e,"utf-8")}catch{throw new Ht(`BUILD produced no ${xr} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(u){throw new Ht(`${xr} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!o||typeof o!="object")throw new Ht(`${xr} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new Ht(`${xr}: "ok" must be a boolean`);let i=n.ok,a=(Array.isArray(n.steps)?n.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let d=u,p=typeof d.name=="string"?d.name:null,g=typeof d.exitCode=="number"?d.exitCode:null;if(p===null||g===null)return[];let f={name:p,exitCode:g};return typeof d.durationMs=="number"&&(f.durationMs=d.durationMs),[f]}),c=typeof n.logTail=="string"?Hf(n.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof n.failedStep=="string"&&n.failedStep)l.failedStep=n.failedStep;else if(!i){let u=a.find(d=>d.exitCode!==0);u&&(l.failedStep=u.name)}return l}function Hf(t){let e=Buffer.from(t,"utf-8");return e.length<=vn?t:`\u2026 [${e.length-vn} bytes elided] \u2026
540
+ `+e.subarray(e.length-vn).toString("utf-8")}import{lstatSync as Kf,mkdtempSync as Wf,readFileSync as qf,readdirSync as bc,rmSync as kc}from"node:fs";import{tmpdir as Yf}from"node:os";import{join as xo,relative as Vf}from"node:path";var $c=new Set(["code","context"]);function xc(t){let e=Wf(xo(Yf(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>kc(e,{recursive:!0,force:!0}),listFiles:()=>vc(e,e),readFile:r=>qf(xo(e,r),"utf-8"),clean:()=>{for(let r of bc(e))$c.has(r)||kc(xo(e,r),{recursive:!0,force:!0})}}}function vc(t,e){let r=[];for(let o of bc(e)){let n=xo(e,o),i=Kf(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&$c.has(o))continue;r.push(...vc(t,n))}else r.push(Vf(t,n))}return r}var vo=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),em=new Set(["implement","resolve-conflict"]);function tm(t){let e=Buffer.from(t,"utf-8");if(e.length<=vo)return t;let r=Math.floor(vo/4),o=vo-r,n=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-o).toString("utf-8"),s=e.length-r-o;return`${n}
541
541
 
542
- \u2026 [${s} bytes elided \u2014 log capped at ${xo} bytes for upload] \u2026
542
+ \u2026 [${s} bytes elided \u2014 log capped at ${vo} bytes for upload] \u2026
543
543
 
544
- ${i}`}function zf(){let t=[],e=!1,r=null,o=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},n=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||o(i)},finalize(){e||(o({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,n()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function vr(t={}){fo();let e=ne(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=Hr("SANDBOX_LOG","sandbox",qf("./logs"));if(o.enabled){let v=new Rt(o);Kr(v),console.log(`[log] file logging \u2192 ${v.path} (rotate at ${o.maxBytes}B, keep ${o.maxFiles})`)}console.log(`codepipe-sandbox v${pe} (protocol ${Se})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let n=Ka(e.llm);console.log(`llm backend: ${n?n.name():"(none \u2014 will not claim agent jobs)"}`);let i=Ya();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new Lt(e.hubUrl,e.token),a=!1,c=new AbortController,l=new Map,u=null,f=null,p=!1,g=()=>{let v=s.openControlSocket();return u=v,v.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:pe,protocolVersion:Se};v.send(JSON.stringify(m))}),v.on("message",m=>{let R=m.toString("utf-8"),k=null;try{let T=JSON.parse(R);T&&typeof T=="object"&&(k=T)}catch{}if(k&&k.type==="hello"){let T=k;f=_r(T.protocolVersion);let I=f?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${T.platformVersion} (protocol ${T.protocolVersion}) \u2014 ${I}`),f&&(p=!1);return}if(k&&k.type==="pause_job"){let T=typeof k.jobId=="string"?k.jobId:"",I=T?l.get(T):void 0;I?(console.warn(`[ws] pause_job ${T} \u2014 aborting agent`),I.paused=!0,I.abort.abort()):console.log(`[ws] pause_job ${T} \u2014 not a running job, ignoring`),T&&v.send(JSON.stringify({type:"job_paused",jobId:T}));return}if(k&&(k.type==="chat_user_message"||k.type==="chat_finalize")){let T=typeof k.jobId=="string"?k.jobId:"",I=T?l.get(T):void 0;if(I?.chatInbox)if(k.type==="chat_user_message"){let $=typeof k.text=="string"?k.text:"";$.trim()&&I.chatInbox.push({kind:"user",text:$})}else I.chatInbox.finalize();else console.log(`[ws] ${String(k.type)} ${T} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${R}`)}),v.on("close",(m,R)=>{console.log(`[ws] closed code=${m} reason=${R?.toString()||""}`),u===v&&(u=null),!a&&setTimeout(g,2e3)}),v.on("error",m=>console.warn(`[ws] error: ${m.message}`)),v},d=g(),h=async v=>{for(;!a;){if(f===!1){p||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${pe}, protocol ${Se}) \u2014 not claiming jobs until versions align.`),p=!0),await new Promise(m=>setTimeout(m,5e3));continue}try{let m=await s.claim(c.signal,v);if(m.status===204)continue;if(m.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,a=!0;break}if(!m.ok){console.warn(`[claim:${v}] ${m.status} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3));continue}let R=await m.json();await S(s,R)}catch(m){if(c.signal.aborted)break;let R=m instanceof Error?m.message:String(m);console.warn(`[claim:${v}] error: ${R} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3))}}};async function S(v,m){let R={abort:new AbortController,paused:!1};m.role==="chat"&&(R.chatInbox=zf()),l.set(m.jobId,R);let k=!1,T=null,I=null,$=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),P=async()=>{try{await v.heartbeat(m.jobId)==="claim_lost"&&(k=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(M){let ye=M instanceof Error?M.message:String(M);console.warn(`[job] ${m.jobId} heartbeat error: ${ye}`)}};P();let B=setInterval(()=>{P()},$),H=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(y(m.prompt," \u2502 "));let xe=[],it=null,E=400,ue=25,Ge=500,_e=()=>{if(it&&(clearTimeout(it),it=null),xe.length===0)return;let M=xe.splice(0,xe.length),ye=u;if(!ye||ye.readyState!==ye.OPEN)return;let Fe={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:M};try{ye.send(JSON.stringify(Fe))}catch{}},Po=M=>{xe.push(M),xe.length>Ge&&xe.shift(),xe.length>=ue?_e():it||(it=setTimeout(_e,E))},st=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,Z=new Set,Eo=null;try{if(!n){k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:H,finishedAt:new Date().toISOString()});return}let M=wc(m.jobId);console.log(`[job] ${m.jobId} workspace=${M.dir}`);let ye=b(m,r);T=ye.gitCreds,I=ye.contextGitCreds;let Fe=T?.env,Wn=ye.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ye.claudeOauthToken}:void 0,He=[],rr=null,Ao=null;try{let N="worktree";He=await pc(M.dir,m.projectId,m.projectRepos,N,Fe);let _=await dc(M.dir,m.projectId,m.contextRepo,N,Fe);Ao=_,rr=_?.workspacePath??null}catch(N){let _=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} materialize failed: ${_}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${_}`},startedAt:H,finishedAt:new Date().toISOString()}),M.dispose();return}let qn=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let N=m.contextRepo?.cloneUrl;if(!N||!Fe)throw new Error(N?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let _ of m.deliveries){let z=He.find(J=>J.name===_.name);z&&(await cc(z,_.deliveryRef,_.deliverySha,N,Fe),console.log(`[job] ${m.jobId} ${z.name}: checked out delivery ${_.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await qn()}catch(N){let _=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} delivery checkout failed: ${_}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${_}`},startedAt:H,finishedAt:new Date().toISOString()}),M.dispose();return}let Yn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},Vn="";if(m.role==="resolve-conflict")try{let N=[];for(let _ of He){let z=Yn[_.name];if(!z)continue;let J=await $n(_,z,Fe);console.log(`[job] ${m.jobId} ${_.name}: merged ${z} into ${_.ref} \u2014 ${J.length} conflicted file(s)`),J.length>0?N.push(`- **${_.name}**:`,...J.map(xt=>` - \`${xt}\``)):N.push(`- **${_.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Vn=`
544
+ ${i}`}function rm(){let t=[],e=!1,r=null,o=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},n=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||o(i)},finalize(){e||(o({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,n()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function Sr(t={}){mo();let e=ne(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=Kr("SANDBOX_LOG","sandbox",Zf("./logs"));if(o.enabled){let v=new It(o);Wr(v),console.log(`[log] file logging \u2192 ${v.path} (rotate at ${o.maxBytes}B, keep ${o.maxFiles})`)}console.log(`codepipe-sandbox v${me} (protocol ${Se})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let n=Va(e.llm);console.log(`llm backend: ${n?n.name():"(none \u2014 will not claim agent jobs)"}`);let i=Xa();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new Dt(e.hubUrl,e.token),a=!1,c=new AbortController,l=new Map,u=null,d=null,p=!1,g=()=>{let v=s.openControlSocket();return u=v,v.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:me,protocolVersion:Se};v.send(JSON.stringify(m))}),v.on("message",m=>{let T=m.toString("utf-8"),k=null;try{let R=JSON.parse(T);R&&typeof R=="object"&&(k=R)}catch{}if(k&&k.type==="hello"){let R=k;d=Or(R.protocolVersion);let I=d?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${R.platformVersion} (protocol ${R.protocolVersion}) \u2014 ${I}`),d&&(p=!1);return}if(k&&k.type==="pause_job"){let R=typeof k.jobId=="string"?k.jobId:"",I=R?l.get(R):void 0;I?(console.warn(`[ws] pause_job ${R} \u2014 aborting agent`),I.paused=!0,I.abort.abort()):console.log(`[ws] pause_job ${R} \u2014 not a running job, ignoring`),R&&v.send(JSON.stringify({type:"job_paused",jobId:R}));return}if(k&&(k.type==="chat_user_message"||k.type==="chat_finalize")){let R=typeof k.jobId=="string"?k.jobId:"",I=R?l.get(R):void 0;if(I?.chatInbox)if(k.type==="chat_user_message"){let $=typeof k.text=="string"?k.text:"";$.trim()&&I.chatInbox.push({kind:"user",text:$})}else I.chatInbox.finalize();else console.log(`[ws] ${String(k.type)} ${R} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${T}`)}),v.on("close",(m,T)=>{console.log(`[ws] closed code=${m} reason=${T?.toString()||""}`),u===v&&(u=null),!a&&setTimeout(g,2e3)}),v.on("error",m=>console.warn(`[ws] error: ${m.message}`)),v},f=g(),h=async v=>{for(;!a;){if(d===!1){p||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${me}, protocol ${Se}) \u2014 not claiming jobs until versions align.`),p=!0),await new Promise(m=>setTimeout(m,5e3));continue}try{let m=await s.claim(c.signal,v);if(m.status===204)continue;if(m.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,a=!0;break}if(!m.ok){console.warn(`[claim:${v}] ${m.status} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3));continue}let T=await m.json();await S(s,T)}catch(m){if(c.signal.aborted)break;let T=m instanceof Error?m.message:String(m);console.warn(`[claim:${v}] error: ${T} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3))}}};async function S(v,m){let T={abort:new AbortController,paused:!1};m.role==="chat"&&(T.chatInbox=rm()),l.set(m.jobId,T);let k=!1,R=null,I=null,$=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),P=async()=>{try{await v.heartbeat(m.jobId)==="claim_lost"&&(k=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(G){let we=G instanceof Error?G.message:String(G);console.warn(`[job] ${m.jobId} heartbeat error: ${we}`)}};P();let B=setInterval(()=>{P()},$),H=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(y(m.prompt," \u2502 "));let xe=[],st=null,A=400,fe=25,He=500,Ne=()=>{if(st&&(clearTimeout(st),st=null),xe.length===0)return;let G=xe.splice(0,xe.length),we=u;if(!we||we.readyState!==we.OPEN)return;let Ke={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:G};try{we.send(JSON.stringify(Ke))}catch{}},Eo=G=>{xe.push(G),xe.length>He&&xe.shift(),xe.length>=fe?Ne():st||(st=setTimeout(Ne,A))},at=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,Z=new Set,Ao=null;try{if(!n){k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:H,finishedAt:new Date().toISOString()});return}let G=xc(m.jobId);console.log(`[job] ${m.jobId} workspace=${G.dir}`);let we=b(m,r);R=we.gitCreds,I=we.contextGitCreds;let Ke=R?.env,zn=we.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:we.claudeOauthToken}:void 0,We=[],or=null,_o=null;try{let N="worktree";We=await gc(G.dir,m.projectId,m.projectRepos,N,Ke);let _=await hc(G.dir,m.projectId,m.contextRepo,N,Ke);_o=_,or=_?.workspacePath??null}catch(N){let _=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} materialize failed: ${_}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${_}`},startedAt:H,finishedAt:new Date().toISOString()}),G.dispose();return}let Jn=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let N=m.contextRepo?.cloneUrl;if(!N||!Ke)throw new Error(N?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let _ of m.deliveries){let z=We.find(J=>J.name===_.name);z&&(await dc(z,_.deliveryRef,_.deliverySha,N,Ke),console.log(`[job] ${m.jobId} ${z.name}: checked out delivery ${_.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await Jn()}catch(N){let _=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} delivery checkout failed: ${_}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${_}`},startedAt:H,finishedAt:new Date().toISOString()}),G.dispose();return}let Xn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},Qn="";if(m.role==="resolve-conflict")try{let N=[];for(let _ of We){let z=Xn[_.name];if(!z)continue;let J=await xn(_,z,Ke);console.log(`[job] ${m.jobId} ${_.name}: merged ${z} into ${_.ref} \u2014 ${J.length} conflicted file(s)`),J.length>0?N.push(`- **${_.name}**:`,...J.map(vt=>` - \`${vt}\``)):N.push(`- **${_.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Qn=`
545
545
 
546
546
  ## Conflicts to resolve
547
547
 
548
548
  `+(N.length>0?N.join(`
549
549
  `):"(no task branches to merge)")+`
550
- `}catch(N){let _=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} conflict merge failed: ${_}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${_}`},startedAt:H,finishedAt:new Date().toISOString()}),M.dispose();return}let Hl=x(w(m.prompt,He,rr),rr,m.taskId)+Vn,_o=[...He.map(N=>N.workspacePath),...rr?[rr]:[]];_o.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${_o.join(", ")}`),st&&(Eo=setInterval(()=>{let _=u;if(!_||_.readyState!==_.OPEN)return;let z;try{z=Hf(xr(M.dir,"drafts")).filter(J=>J.endsWith(".json")).sort()}catch{return}for(let J of z){if(Z.has(J))continue;if(Z.size>=ri)break;let xt;try{let ae=JSON.parse(vn(xr(M.dir,"drafts",J),"utf-8")),at=typeof ae.localRef=="string"?ae.localRef:"",D=typeof ae.title=="string"?ae.title:"",re=typeof ae.body=="string"?ae.body:"";if(!at||!D)continue;xt={localRef:at,title:D,body:re,...ae.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ae.links)?{links:ae.links}:{}}}catch{continue}Z.add(J);let Oo={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:st,child:xt};try{_.send(JSON.stringify(Oo))}catch{}}},1500));try{let N={workspaceDir:M.dir,role:m.role,prompt:Hl,addDirs:_o,metadata:m.metadata??{},...m.model?{model:m.model}:{},...Wn?{env:Wn}:{},signal:R.abort.signal,onActivity:Po},_=R.chatInbox?await n.run({...N,interactive:{inbox:R.chatInbox.iterable}}):await za(n,N,{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{M.clean();for(let D of He)try{await nc(D);let re=Yn[D.name];m.role==="resolve-conflict"&&re&&await $n(D,re,Fe)}catch(re){let or=re instanceof Error?re.message:String(re);console.warn(`[job] ${m.jobId} worktree reset failed (${D.name}): ${or}`)}try{await qn()}catch(D){let re=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${re}`)}},aborted:()=>k||R.paused}),z=[];if(Yf.has(m.role)&&He.length>0){let D=m.metadata??{},re=typeof D.commitMessage=="string"?D.commitMessage:`${m.taskId}: changes`,or=m.contextRepo?.cloneUrl,zn=I?.env;if(!or||!zn)throw new Error("delivery requested but "+(or?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Kl=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let Oe of He){let nr=await ic(Oe,re);if(!nr){console.log(`[job] ${m.jobId} ${Oe.name}: no changes \u2014 no delivery`);continue}let No=`codepipe/deliveries/${Kl}/${m.jobId}/${Oe.name}`;await sc(Oe,nr,No,or,zn),z.push({name:Oe.name,deliveryRef:No,deliverySha:nr,baseSha:Oe.baseSha}),console.log(`[job] ${m.jobId} ${Oe.name}: delivered ${nr.slice(0,10)} \u2192 ${No}`);let Jn=await ac(Oe,nr);if(Jn.trim().length>0){let Wl=xr("display",`${Oe.name}.diff`),Xn=xr(M.dir,Wl);Ff(Wf(Xn),{recursive:!0}),Kf(Xn,Jn)}}}if(m.role==="resolve-conflict"&&z.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 J;m.role==="build"&&(J=mc(M.dir),console.log(`[job] ${m.jobId} build verdict: ok=${J.ok}`+(J.failedStep?` failedStep=${J.failedStep}`:"")));let xt=_.artifactPaths.length>0?_.artifactPaths:M.listFiles(),Oo=Array.from(new Set(xt)),ae;if(Ao)try{let D=await fc(Ao,m.role==="index"?["adr/SOURCES.md"]:[]);D.length>0&&(ae=D,console.log(`[job] ${m.jobId} captured ${D.length} knowledge file(s) for Context Repo`))}catch(D){let re=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${re}`)}let at={jobId:m.jobId,status:"succeeded",artifacts:Oo.map(D=>({path:D,contentBase64:vn(`${M.dir}/${D}`).toString("base64")})),...ae?{contextWrites:ae}:{},...z.length>0?{deliveries:z}:{},log:Vf(_.log),startedAt:H,finishedAt:new Date().toISOString(),usage:_.usage,..._.rateLimit?{rateLimit:_.rateLimit}:{},...J?{build:J}:{}};if(k||R.paused)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${R.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await v.submitResult(at),console.log(`[job] ${m.jobId} done \u2014 uploaded ${at.artifacts.length} artifact(s):`);for(let D of at.artifacts){let re=Buffer.from(D.contentBase64,"base64").length;console.log(` \xB7 ${D.path} (${re} bytes)`)}at.artifacts.length===0&&console.warn(`[job] ${m.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(N){let _=N instanceof Error?N.message:String(N);if(R.paused)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(k)console.warn(`[job] ${m.jobId} failed after claim lost (${_}) \u2014 skipping result upload`);else{let z=Va(N);console.warn(z?`[job] ${m.jobId} failed: ${_} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${_}`),await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:H,finishedAt:new Date().toISOString(),...z?{authError:!0}:{}})}}finally{M.dispose()}}finally{clearInterval(B),Eo&&clearInterval(Eo),_e(),R.chatInbox?.close(),l.delete(m.jobId),T?.cleanup(),I?.cleanup()}}function b(v,m){if(!v.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${v.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let R;try{R=JSON.parse(Zr(m,v.credBundle).toString("utf-8"))}catch($){return console.warn(`[job] ${v.jobId} failed to open credBundle: ${$ instanceof Error?$.message:String($)}`),{gitCreds:null,contextGitCreds:null}}let k=kn(R);k&&console.log(`[job] ${v.jobId} cred bundle opened \u2014 git creds configured`);let T=Qa(R,v.contextRepo.cloneUrl),I={gitCreds:k,contextGitCreds:T};return R.claudeOauthToken&&(I.claudeOauthToken=R.claudeOauthToken),I}function y(v,m){return v.split(`
551
- `).map(R=>m+R).join(`
552
- `)}function w(v,m,R){let k=m[0]?.workspacePath??"";return v.replace(/\{\{codeDir\}\}/g,k).replace(/\{\{codeRoot\}\}/g,k?k.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,R??"")}function x(v,m,R){let k=v,T=R.includes("::")?"":R.split(":",2)[1]??"",I=$=>{if(!m||!T)return"";try{return vn(xr(m,"tasks",T,$),"utf-8").trim()}catch{return""}};if(k.includes("{{solutionMd}}")){let $=I("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";k=k.replace(/\{\{solutionMd\}\}/g,()=>$)}if(k.includes("{{taskDescription}}")){let $=I("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";k=k.replace(/\{\{taskDescription\}\}/g,()=>$)}return k}let O=v=>{if(a)return;a=!0,console.log(`
553
- [${v}] shutting down`),c.abort();let m=[...l.keys()];for(let T of l.values())T.abort.abort();let R=new AbortController,k=setTimeout(()=>R.abort(),3e3);(async()=>(await Promise.all(m.map(async T=>{try{await s.releaseJob(T,`sandbox ${v}`,R.signal),console.log(`[${v}] released job ${T}`)}catch(I){let $=I instanceof Error?I.message:String(I);console.warn(`[${v}] release failed: ${$} (sweeper will reclaim)`)}})),clearTimeout(k),d.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM"));let j=[h("implementation")];e.planningLane!==!1?j.push(h("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(j)}async function bc(t={profile:void 0}){let e=fe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=no(e.hubUrl,e.cliToken),o=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let f=JSON.parse(u);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of o.events)console.log(` ${i}`);o.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await G(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let n=ne(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as ym}from"node:child_process";import{existsSync as qt,mkdirSync as Bc,readFileSync as Mc,readdirSync as wm,writeFileSync as Gc}from"node:fs";import{join as yt,resolve as Fc}from"node:path";import{setTimeout as Rn}from"node:timers/promises";import{cancel as km,confirm as Yt,intro as Hc,isCancel as Pn,log as C,outro as In,password as Vt,select as wt,spinner as Kc,text as X}from"@clack/prompts";import{simpleGit as Co}from"simple-git";async function Kt(t,e,r){return e.host==="github"?Xf(t,e,r):e.host==="gitlab"?nm(t,e,r):sm(t,e,r)}async function $c(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 rt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await xc(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 tt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await vc(e.gitlabToken,t):n}}return e.bitbucket?(await Ht(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await Sc(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 xc(t,e){let r=!1;try{r=(await rt(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 vc(t,e){let r=!1;try{r=(await tt(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 Sc(t,e){let r=!1;try{r=(await Ht(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 Jf="https://api.github.com";async function rt(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(Jf+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 Xf(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 Qf(o,e,r),i=await em(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=At(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await tm(o,n.owner,n.name,a.path,i)||await rm(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 Qf(t,e,r){let o=await rt(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 xc(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await Zf(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 rt(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 Zf(t,e){let{status:r,data:o}=await rt(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function em(t,e,r){let{data:o}=await rt(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function tm(t,e,r,o,n){let{status:i,data:s}=await rt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function rm(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 rt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var om="https://gitlab.com/api/v4";async function tt(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(om+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 nm(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 tt(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 vc(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await tt(o,"GET","/user"),p={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let d=await tt(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(d.status===404||!d.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);p.namespace_id=d.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await tt(o,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=At(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let g=(await tt(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let d of g)l.add(d.path);if(g.length<100)break}let u=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return u.length>0?await tt(o,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var im="https://api.bitbucket.org/2.0";async function Ht(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(im+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 sm(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 Ht(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 Sc(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 Ht(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=At(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await Ht(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let g of l)f.set(g.path,g.content);if((await Ht(o,"POST",`${n}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var am={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function ge(t){let e=t.trim();if(!e)return null;let r,o;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),o=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),o=a[2]}let n=am[r];if(!n)return null;let i=o.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:n,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as cm}from"node:crypto";import{existsSync as Cc,mkdirSync as lm,readFileSync as Tc,readdirSync as um,rmSync as vo,writeFileSync as pm}from"node:fs";import{homedir as dm}from"node:os";import{dirname as fm,join as Sn}from"node:path";var mm=24*60*60*1e3;function Rc(){return Sn(dm(),".codepipe","init-drafts")}function Cn(t){let e=cm("sha256").update(t).digest("hex").slice(0,16);return Sn(Rc(),`${e}.json`)}function Ic(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=mm)}function jc(t){let e=Cn(t);if(!Cc(e))return null;try{let r=JSON.parse(Tc(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Ic(r.savedAt)?(vo(e,{force:!0}),null):r}catch{return null}}function Tn(t){vo(Cn(t),{force:!0})}function Pc(){let t=Rc();if(Cc(t))for(let e of um(t)){let r=Sn(t,e);try{let o=JSON.parse(Tc(r,"utf-8"));Ic(o.savedAt)&&vo(r,{force:!0})}catch{vo(r,{force:!0})}}}var Wt=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=Cn(this.cwd);lm(fm(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};pm(e,JSON.stringify(r,null,2)+`
554
- `,{mode:384})}};function Ec(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 Ac(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 _c}from"node:fs";import{join as Oc}from"node:path";import{simpleGit as Nc}from"simple-git";var gm={info:t=>console.log(t),warn:t=>console.warn(t)};async function Sr(t,e,r={}){let o=r.log??gm,n=[];for(let i of e){let s=Oc(t,i.mountAs),a=si(i);if(!_c(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 Nc().clone(a,s),n.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let f=u instanceof Error?u.message:String(u);o.warn(`clone failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!_c(Oc(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=Nc(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!hm(l,a)){o.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let f=u instanceof Error?u.message:String(u);o.warn(`fetch failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}}return n}function hm(t,e){return Uc(t)===Uc(e)}function Uc(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Lc(t={}){let e=de();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await 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 Dc=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function W(t){km(t),process.exit(1)}function he(t){return Pn(t)&&W("aborted"),t}function F(t){return Pn(t)&&W("aborted"),typeof t=="string"?t:""}async function Wc(t={}){Hc("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Pc();let r=jc(e),o,n=!1;r&&Object.keys(r.answers).length>0?he(await Yt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(C.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new Wt(e,r),n=!0):(Tn(e),o=new Wt(e)):o=new Wt(e);let i=t.force===!0?null:await En(e),s=await o.ask("target",async()=>he(await wt({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?C.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||Yc(e,t.force===!0));let c=await o.ask("hubUrl",async()=>F(await X({message:"HUB URL",placeholder:ve,initialValue:L("HUB_URL")??ve,validate:E=>E.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await o.ask("email",()=>zt()),{cliToken:u,accountEmail:f}=await o.ask("bootstrap",()=>Jt(c,l)),p=null;s==="farm"&&(p=await bm(c,u));let g=a?xm(a.parsed.repoName):"",d=await o.ask("projectId",async()=>F(await X({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:E=>lt.test(E.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await o.ask("projectName",async()=>F(await X({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),S=await o.ask("automationLevel",async()=>he(await wt({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"}))),b=await o.ask("youtrack",()=>el()),y=await o.ask("youtrackProjectKey",async()=>F(await X({message:"YouTrack project key",placeholder:"DEV",validate:E=>E.trim().length>0?void 0:"required"})).trim()),w=await o.ask("youtrackWrites",async()=>he(await Yt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),x=o.get("tokens")??{},O=()=>o.set("tokens",x),j=await o.ask("repos",()=>Tm(x,l,a,{onCred:O,initial:o.get("reposPartial")??[],onProgress:E=>o.set("reposPartial",E)}));o.delete("reposPartial");let v=await Rm(await o.ask("contextRepo",()=>Xc(d,j,x,l)),d,j,x,l,O,E=>o.set("contextRepo",E)),{spec:m,mode:R}=v;C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let k=await o.ask("assigneeLogin",async()=>F(await X({message:"your YouTrack login (the assignee value)",...b.login?{initialValue:b.login}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),T=await o.ask("claudeToken",()=>Om(s==="farm")),I={projectId:d,name:h,automationLevel:S,repos:j,youtrackProjectKey:y};C.step(`${R==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let $;try{$=await Kt(I,m,{...Qc(x),youtrackWrites:w,trackerUrl:b.url,mode:R,log:{info:E=>C.message(E),warn:E=>C.warn(E)}})}catch(E){W(`Context Repo provisioning failed: ${E instanceof Error?E.message:String(E)}`)}I.contextRepo=$,C.success(`Context Repo ready: ${$.owner}/${$.name}@${$.branch}`),C.step(`registering project on ${c}\u2026`);let P;try{P=await Qe(c,u,I)}catch(E){if(E instanceof A&&E.status===409){C.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{P=await G(c,u,d)}catch(ue){throw ue instanceof A&&W(`HUB \u2192 ${ue.status} ${ue.message}`),ue}}else if(E instanceof A&&E.status===401)o.delete("cliToken"),W("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(E instanceof A)W(`HUB \u2192 ${E.status} ${E.message}`);else throw E}let B=P.contextRepo??$;C.success(`project ${P.projectId} ready (${P.provisioningStatus})`);let H=await Am(B),xe={url:b.url,token:b.token};if(s==="farm"){let E=p,ue={...x,...H?{contextWrite:H}:{},...T?{claude:{oauthToken:T}}:{},youtrack:xe},Ge=x.github?.token;if(B.host==="github"&&Ge)try{let Z=va(`devpipe-${d}`);await Sa(B,Ge,Z.publicKey,`devpipe-${d}`),ue.contextSsh={privateKey:Z.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(Z){C.warn(`could not set up Context Repo SSH deploy key (${Z instanceof Error?Z.message:String(Z)}); the farm will fall back to the token path.`)}let _e={projectId:d,config:{hubUrl:c,cliToken:u,projectId:d},secrets:ue,contextRepo:B,projectConfig:je(I,w,b.url,k||void 0)},Po=_t(E.farm.publicKey,JSON.stringify(_e));C.step(`handing project ${d} to farm ${E.farm.name}\u2026`);let st;try{st=await io(c,u,E.farm.farmId,{projectId:d,sealedBundle:Po})}catch(Z){throw Z instanceof A&&W(Z.status===409?`farm ${E.farm.name} is offline \u2014 start it and re-run.`:Z.status===504?`farm ${E.farm.name} did not respond in time.`:`HUB \u2192 ${Z.status} ${Z.message}`),Z}st.ok||W(`farm rejected provisioning: ${st.error??"unknown error"}`),await jn(c,u,d,B,Ge),o.clear(),In(`done. project ${d} is now hosted on farm ${E.farm.name} (daemon ${st.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Zc(x),await Vc(e,B.cloneUrl,B.branch),Jc(e),a&&await Sm(e);{let E=yt(e,Te);Pt(E);let ue=je(I,w,b.url,k||void 0),Ge=cr(E,ue);Ge.length>0&&C.success(`local project config \u2192 .codepipe/{${Ge.join(", ")}}`),dt(d,ue,{info:_e=>C.message(_e),warn:_e=>C.warn(_e)})}await zc(e,P.repos);let it={hubUrl:c,cliToken:u,projectId:d,...x,...H?{contextWrite:H}:{},...T?{claude:{oauthToken:T}}:{},youtrack:xe};K(it),Ue({hubUrl:c,cliToken:u,projectId:d,accountEmail:f},d),C.success(`secrets \u2192 ${Re(d)}`),await jn(c,u,d,B,x.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),In("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function jn(t,e,r,o,n){let i=await Ac(o,n),s=Ec(i),a=await wt({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Pn(a)||a!==s.proceedValue))try{let{jobId:c}=await ao(t,e,r,{reindex:s.reindex});C.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){C.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function bm(t,e){let r;try{r=await Qs(t,e)}catch(c){throw c instanceof A&&W(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&W("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let n=he(await wt({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=oo(i.farmId,i.publicKey)}catch(c){W(c instanceof Error?c.message:String(c))}return he(await Yt({message:`confirm farm ${i.name} cred-channel fingerprint:
550
+ `}catch(N){let _=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} conflict merge failed: ${_}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${_}`},startedAt:H,finishedAt:new Date().toISOString()}),G.dispose();return}let Jl=x(w(m.prompt,We,or),or,m.taskId)+Qn,Oo=[...We.map(N=>N.workspacePath),...or?[or]:[]];Oo.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${Oo.join(", ")}`),at&&(Ao=setInterval(()=>{let _=u;if(!_||_.readyState!==_.OPEN)return;let z;try{z=Jf(vr(G.dir,"drafts")).filter(J=>J.endsWith(".json")).sort()}catch{return}for(let J of z){if(Z.has(J))continue;if(Z.size>=si)break;let vt;try{let le=JSON.parse(Sn(vr(G.dir,"drafts",J),"utf-8")),ct=typeof le.localRef=="string"?le.localRef:"",D=typeof le.title=="string"?le.title:"",re=typeof le.body=="string"?le.body:"";if(!ct||!D)continue;vt={localRef:ct,title:D,body:re,...le.isEpic===!0?{isEpic:!0}:{},...Array.isArray(le.links)?{links:le.links}:{}}}catch{continue}Z.add(J);let No={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:at,child:vt};try{_.send(JSON.stringify(No))}catch{}}},1500));try{let N={workspaceDir:G.dir,role:m.role,prompt:Jl,addDirs:Oo,metadata:m.metadata??{},...m.model?{model:m.model}:{},...zn?{env:zn}:{},signal:T.abort.signal,onActivity:Eo},_=T.chatInbox?await n.run({...N,interactive:{inbox:T.chatInbox.iterable}}):await Za(n,N,{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{G.clean();for(let D of We)try{await cc(D);let re=Xn[D.name];m.role==="resolve-conflict"&&re&&await xn(D,re,Ke)}catch(re){let nr=re instanceof Error?re.message:String(re);console.warn(`[job] ${m.jobId} worktree reset failed (${D.name}): ${nr}`)}try{await Jn()}catch(D){let re=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${re}`)}},aborted:()=>k||T.paused}),z=[];if(em.has(m.role)&&We.length>0){let D=m.metadata??{},re=typeof D.commitMessage=="string"?D.commitMessage:`${m.taskId}: changes`,nr=m.contextRepo?.cloneUrl,Zn=I?.env;if(!nr||!Zn)throw new Error("delivery requested but "+(nr?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Xl=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let Ue of We){let ir=await lc(Ue,re);if(!ir){console.log(`[job] ${m.jobId} ${Ue.name}: no changes \u2014 no delivery`);continue}let Uo=`codepipe/deliveries/${Xl}/${m.jobId}/${Ue.name}`;await uc(Ue,ir,Uo,nr,Zn),z.push({name:Ue.name,deliveryRef:Uo,deliverySha:ir,baseSha:Ue.baseSha}),console.log(`[job] ${m.jobId} ${Ue.name}: delivered ${ir.slice(0,10)} \u2192 ${Uo}`);let ei=await pc(Ue,ir);if(ei.trim().length>0){let Ql=vr("display",`${Ue.name}.diff`),ti=vr(G.dir,Ql);zf(Qf(ti),{recursive:!0}),Xf(ti,ei)}}}if(m.role==="resolve-conflict"&&z.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 J;m.role==="build"&&(J=wc(G.dir),console.log(`[job] ${m.jobId} build verdict: ok=${J.ok}`+(J.failedStep?` failedStep=${J.failedStep}`:"")));let vt=_.artifactPaths.length>0?_.artifactPaths:G.listFiles(),No=Array.from(new Set(vt)),le;if(_o)try{let D=await yc(_o,m.role==="index"?["adr/SOURCES.md"]:[]);D.length>0&&(le=D,console.log(`[job] ${m.jobId} captured ${D.length} knowledge file(s) for Context Repo`))}catch(D){let re=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${re}`)}let ct={jobId:m.jobId,status:"succeeded",artifacts:No.map(D=>({path:D,contentBase64:Sn(`${G.dir}/${D}`).toString("base64")})),...le?{contextWrites:le}:{},...z.length>0?{deliveries:z}:{},log:tm(_.log),startedAt:H,finishedAt:new Date().toISOString(),usage:_.usage,..._.rateLimit?{rateLimit:_.rateLimit}:{},...J?{build:J}:{}};if(k||T.paused)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${T.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await v.submitResult(ct),console.log(`[job] ${m.jobId} done \u2014 uploaded ${ct.artifacts.length} artifact(s):`);for(let D of ct.artifacts){let re=Buffer.from(D.contentBase64,"base64").length;console.log(` \xB7 ${D.path} (${re} bytes)`)}ct.artifacts.length===0&&console.warn(`[job] ${m.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(N){let _=N instanceof Error?N.message:String(N);if(T.paused)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(k)console.warn(`[job] ${m.jobId} failed after claim lost (${_}) \u2014 skipping result upload`);else{let z=Qa(N);console.warn(z?`[job] ${m.jobId} failed: ${_} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${_}`),await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:H,finishedAt:new Date().toISOString(),...z?{authError:!0}:{}})}}finally{G.dispose()}}finally{clearInterval(B),Ao&&clearInterval(Ao),Ne(),T.chatInbox?.close(),l.delete(m.jobId),R?.cleanup(),I?.cleanup()}}function b(v,m){if(!v.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${v.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let T;try{T=JSON.parse(eo(m,v.credBundle).toString("utf-8"))}catch($){return console.warn(`[job] ${v.jobId} failed to open credBundle: ${$ instanceof Error?$.message:String($)}`),{gitCreds:null,contextGitCreds:null}}let k=bn(T);k&&console.log(`[job] ${v.jobId} cred bundle opened \u2014 git creds configured`);let R=rc(T,v.contextRepo.cloneUrl),I={gitCreds:k,contextGitCreds:R};return T.claudeOauthToken&&(I.claudeOauthToken=T.claudeOauthToken),I}function y(v,m){return v.split(`
551
+ `).map(T=>m+T).join(`
552
+ `)}function w(v,m,T){let k=m[0]?.workspacePath??"";return v.replace(/\{\{codeDir\}\}/g,k).replace(/\{\{codeRoot\}\}/g,k?k.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,T??"")}function x(v,m,T){let k=v,R=T.includes("::")?"":T.split(":",2)[1]??"",I=$=>{if(!m||!R)return"";try{return Sn(vr(m,"tasks",R,$),"utf-8").trim()}catch{return""}};if(k.includes("{{solutionMd}}")){let $=I("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";k=k.replace(/\{\{solutionMd\}\}/g,()=>$)}if(k.includes("{{taskDescription}}")){let $=I("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";k=k.replace(/\{\{taskDescription\}\}/g,()=>$)}return k}let O=v=>{if(a)return;a=!0,console.log(`
553
+ [${v}] shutting down`),c.abort();let m=[...l.keys()];for(let R of l.values())R.abort.abort();let T=new AbortController,k=setTimeout(()=>T.abort(),3e3);(async()=>(await Promise.all(m.map(async R=>{try{await s.releaseJob(R,`sandbox ${v}`,T.signal),console.log(`[${v}] released job ${R}`)}catch(I){let $=I instanceof Error?I.message:String(I);console.warn(`[${v}] release failed: ${$} (sweeper will reclaim)`)}})),clearTimeout(k),f.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM"));let j=[h("implementation")];e.planningLane!==!1?j.push(h("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(j)}async function Sc(t={profile:void 0}){let e=ge(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=io(e.hubUrl,e.cliToken),o=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let d=JSON.parse(u);d.type==="registered"?(a=!!d.ok,clearTimeout(c),r.send("ping")):d.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of o.events)console.log(` ${i}`);o.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await M(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let n=ne(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as Sm}from"node:child_process";import{existsSync as Yt,mkdirSync as Hc,readFileSync as Kc,readdirSync as Cm,writeFileSync as Wc}from"node:fs";import{join as wt,resolve as qc}from"node:path";import{setTimeout as In}from"node:timers/promises";import{cancel as Rm,confirm as Vt,intro as Yc,isCancel as En,log as C,outro as jn,password as zt,select as kt,spinner as Vc,text as X}from"@clack/prompts";import{simpleGit as Ro}from"simple-git";async function Wt(t,e,r){return e.host==="github"?nm(t,e,r):e.host==="gitlab"?pm(t,e,r):fm(t,e,r)}async function Cc(t,e,r={}){let o=r.explain??!0,n=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await ot(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await Rc(e.githubToken,t):n}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await rt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await Tc(e.gitlabToken,t):n}}return e.bitbucket?(await Kt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await Ic(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 Rc(t,e){let r=!1;try{r=(await ot(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function Tc(t,e){let r=!1;try{r=(await rt(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function Ic(t,e){let r=!1;try{r=(await Kt(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}var om="https://api.github.com";async function ot(t,e,r,o){let n={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};o!==void 0&&(n.body=JSON.stringify(o),n.headers["Content-Type"]="application/json");let i=await fetch(om+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 nm(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 im(o,e,r),i=await am(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=_t(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await cm(o,n.owner,n.name,a.path,i)||await lm(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 im(t,e,r){let o=await ot(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(o.status===200&&o.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:o.data.owner.login,name:o.data.name,sshUrl:o.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await Rc(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await sm(t,e.owner),i=n?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${n?"org":"user"})`);let s=await ot(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function sm(t,e){let{status:r,data:o}=await ot(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function am(t,e,r){let{data:o}=await ot(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function cm(t,e,r,o,n){let{status:i,data:s}=await ot(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function lm(t,e,r,o,n,i,s,a){let c={message:i,content:Buffer.from(n,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await ot(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var um="https://gitlab.com/api/v4";async function rt(t,e,r,o){let n={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...o!==void 0?{"Content-Type":"application/json"}:{}}};o!==void 0&&(n.body=JSON.stringify(o));let i=await fetch(um+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 pm(t,e,r){let o=r.gitlabToken;if(!o)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let n=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await rt(o,"GET",`/projects/${n}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Tc(o,e)} (attach joins an existing Context Repo and never creates one)`);let d=await rt(o,"GET","/user"),p={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(d.data?.username!==e.owner){let f=await rt(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);p.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await rt(o,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=_t(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let d=1;;d++){let g=(await rt(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${d}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of g)l.add(f.path);if(g.length<100)break}let u=c.filter(d=>!l.has(d.path)).map(d=>({action:"create",file_path:d.path,content:d.content}));return u.length>0?await rt(o,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var dm="https://api.bitbucket.org/2.0";async function Kt(t,e,r,o){let n={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};o?.json!==void 0?(n.body=JSON.stringify(o.json),n.headers["Content-Type"]="application/json"):o?.form&&(n.body=o.form);let i=await fetch(dm+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 fm(t,e,r){let o=r.bitbucket;if(!o)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let n=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await Kt(o,"GET",n);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Ic(o,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let d=await Kt(o,"POST",n,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(d.status===404||!d.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=d.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=_t(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let d of c)(await Kt(o,"GET",`${n}/src/${encodeURIComponent(a)}/${d.path}?format=meta`)).status===404&&l.push(d);if(l.length>0){let d=new URLSearchParams;d.set("message","chore(codepipe): scaffold context repo files"),d.set("branch",a);for(let g of l)d.set(g.path,g.content);if((await Kt(o,"POST",`${n}/src`,{form:d})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(d=>d.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var mm={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function ce(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=mm[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 gm}from"node:crypto";import{existsSync as jc,mkdirSync as hm,readFileSync as Pc,readdirSync as ym,rmSync as So,writeFileSync as wm}from"node:fs";import{homedir as km}from"node:os";import{dirname as bm,join as Cn}from"node:path";var $m=24*60*60*1e3;function Ec(){return Cn(km(),".codepipe","init-drafts")}function Rn(t){let e=gm("sha256").update(t).digest("hex").slice(0,16);return Cn(Ec(),`${e}.json`)}function Ac(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=$m)}function _c(t){let e=Rn(t);if(!jc(e))return null;try{let r=JSON.parse(Pc(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Ac(r.savedAt)?(So(e,{force:!0}),null):r}catch{return null}}function Tn(t){So(Rn(t),{force:!0})}function Oc(){let t=Ec();if(jc(t))for(let e of ym(t)){let r=Cn(t,e);try{let o=JSON.parse(Pc(r,"utf-8"));Ac(o.savedAt)&&So(r,{force:!0})}catch{So(r,{force:!0})}}}var qt=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let o=await r();return this.set(e,o),o}clear(){Tn(this.cwd)}persist(){let e=Rn(this.cwd);hm(bm(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};wm(e,JSON.stringify(r,null,2)+`
554
+ `,{mode:384})}};function Nc(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 Uc(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 Lc}from"node:fs";import{join as Dc}from"node:path";import{simpleGit as Bc}from"simple-git";var xm={info:t=>console.log(t),warn:t=>console.warn(t)};async function Cr(t,e,r={}){let o=r.log??xm,n=[];for(let i of e){let s=Dc(t,i.mountAs),a=ui(i);if(!Lc(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 Bc().clone(a,s),n.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let d=u instanceof Error?u.message:String(u);o.warn(`clone failed for ${i.mountAs}: ${d}`),n.push({mountAs:i.mountAs,status:"error",detail:d})}continue}if(!Lc(Dc(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=Bc(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!vm(l,a)){o.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let d=u instanceof Error?u.message:String(u);o.warn(`fetch failed for ${i.mountAs}: ${d}`),n.push({mountAs:i.mountAs,status:"error",detail:d})}}return n}function vm(t,e){return Mc(t)===Mc(e)}function Mc(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Gc(t={}){let e=se();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await Cr(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let o of r)console.log(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}var Fc=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function W(t){Rm(t),process.exit(1)}function ye(t){return En(t)&&W("aborted"),t}function F(t){return En(t)&&W("aborted"),typeof t=="string"?t:""}async function zc(t={}){Yc("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Oc();let r=_c(e),o,n=!1;r&&Object.keys(r.answers).length>0?ye(await Vt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(C.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new qt(e,r),n=!0):(Tn(e),o=new qt(e)):o=new qt(e);let i=t.force===!0?null:await An(e),s=await o.ask("target",async()=>ye(await kt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?C.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||Xc(e,t.force===!0));let c=await o.ask("hubUrl",async()=>F(await X({message:"HUB URL",placeholder:ve,initialValue:L("HUB_URL")??ve,validate:A=>A.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await o.ask("email",()=>Jt()),{cliToken:u,accountEmail:d}=await o.ask("bootstrap",()=>Xt(c,l)),p=null;s==="farm"&&(p=await Tm(c,u));let g=a?jm(a.parsed.repoName):"",f=await o.ask("projectId",async()=>F(await X({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:A=>ut.test(A.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await o.ask("projectName",async()=>F(await X({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:A=>A.trim().length>0?void 0:"required"})).trim()),S=await o.ask("automationLevel",async()=>ye(await kt({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),b=await o.ask("youtrack",()=>nl()),y=await o.ask("youtrackProjectKey",async()=>F(await X({message:"YouTrack project key",placeholder:"DEV",validate:A=>A.trim().length>0?void 0:"required"})).trim()),w=await o.ask("youtrackWrites",async()=>ye(await Vt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),x=o.get("tokens")??{},O=()=>o.set("tokens",x),j=await o.ask("repos",()=>_m(x,l,a,{onCred:O,initial:o.get("reposPartial")??[],onProgress:A=>o.set("reposPartial",A)}));o.delete("reposPartial");let v=await Om(await o.ask("contextRepo",()=>tl(f,j,x,l)),f,j,x,l,O,A=>o.set("contextRepo",A)),{spec:m,mode:T}=v;C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let k=await o.ask("assigneeLogin",async()=>F(await X({message:"your YouTrack login (the assignee value)",...b.login?{initialValue:b.login}:{},validate:A=>A.trim().length>0?void 0:"required"})).trim()),R=await o.ask("claudeToken",()=>Gm(s==="farm")),I={projectId:f,name:h,automationLevel:S,repos:j,youtrackProjectKey:y};C.step(`${T==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let $;try{$=await Wt(I,m,{...rl(x),youtrackWrites:w,trackerUrl:b.url,mode:T,log:{info:A=>C.message(A),warn:A=>C.warn(A)}})}catch(A){W(`Context Repo provisioning failed: ${A instanceof Error?A.message:String(A)}`)}I.contextRepo=$,C.success(`Context Repo ready: ${$.owner}/${$.name}@${$.branch}`),C.step(`registering project on ${c}\u2026`);let P;try{P=await Ee(c,u,I)}catch(A){if(A instanceof E&&A.status===409){C.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{P=await M(c,u,f)}catch(fe){throw fe instanceof E&&W(`HUB \u2192 ${fe.status} ${fe.message}`),fe}}else if(A instanceof E&&A.status===401)o.delete("cliToken"),W("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(A instanceof E)W(`HUB \u2192 ${A.status} ${A.message}`);else throw A}let B=P.contextRepo??$;C.success(`project ${P.projectId} ready (${P.provisioningStatus})`);let H=await Bm(B),xe={url:b.url,token:b.token};if(s==="farm"){let A=p,fe={...x,...H?{contextWrite:H}:{},...R?{claude:{oauthToken:R}}:{},youtrack:xe},He=x.github?.token;if(B.host==="github"&&He)try{let Z=Ta(`devpipe-${f}`);await Ia(B,He,Z.publicKey,`devpipe-${f}`),fe.contextSsh={privateKey:Z.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(Z){C.warn(`could not set up Context Repo SSH deploy key (${Z instanceof Error?Z.message:String(Z)}); the farm will fall back to the token path.`)}let Ne={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:fe,contextRepo:B,projectConfig:je(I,w,b.url,k||void 0)},Eo=Ot(A.farm.publicKey,JSON.stringify(Ne));C.step(`handing project ${f} to farm ${A.farm.name}\u2026`);let at;try{at=await so(c,u,A.farm.farmId,{projectId:f,sealedBundle:Eo})}catch(Z){throw Z instanceof E&&W(Z.status===409?`farm ${A.farm.name} is offline \u2014 start it and re-run.`:Z.status===504?`farm ${A.farm.name} did not respond in time.`:`HUB \u2192 ${Z.status} ${Z.message}`),Z}at.ok||W(`farm rejected provisioning: ${at.error??"unknown error"}`),await Pn(c,u,f,B,He),o.clear(),jn(`done. project ${f} is now hosted on farm ${A.farm.name} (daemon ${at.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}ol(x),await Qc(e,B.cloneUrl,B.branch),el(e),a&&await Em(e);{let A=wt(e,Re);Et(A);let fe=je(I,w,b.url,k||void 0),He=lr(A,fe);He.length>0&&C.success(`local project config \u2192 .codepipe/{${He.join(", ")}}`),ft(f,fe,{info:Ne=>C.message(Ne),warn:Ne=>C.warn(Ne)})}await Zc(e,P.repos);let st={hubUrl:c,cliToken:u,projectId:f,...x,...H?{contextWrite:H}:{},...R?{claude:{oauthToken:R}}:{},youtrack:xe};K(st),De({hubUrl:c,cliToken:u,projectId:f,accountEmail:d},f),C.success(`secrets \u2192 ${Te(f)}`),await Pn(c,u,f,B,x.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),jn("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Pn(t,e,r,o,n){let i=await Uc(o,n),s=Nc(i),a=await kt({message:s.message,options:s.options,initialValue:s.initialValue});if(!(En(a)||a!==s.proceedValue))try{let{jobId:c}=await co(t,e,r,{reindex:s.reindex});C.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){C.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function Tm(t,e){let r;try{r=await ra(t,e)}catch(c){throw c instanceof E&&W(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&W("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=ye(await kt({message:"target farm",options:o.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=o.find(c=>c.farmId===n),s;try{s=no(i.farmId,i.publicKey)}catch(c){W(c instanceof Error?c.message:String(c))}return ye(await Vt({message:`confirm farm ${i.name} cred-channel fingerprint:
555
555
  ${s}
556
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||W("farm fingerprint not confirmed \u2014 aborting."),ro(i.farmId,s),{farm:i,fingerprint:s}}async function qc(t){Hc(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Yc(e,t.force===!0);let r=F(await X({message:"HUB URL",initialValue:L("HUB_URL")??ve,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await zt(),{cliToken:n,accountEmail:i}=await Jt(r,o);C.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await G(r,n,t.projectId)}catch(f){throw f instanceof A&&W(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||W(`project ${t.projectId} has no Context Repo on HUB`);let a=await el(),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(p=>p.host===f)?.owner,o);Zc(c),await Vc(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Jc(e);{let f=yt(e,Te);Pt(f);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=je(p,!0,a.url),d=cr(f,g);d.length>0&&C.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),dt(t.projectId,g,{info:h=>C.message(h),warn:h=>C.warn(h)})}await zc(e,s.repos);let u={hubUrl:r,cliToken:n,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};K(u),Ue({hubUrl:r,cliToken:n,projectId:t.projectId,accountEmail:i},t.projectId),C.success(`secrets \u2192 ${Re(t.projectId)}`),await jn(r,n,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),In("done.")}function Yc(t,e){if(!qt(t)){Bc(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=wm(t).filter(n=>!r.has(n));o.length!==0&&(e||W(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function En(t){if(!qt(yt(t,".git")))return null;try{let r=(await Co(t).remote(["get-url","origin"])||"").toString().trim(),o=r?ge(r):null;return o?{parsed:o,defaultBranch:await $m(t)}:null}catch{return null}}async function $m(t){let e=Co(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 xm(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return lt.test(e)?e:""}function vm(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Sm(t){let e=yt(t,".gitignore"),r=qt(e)?Mc(e,"utf-8"):"";if(vm(r))return;if(!he(await Yt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){C.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let n=r.length===0||r.endsWith(`
556
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||W("farm fingerprint not confirmed \u2014 aborting."),oo(i.farmId,s),{farm:i,fingerprint:s}}async function Jc(t){Yc(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Xc(e,t.force===!0);let r=F(await X({message:"HUB URL",initialValue:L("HUB_URL")??ve,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await Jt(),{cliToken:n,accountEmail:i}=await Xt(r,o);C.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await M(r,n,t.projectId)}catch(d){throw d instanceof E&&W(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||W(`project ${t.projectId} has no Context Repo on HUB`);let a=await nl(),c={},l=new Set(s.repos.map(d=>d.host));l.add(s.contextRepo.host);for(let d of l)await Co(d,c,d===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===d)?.owner,o);ol(c),await Qc(e,s.contextRepo.cloneUrl,s.contextRepo.branch),el(e);{let d=wt(e,Re);Et(d);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=je(p,!0,a.url),f=lr(d,g);f.length>0&&C.success(`local project config \u2192 .codepipe/{${f.join(", ")}} (defaults \u2014 review and adjust)`),ft(t.projectId,g,{info:h=>C.message(h),warn:h=>C.warn(h)})}await Zc(e,s.repos);let u={hubUrl:r,cliToken:n,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};K(u),De({hubUrl:r,cliToken:n,projectId:t.projectId,accountEmail:i},t.projectId),C.success(`secrets \u2192 ${Te(t.projectId)}`),await Pn(r,n,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),jn("done.")}function Xc(t,e){if(!Yt(t)){Hc(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=Cm(t).filter(n=>!r.has(n));o.length!==0&&(e||W(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function An(t){if(!Yt(wt(t,".git")))return null;try{let r=(await Ro(t).remote(["get-url","origin"])||"").toString().trim(),o=r?ce(r):null;return o?{parsed:o,defaultBranch:await Im(t)}:null}catch{return null}}async function Im(t){let e=Ro(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 jm(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return ut.test(e)?e:""}function Pm(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Em(t){let e=wt(t,".gitignore"),r=Yt(e)?Kc(e,"utf-8"):"";if(Pm(r))return;if(!ye(await Vt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){C.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let n=r.length===0||r.endsWith(`
557
557
  `)?"":`
558
- `;Gc(e,r+n+`
558
+ `;Wc(e,r+n+`
559
559
  # codepipe workspace (added by \`codepipe init\`)
560
560
  .codepipe/
561
- `),C.success(`.codepipe/ added to ${Fc(e)}`)}function Cm(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let o=ym(e,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}catch{}}async function zt(){let t="";try{t=(await Co().raw(["config","--global","user.email"])||"").trim()}catch{}return F(await X({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Jt(t,e){C.step(`connecting account ${e}`);let r;try{r=await ta(t,e)}catch(s){throw s instanceof hr&&W(`${e} is not authorized on this HUB yet.
561
+ `),C.success(`.codepipe/ added to ${qc(e)}`)}function Am(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let o=Sm(e,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}catch{}}async function Jt(){let t="";try{t=(await Ro().raw(["config","--global","user.email"])||"").trim()}catch{}return F(await X({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Xt(t,e){C.step(`connecting account ${e}`);let r;try{r=await ia(t,e)}catch(s){throw s instanceof yr&&W(`${e} is not authorized on this HUB yet.
562
562
  Sign up at ${t} (registration form on the login screen),
563
563
  wait for the operator to approve it by email, then re-run
564
- \`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Cm(r.authorizeUrl),C.message(`a browser tab was opened to confirm this CLI:
564
+ \`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Am(r.authorizeUrl),C.message(`a browser tab was opened to confirm this CLI:
565
565
  ${r.authorizeUrl}
566
566
  `+(r.emailSent?" (already signed in to the dashboard there? just click Connect)":` if you're signed in to the CodePipe dashboard, just click Connect \u2014
567
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&C.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),C.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 ra(t,r.requestId)}catch(a){C.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&&C.message(`connected as ${a} (the account confirmed in the browser).`),C.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&W("the HUB rejected this account"),s.status==="expired"&&W("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){o||(o=!0,i=n+24*60*6e4,C.message(`email confirmed. waiting for the operator to approve your account\u2026
568
- (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)}W("bootstrap timed out")}async function Vc(t,e,r){let o=yt(t,Te);if(qt(yt(o,".git"))){C.message(`${o} already cloned \u2014 skipping`);return}qt(o)&&W(`${o} exists but is not a git repo \u2014 remove it and re-run`),Bc(o,{recursive:!0}),C.step(`cloning Context Repo \u2192 ${o}`);try{await Co().clone(e,o,["--branch",r]),C.success(`cloned ${e}`)}catch(n){W(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function zc(t,e){if(e.length===0)return;C.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=>C.message(n),warn:n=>C.warn(n)}});for(let n of o)C.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function Jc(t){let e=yt(t,Te,".gitignore"),r="";if(qt(e)&&(r=Mc(e,"utf-8")),Dc.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
567
+ otherwise use the emailed link the page offers.`))),r.approvalRequired&&C.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),C.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 sa(t,r.requestId)}catch(a){C.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await In(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&C.message(`connected as ${a} (the account confirmed in the browser).`),C.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&W("the HUB rejected this account"),s.status==="expired"&&W("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){o||(o=!0,i=n+24*60*6e4,C.message(`email confirmed. waiting for the operator to approve your account\u2026
568
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await In(5e3);continue}await In(2e3)}W("bootstrap timed out")}async function Qc(t,e,r){let o=wt(t,Re);if(Yt(wt(o,".git"))){C.message(`${o} already cloned \u2014 skipping`);return}Yt(o)&&W(`${o} exists but is not a git repo \u2014 remove it and re-run`),Hc(o,{recursive:!0}),C.step(`cloning Context Repo \u2192 ${o}`);try{await Ro().clone(e,o,["--branch",r]),C.success(`cloned ${e}`)}catch(n){W(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function Zc(t,e){if(e.length===0)return;C.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 Cr(t,r,{log:{info:n=>C.message(n),warn:n=>C.warn(n)}});for(let n of o)C.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function el(t){let e=wt(t,Re,".gitignore"),r="";if(Yt(e)&&(r=Kc(e,"utf-8")),Fc.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
569
569
  `)||r.length===0?"":`
570
- `,i=Dc.join(`
570
+ `,i=Fc.join(`
571
571
  `)+`
572
- `;Gc(e,r+n+(r?`
573
- `:"")+i),C.message(`appended runtime entries to ${Fc(e)}`)}async function Tm(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;C.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await So(s.host,t,s.owner,e),i?.();let c=F(await X({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=F(await X({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();n.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),o.onProgress?.(n)}for(;he(await Yt({message:n.length===0?"Add a project repository?":"Want to add another repository?",initialValue:n.length===0}));){let a=F(await X({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||ge(g)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=ge(a);C.message(`${c.host}: ${c.owner}/${c.repoName}`),await So(c.host,t,c.owner,e),i?.();let l=F(await X({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:g=>g.trim().length>0?void 0:"required"})).trim(),u=F(await X({message:"default branch (optional)",placeholder:"main"})).trim(),f=F(await X({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),p={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(p.defaultBranch=u),f&&f!==l&&(p.mountAs=f),n.push(p),o.onProgress?.(n)}return n}async function Xc(t,e,r,o){C.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=he(await wt({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"&&C.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=F(await X({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Ne(t),validate:u=>{let f=(u??"").trim();if(!f)return"required";if(!ge(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=ge(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Im(),l=F(await X({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=F(await X({message:"Context Repo name",placeholder:Ne(t),initialValue:Ne(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:n}}function Qc(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??Tt()}}async function Rm(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 u=Kc();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await $c(c,Qc(o),{explain:l==="attach"});if(f.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(f.detail,1);let p=he(await wt({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(p==="abort"&&W("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await Xc(e,r,o,n),s(a)}}async function Im(){return he(await wt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Cr(t,e){let r=Kc();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 Zc(t){fr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),mr(t.gitlab?.token??process.env.GITLAB_TOKEN),gr(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function So(t,e,r,o){if(!e[t])if(t==="github"){let n=await jm(r);n?e.github=n:C.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await Pm(r,o);n?e.bitbucket=n:C.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 Em();n?e.gitlab=n:C.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function jm(t){for(;;){let e=F(await Vt({message:`GitHub PAT \u2014 blank to skip
572
+ `;Wc(e,r+n+(r?`
573
+ `:"")+i),C.message(`appended runtime entries to ${qc(e)}`)}async function _m(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;C.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Co(s.host,t,s.owner,e),i?.();let c=F(await X({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=F(await X({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();n.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),o.onProgress?.(n)}for(;ye(await Vt({message:n.length===0?"Add a project repository?":"Want to add another repository?",initialValue:n.length===0}));){let a=F(await X({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||ce(g)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=ce(a);C.message(`${c.host}: ${c.owner}/${c.repoName}`),await Co(c.host,t,c.owner,e),i?.();let l=F(await X({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:g=>g.trim().length>0?void 0:"required"})).trim(),u=F(await X({message:"default branch (optional)",placeholder:"main"})).trim(),d=F(await X({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),p={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(p.defaultBranch=u),d&&d!==l&&(p.mountAs=d),n.push(p),o.onProgress?.(n)}return n}async function tl(t,e,r,o){C.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=ye(await kt({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));n==="attach"&&C.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=F(await X({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Le(t),validate:u=>{let d=(u??"").trim();if(!d)return"required";if(!ce(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=ce(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Nm(),l=F(await X({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=F(await X({message:"Context Repo name",placeholder:Le(t),initialValue:Le(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:n}}function rl(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??Tt()}}async function Om(t,e,r,o,n,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Co(c.host,o,c.owner,n),i?.();let u=Vc();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let d=await Cc(c,rl(o),{explain:l==="attach"});if(d.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(d.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${d.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(d.detail,1);let p=ye(await kt({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(p==="abort"&&W("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await tl(e,r,o,n),s(a)}}async function Nm(){return ye(await kt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Rr(t,e){let r=Vc();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 ol(t){mr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),gr(t.gitlab?.token??process.env.GITLAB_TOKEN),hr(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Co(t,e,r,o){if(!e[t])if(t==="github"){let n=await Um(r);n?e.github=n:C.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await Lm(r,o);n?e.bitbucket=n:C.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 Dm();n?e.gitlab=n:C.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Um(t){for(;;){let e=F(await zt({message:`GitHub PAT \u2014 blank to skip
574
574
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
575
575
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
576
576
  if org: approve token in org Settings \u2192 Personal access tokens.
577
577
  (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
578
- set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Cr("GitHub",()=>Ye(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Pm(t,e){for(C.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
578
+ set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Rr("GitHub",()=>ze(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Lm(t,e){for(C.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
579
579
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
580
580
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
581
581
  read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
582
582
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
583
- The token is shown ONCE \u2014 copy it right away.`);;){let r=F(await X({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=F(await Vt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){C.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Cr("Bitbucket",()=>Ve(r,o,t)))return{email:r,apiToken:o};C.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Em(){for(;;){let t=F(await Vt({message:`GitLab PAT \u2014 blank to skip
584
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Cr("GitLab",()=>ze(t))){let e=await Wi(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Am(t){if(he(await Yt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
583
+ The token is shown ONCE \u2014 copy it right away.`);;){let r=F(await X({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=F(await zt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){C.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Rr("Bitbucket",()=>Je(r,o,t)))return{email:r,apiToken:o};C.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Dm(){for(;;){let t=F(await zt({message:`GitLab PAT \u2014 blank to skip
584
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Rr("GitLab",()=>Xe(t))){let e=await zi(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Bm(t){if(ye(await Vt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
585
585
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
586
586
  credential. A scoped token hardens setups where the SANDBOX runs outside
587
587
  your trusted network.`,initialValue:!1})))for(t.host==="github"?C.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
588
588
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
589
589
  required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):C.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
590
- (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=F(await Vt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Cr("contextWrite",()=>_m(r,t)))return{token:r};C.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function _m(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 Om(t){if(Do()?.claude?.oauthToken&&!t)return C.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`)."),"";C.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?`
591
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=F(await Vt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||C.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):(C.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 el(){for(;;){let t=F(await X({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=F(await Vt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Cr("YouTrack",()=>Xe({baseUrl:t,token:e}))){let r=await xs({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Nm}from"node:fs";function Q(t){throw new Error(t)}function te(t,e){return(typeof t!="string"||t.trim().length===0)&&Q(`config: '${e}' must be a non-empty string`),t.trim()}function Tr(t,e){if(t==null)return;typeof t!="string"&&Q(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Um(t){(!t||typeof t!="object")&&Q("config: expected a JSON object");let e=t,r=te(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Q("config: 'hubUrl' must start with http(s)://");let o=te(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&Q("config: 'project' is required");let i=n,s=te(i.id,"project.id");lt.test(s)||Q("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=te(i.name,"project.name"),c=te(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Q("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Q("config: 'project.repos' must be an array");let u=l.map((y,w)=>{(!y||typeof y!="object")&&Q(`config: project.repos[${w}] must be an object`);let x=y,O=te(x.host,`project.repos[${w}].host`);O!=="github"&&O!=="bitbucket"&&O!=="gitlab"&&Q(`config: project.repos[${w}].host must be 'github', 'bitbucket' or 'gitlab'`);let j={name:te(x.name,`project.repos[${w}].name`),host:O,owner:te(x.owner,`project.repos[${w}].owner`),repoName:te(x.repoName,`project.repos[${w}].repoName`)},v=Tr(x.defaultBranch,`project.repos[${w}].defaultBranch`);v&&(j.defaultBranch=v);let m=Tr(x.mountAs,`project.repos[${w}].mountAs`);return m&&(j.mountAs=m),j}),f=i.contextRepo;(!f||typeof f!="object")&&Q("config: 'project.contextRepo' is required");let p=f,g=Tr(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&Q("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:g,owner:te(p.owner,"project.contextRepo.owner"),name:Tr(p.name,"project.contextRepo.name")??Ne(s)},h={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:d}},S=Tr(i.youtrackProjectKey,"project.youtrackProjectKey");S&&(h.project.youtrackProjectKey=S),i.index!==void 0&&(typeof i.index!="boolean"&&Q("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Q("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites);let b=e.secrets;if(b!==void 0){(typeof b!="object"||b===null)&&Q("config: 'secrets' must be an object");let y=b,w={};if(y.github){let x=y.github;w.github={token:te(x.token,"secrets.github.token")}}if(y.bitbucket){let x=y.bitbucket;w.bitbucket={email:te(x.email,"secrets.bitbucket.email"),apiToken:te(x.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let x=y.gitlab;w.gitlab={token:te(x.token,"secrets.gitlab.token")}}if(y.youtrack){let x=y.youtrack;w.youtrack={url:te(x.url,"secrets.youtrack.url").replace(/\/$/,""),token:te(x.token,"secrets.youtrack.token")}}if(y.contextWrite){let x=y.contextWrite;w.contextWrite={token:te(x.token,"secrets.contextWrite.token")}}h.secrets=w}return h}async function Lm(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Dm(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await Ye(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 Ve(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await ze(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Xe({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function tl(t){let e=!t.configPath||t.configPath==="-"?await Lm():Nm(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){Q(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let o=Um(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 Dm(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 Kt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??Tt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:p=>console.log(` ${p}`),warn:p=>console.warn(` ${p}`)}})}catch(p){Q(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${n}\u2026`);let u;try{u=await Qe(n,i,a)}catch(p){if(p instanceof A&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await G(n,i,s.id);else if(p instanceof A)Q(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(K(f),Ue({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Re(s.id)}`),dt(s.id,je(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await ao(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${p}); runs once a SANDBOX claims it.`)}catch(p){console.warn(`could not enqueue index job: ${p instanceof Error?p.message:String(p)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as rl,intro as ol,isCancel as nl,log as An,outro as Bm,password as il}from"@clack/prompts";async function Mm(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function sl(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Mm(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){ol("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),An.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await il({message:"Claude OAuth token"});nl(i)&&(rl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),xi({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Fr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=fe(t.profile);if(!e){ol(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),An.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await il({message:"Claude OAuth token"});nl(i)&&(rl("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},K(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(An.success("Claude OAuth token saved."),Bm("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Gm,confirm as Fm,intro as Hm,isCancel as al,log as ie,outro as Km,select as cl,text as ot}from"@clack/prompts";function ll(t){Gm(t),process.exit(1)}function Xt(t){return al(t)&&ll("aborted"),t}function Rr(t){return al(t)&&ll("aborted"),typeof t=="string"?t:""}async function Wm(t,e){let r=Xt(await cl({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=Rr(await ot({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=Rr(await ot({message:"Context Repo name",placeholder:Ne(t),initialValue:Ne(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function ul(t={profile:void 0}){let e=fe(t.profile);Hm(`codepipe project add \u2192 ${e.hubUrl}`);let r=Xt(await ot({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>lt.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=Xt(await ot({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),n=Xt(await cl({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=Xt(await ot({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Xt(await Fm({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=Rr(await ot({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:b=>!b||!b.trim()||ge(b)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!p)break;let g=ge(p);ie.message(`${g.host}: ${g.owner}/${g.repoName}`);let d=Rr(await ot({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:b=>b.trim().length>0?void 0:"required"})).trim(),h=Rr(await ot({message:"default branch (optional)",placeholder:"main"})).trim(),S={name:d,host:g.host,owner:g.owner,repoName:g.repoName};h&&(S.defaultBranch=h),a.push(S)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let l=await Wm(r,a),u=U(e.projectId);ie.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Kt(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??Tt(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>ie.message(p),warn:p=>ie.warn(p)}})}catch(p){ie.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=f,ie.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await Qe(e.hubUrl,e.cliToken,c);ie.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),dt(r,je(c,s,u?.youtrack?.url),{info:g=>ie.message(g),warn:g=>ie.warn(g)}),p.contextRepo&&(ie.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),ie.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&ie.error(` error: ${p.provisioningError}`),Km("done")}catch(p){p instanceof A?(ie.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&ie.message(JSON.stringify(p.payload,null,2))):ie.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{existsSync as qm,rmSync as Ym}from"node:fs";import{confirm as Vm,intro as zm,isCancel as Jm,log as nt,outro as Xm,spinner as Qm}from"@clack/prompts";function Ae(t){nt.error(t),process.exit(1)}var pl=t=>t.trim().replace(/\/+$/,"");async function dl(t){zm("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??de()?.spec.projectId??void 0;e||Ae("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=we(e);r||Ae(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let o=pl(r.hubUrl),n=r.projectId,i=pl(t.hub);i.startsWith("http")||Ae("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??n,c=s===e;c&&a===n&&i===o&&Ae(`profile '${e}' is already on ${o} \u2014 nothing to move.`);let l;{let b=Qm();b.start(`reading project ${n} from ${o}\u2026`);try{l=await G(o,r.cliToken,n),b.stop(`read project ${n} (${l.name})`)}catch(y){throw b.stop("could not read the source project",1),y instanceof A&&Ae(`source HUB ${o} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||Ae(`project ${n} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=U(n),f=(t.account??r.accountEmail??await zt()).trim().toLowerCase();if(nt.message(`move project '${n}'
590
+ (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=F(await zt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Rr("contextWrite",()=>Mm(r,t)))return{token:r};C.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Mm(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 Gm(t){if(Bo()?.claude?.oauthToken&&!t)return C.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`)."),"";C.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?`
591
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=F(await zt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||C.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):(C.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 nl(){for(;;){let t=F(await X({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=F(await zt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Rr("YouTrack",()=>Ze({baseUrl:t,token:e}))){let r=await Rs({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Fm}from"node:fs";function Q(t){throw new Error(t)}function te(t,e){return(typeof t!="string"||t.trim().length===0)&&Q(`config: '${e}' must be a non-empty string`),t.trim()}function Tr(t,e){if(t==null)return;typeof t!="string"&&Q(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Hm(t){(!t||typeof t!="object")&&Q("config: expected a JSON object");let e=t,r=te(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Q("config: 'hubUrl' must start with http(s)://");let o=te(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&Q("config: 'project' is required");let i=n,s=te(i.id,"project.id");ut.test(s)||Q("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=te(i.name,"project.name"),c=te(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Q("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Q("config: 'project.repos' must be an array");let u=l.map((y,w)=>{(!y||typeof y!="object")&&Q(`config: project.repos[${w}] must be an object`);let x=y,O=te(x.host,`project.repos[${w}].host`);O!=="github"&&O!=="bitbucket"&&O!=="gitlab"&&Q(`config: project.repos[${w}].host must be 'github', 'bitbucket' or 'gitlab'`);let j={name:te(x.name,`project.repos[${w}].name`),host:O,owner:te(x.owner,`project.repos[${w}].owner`),repoName:te(x.repoName,`project.repos[${w}].repoName`)},v=Tr(x.defaultBranch,`project.repos[${w}].defaultBranch`);v&&(j.defaultBranch=v);let m=Tr(x.mountAs,`project.repos[${w}].mountAs`);return m&&(j.mountAs=m),j}),d=i.contextRepo;(!d||typeof d!="object")&&Q("config: 'project.contextRepo' is required");let p=d,g=Tr(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&Q("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:g,owner:te(p.owner,"project.contextRepo.owner"),name:Tr(p.name,"project.contextRepo.name")??Le(s)},h={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},S=Tr(i.youtrackProjectKey,"project.youtrackProjectKey");S&&(h.project.youtrackProjectKey=S),i.index!==void 0&&(typeof i.index!="boolean"&&Q("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Q("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites);let b=e.secrets;if(b!==void 0){(typeof b!="object"||b===null)&&Q("config: 'secrets' must be an object");let y=b,w={};if(y.github){let x=y.github;w.github={token:te(x.token,"secrets.github.token")}}if(y.bitbucket){let x=y.bitbucket;w.bitbucket={email:te(x.email,"secrets.bitbucket.email"),apiToken:te(x.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let x=y.gitlab;w.gitlab={token:te(x.token,"secrets.gitlab.token")}}if(y.youtrack){let x=y.youtrack;w.youtrack={url:te(x.url,"secrets.youtrack.url").replace(/\/$/,""),token:te(x.token,"secrets.youtrack.token")}}if(y.contextWrite){let x=y.contextWrite;w.contextWrite={token:te(x.token,"secrets.contextWrite.token")}}h.secrets=w}return h}async function Km(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Wm(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await ze(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${o}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(n=>n.host==="bitbucket")?.owner,o=await Je(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await Xe(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Ze({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function il(t){let e=!t.configPath||t.configPath==="-"?await Km():Fm(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){Q(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let o=Hm(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 Wm(o));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Wt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??Tt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:p=>console.log(` ${p}`),warn:p=>console.warn(` ${p}`)}})}catch(p){Q(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${n}\u2026`);let u;try{u=await Ee(n,i,a)}catch(p){if(p instanceof E&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await M(n,i,s.id);else if(p instanceof E)Q(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let d={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(K(d),De({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Te(s.id)}`),ft(s.id,je(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await co(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${p}); runs once a SANDBOX claims it.`)}catch(p){console.warn(`could not enqueue index job: ${p instanceof Error?p.message:String(p)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as sl,intro as al,isCancel as cl,log as _n,outro as qm,password as ll}from"@clack/prompts";async function Ym(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function ul(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Ym(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){al("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),_n.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await ll({message:"Claude OAuth token"});cl(i)&&(sl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Ri({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Hr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=ge(t.profile);if(!e){al(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),_n.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await ll({message:"Claude OAuth token"});cl(i)&&(sl("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},K(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(_n.success("Claude OAuth token saved."),qm("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Vm,confirm as zm,intro as Jm,isCancel as pl,log as ie,outro as Xm,select as dl,text as nt}from"@clack/prompts";function fl(t){Vm(t),process.exit(1)}function Qt(t){return pl(t)&&fl("aborted"),t}function Ir(t){return pl(t)&&fl("aborted"),typeof t=="string"?t:""}async function Qm(t,e){let r=Qt(await dl({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),o=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",n=Ir(await nt({message:"Context Repo owner (org / group / workspace / user)",placeholder:o||"your-org",initialValue:o,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Ir(await nt({message:"Context Repo name",placeholder:Le(t),initialValue:Le(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function ml(t={profile:void 0}){let e=ge(t.profile);Jm(`codepipe project add \u2192 ${e.hubUrl}`);let r=Qt(await nt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>ut.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=Qt(await nt({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),n=Qt(await dl({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=Qt(await nt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Qt(await zm({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=Ir(await nt({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:b=>!b||!b.trim()||ce(b)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!p)break;let g=ce(p);ie.message(`${g.host}: ${g.owner}/${g.repoName}`);let f=Ir(await nt({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:b=>b.trim().length>0?void 0:"required"})).trim(),h=Ir(await nt({message:"default branch (optional)",placeholder:"main"})).trim(),S={name:f,host:g.host,owner:g.owner,repoName:g.repoName};h&&(S.defaultBranch=h),a.push(S)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let l=await Qm(r,a),u=U(e.projectId);ie.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let d;try{d=await Wt(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??Tt(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>ie.message(p),warn:p=>ie.warn(p)}})}catch(p){ie.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=d,ie.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await Ee(e.hubUrl,e.cliToken,c);ie.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),ft(r,je(c,s,u?.youtrack?.url),{info:g=>ie.message(g),warn:g=>ie.warn(g)}),p.contextRepo&&(ie.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),ie.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&ie.error(` error: ${p.provisioningError}`),Xm("done")}catch(p){p instanceof E?(ie.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&ie.message(JSON.stringify(p.payload,null,2))):ie.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{existsSync as Zm,rmSync as eg}from"node:fs";import{confirm as tg,intro as rg,isCancel as og,log as it,outro as ng,spinner as ig}from"@clack/prompts";function _e(t){it.error(t),process.exit(1)}var gl=t=>t.trim().replace(/\/+$/,"");async function hl(t){rg("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??se()?.spec.projectId??void 0;e||_e("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=ue(e);r||_e(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let o=gl(r.hubUrl),n=r.projectId,i=gl(t.hub);i.startsWith("http")||_e("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??n,c=s===e;c&&a===n&&i===o&&_e(`profile '${e}' is already on ${o} \u2014 nothing to move.`);let l;{let b=ig();b.start(`reading project ${n} from ${o}\u2026`);try{l=await M(o,r.cliToken,n),b.stop(`read project ${n} (${l.name})`)}catch(y){throw b.stop("could not read the source project",1),y instanceof E&&_e(`source HUB ${o} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||_e(`project ${n} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=U(n),d=(t.account??r.accountEmail??await Jt()).trim().toLowerCase();if(it.message(`move project '${n}'
592
592
  from : ${o} (profile ${e})
593
- to : ${i} (profile ${s}, project ${a}, account ${f})
593
+ to : ${i} (profile ${s}, project ${a}, account ${d})
594
594
  \u2022 the source registration on the old HUB is left intact (non-destructive)
595
595
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
596
- `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${o}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${o}`)),!t.yes){let b=await Vm({message:"Continue?",initialValue:!0});(Jm(b)||!b)&&Ae("aborted")}!c&&a===n&&nt.warn(`source and destination share the same project id, so they share one secrets file (${Re(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:p,accountEmail:g}=await Jt(i,f),d={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:g,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};nt.step(`registering project on ${i}\u2026`);let h;try{h=await Qe(i,p,d)}catch(b){if(b instanceof A&&b.status===409){nt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await G(i,p,a)}catch(y){throw y instanceof A&&Ae(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if(b instanceof A&&b.status===403)Ae(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(b instanceof A)Ae(`target HUB \u2192 ${b.status} ${b.message}`);else throw b}nt.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),Ue({hubUrl:i,cliToken:p,projectId:a,accountEmail:g},s);let S={...u??{},hubUrl:i,cliToken:p,projectId:a};if(delete S.sandboxPins,K(S),nt.success(`profile '${s}' \u2192 ${Re(a)}`),c){let b=$e(s);qm(b)&&(Ym(b),nt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}Xm(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as _n,rmSync as Zm,statSync as eg}from"node:fs";import{join as To,relative as tg,resolve as rg}from"node:path";import{cancel as og,intro as ml,isCancel as ng,log as Y,outro as gl,text as kt}from"@clack/prompts";import{simpleGit as hl}from"simple-git";function ce(t){og(t),process.exit(1)}function bt(t){return ng(t)&&ce("aborted"),typeof t=="string"?t:""}async function fl(t){try{let e=await hl(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function ig(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function sg(t,e){let r=U(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(ig(r,e)){Y.message(`reusing existing ${e} credentials`);return}if(Y.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let o=bt(await kt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),n=bt(await kt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:o,apiToken:n}}else{let o=bt(await kt({message:`${e} access token (read access to the repo)`,validate:n=>n.trim()?void 0:"required"})).trim();e==="github"?r.github={token:o}:r.gitlab={token:o}}K(r),Y.success(`saved ${e} credentials`)}async function yl(t){let e=fe(t.profile);ml(`codepipe repo add \u2192 project ${e.projectId}`);let r=de()??void 0,o;try{o=(await G(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){ce(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let n=t.target?.trim();if(!n){let y=await fl(process.cwd());y?(n=process.cwd(),Y.message(`using the current directory (${y})`)):n=bt(await kt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:w=>w.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(_n(n)&&eg(n).isDirectory()){i=rg(n);let y=await fl(i);y||ce(`${i} is not a git repository (no origin remote)`);let w=ge(y);w||ce(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=w,s=y,Y.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let y=ge(n);y||ce(`"${n}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,s=n,Y.message(`${a}: ${c}/${l}`)}let u=bt(await kt({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:y=>y.trim()?void 0:"required"})).trim();o.some(y=>y.name===u)&&ce(`a repo named "${u}" is already registered`);let f=bt(await kt({message:"default branch (optional)",placeholder:"main"})).trim(),p=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let y=tg(r.root,i);p=y===""?".":y}let g=bt(await kt({message:"mount_as (directory relative to the workspace root)",placeholder:p,initialValue:p})).trim()||p;o.some(y=>(y.mountAs??y.name)===g)&&ce(`mount_as "${g}" is already used by another repo`),await sg(e,a);let d={name:u,host:a,owner:c,repoName:l,mountAs:g,...f?{defaultBranch:f}:{}};if(!i){let y=r?To(r.root,g):ke(e.projectId,u);if(_n(To(y,".git")))Y.message(`already cloned at ${y}`);else{Y.info(`cloning ${s} \u2192 ${y} \u2026`);try{await hl().clone(s,y),Y.success(`cloned into ${y}`)}catch(w){ce(`clone failed: ${w instanceof Error?w.message.trim():String(w)}
597
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await la(e.hubUrl,e.cliToken,e.projectId,d)}catch(y){y instanceof A&&ce(`HUB \u2192 ${y.status} ${y.message}`),ce(y instanceof Error?y.message:String(y))}let{updated:S,errors:b}=lr(e.projectId,h.repos,r?.contextDir);for(let y of S)Y.message(`updated ${y}`);for(let y of b)Y.warn(`could not update ${y.path}: ${y.error}`);Y.success(`added "${u}" \u2014 project now has ${h.repos.length} repo(s)`),gl("done")}async function wl(t){let e=fe(t.profile);ml(`codepipe repo remove \u2192 project ${e.projectId}`);let r=de()??void 0,o;try{let c=(await G(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);o=c?c.mountAs??c.name:void 0}catch{}let n;try{n=await ua(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof A&&(a.status===404&&ce(`no repo named "${t.name}" in this project`),ce(`HUB \u2192 ${a.status} ${a.message}`)),ce(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=lr(e.projectId,n.repos,r?.contextDir);for(let a of i)Y.message(`updated ${a}`);for(let a of s)Y.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(o===".")Y.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&o?To(r.root,o):ke(e.projectId,t.name);if(_n(To(a,".git")))try{Zm(a,{recursive:!0,force:!0}),Y.message(`deleted local clone ${a}`)}catch(c){Y.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else Y.message(`no local clone found to purge (${a})`)}Y.success(`removed "${t.name}" \u2014 ${n.repos.length} repo(s) left`),gl("done")}async function kl(t){let e=fe(t.profile),r;try{r=(await G(e.hubUrl,e.cliToken,e.projectId)).repos}catch(o){console.error(`could not read project from HUB: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let o of r){let n=o.mountAs??o.name,i=o.defaultBranch?` @${o.defaultBranch}`:"";console.log(` ${o.name} ${o.host}:${o.owner}/${o.repoName}${i} \u2192 ${n}`)}}import{spawn as ag}from"node:child_process";import{existsSync as bl}from"node:fs";import{homedir as cg,hostname as lg}from"node:os";import{join as Ro}from"node:path";async function ug(t,e,r){let o=ne(e);if(!o)return!0;if(o.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${$e(e)} points at a different HUB (${o.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let n;try{n=await Zs(t.hubUrl.replace(/\/$/,""),o.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(n==="unsupported")return console.log(`[up] worker already registered as ${o.sandboxId} (${o.name})`),!1;if(n==="ok")return console.log(`[up] worker already registered as ${o.sandboxId} (${o.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${o.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${$e(e)} still holds its token.
598
- Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${o.sandboxId} \u2014 replacing the registration`),$i(t.projectId,o.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${o.sandboxId}`),!0}async function pg(t,e,r){let o=ne(e)!==null;if(!await ug(t,e,r))return;console.log(o?"[up] re-registering the worker \u2014 requesting an account-issued token from HUB":"[up] no worker registration \u2014 requesting an account-issued token from HUB");let n;try{({secret:n}=await so(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 mt({hub:t.hubUrl,token:n,name:r.name??`${lg()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...o?{force:!0}:{},...e?{profile:e}:{}})}function dg(t,e){let r=ne(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=Pe(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=Gr(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 fg(t,e){let r=process.cwd(),o=Ro(r,Te);if(Dr(t.projectId,r)){console.log(`[up] using the workspace context at ${o}`);return}if(bl(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 G(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await En(r);if(!ii(r,i?.parsed??null,n.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=U(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await po({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=Ro(cg(),".codepipe",e?Ro("profiles",e,"context-config"):"context-config");if(qr(c.contextDir,l,a),!bl(Ro(c.contextDir,"project.yaml"))){Pt(c.contextDir);let u={projectId:t.projectId,name:n.name,automationLevel:n.automationLevel,repos:n.repos,...n.youtrackProjectKey?{youtrackProjectKey:n.youtrackProjectKey}:{}};cr(c.contextDir,je(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${o}`)}async function $l(t){let{cfg:e,profile:r}=Mr(t.profile);await fg(e,r),await pg(e,r,t),dg(e.projectId,r);let o=process.argv[1];if(!o)throw new Error("cannot resolve the codepipe entry script for child processes");let n=(g,d)=>{let h=S=>b=>{for(let y of b.toString("utf-8").split(`
599
- `))y.length>0&&S.write(`${d} ${y}
600
- `)};g.stdout?.on("data",h(process.stdout)),g.stderr?.on("data",h(process.stderr))},i=(g,d)=>{let h=ag(process.execPath,[o,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return n(h,g),h};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=g=>{if(!l){l=!0,console.log(`
601
- [up] ${g} \u2014 stopping both roles`);for(let{child:d}of c)d.exitCode===null&&d.kill(g);setTimeout(()=>{for(let{name:d,child:h}of c)h.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),h.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let f=c.map(({name:g,child:d})=>new Promise(h=>{d.on("exit",(S,b)=>h({name:g,code:S??(b?1:0)}))})),p=await Promise.race(f);l||(console.log(`[up] ${p.name} exited (code ${p.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(f),process.exit(p.code)}import{existsSync as _l,mkdirSync as wg,readFileSync as kg,writeFileSync as bg}from"node:fs";import{homedir as $g}from"node:os";import{dirname as xg,join as Ol}from"node:path";import*as Zt from"node:readline";import{existsSync as Un,readFileSync as mg,writeFileSync as gg}from"node:fs";import{join as jr}from"node:path";import{simpleGit as Nn}from"simple-git";var xl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],hg="apply-queue.json";function vl(t){return jr(t,hg)}function Qt(t){let e=vl(t);if(!Un(e))return{};try{return JSON.parse(mg(e,"utf-8"))}catch{return{}}}function Sl(t,e){gg(vl(t),JSON.stringify(e,null,2)+`
602
- `)}async function Cl(t,e,r,o,n){let i;try{i=await ia(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(p){return{ok:!1,message:`claim failed: ${p instanceof Error?p.message:String(p)}`}}let s=[];for(let p of i.repos){let g=t.spec.repos.find(b=>b.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let d=jr(t.root,g.mountAs);if(!Un(jr(d,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Nn(d).status()).isClean())return{ok:!1,message:`${g.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:p,spec:g,dir:d})}let a=[];for(let p of s){let g=Nn(p.dir),d=await yg(g),h=p.claimRepo;try{await g.fetch()}catch(y){return await On(a,n),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${Ir(y)}`}}let S=`origin/${h.baseRef}`,b;try{b=await Xr(g,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(y){return await On(a,n),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${Ir(y)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:d,branch:h.branchName,baseSha:S,deliveryCommit:b,startPoint:S})}let c=[];for(let p of a)try{if(o==="apply"){await p.git.checkout(["-B",p.branch,p.startPoint]),await p.git.raw([...xl,"cherry-pick",p.deliveryCommit]);let g=(await p.git.revparse(["HEAD"])).trim();c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha,appliedSha:g})}else await p.git.checkout(["--detach",p.startPoint]),await p.git.raw([...xl,"cherry-pick","--no-commit",p.deliveryCommit]),await p.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha})}catch(g){return await p.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await On(a,n),{ok:!1,message:`apply failed in ${p.mountAs}: ${Ir(g)} (rolled back all repos)`}}let l=Qt(t.contextDir);l[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},Sl(t.contextDir,l);let u=c.map(p=>p.mountAs).join(", "),f=o==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${o==="apply"?"applied":"unstashed"} ${r} in ${u}
603
- ${f}
604
- or: /abort ${r} --reason "..."`}}function Ln(t,e){let r=Qt(t);r[e]&&(delete r[e],Sl(t,r))}async function On(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}: ${Ir(o)} \u2014 check manually`)}}async function Tl(t,e,r){let n=Qt(t.contextDir)[e];if(n){for(let i of n.repos){let s=jr(t.root,i.mountAs);if(!Un(jr(s,".git")))continue;let a=Nn(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${Ir(u)} \u2014 check manually`)}}Ln(t.contextDir,e)}}async function yg(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Ir(t){return t instanceof Error?t.message.trim():String(t)}var Io=Ol($g(),".codepipe","history"),Rl=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Nl=500,Il=40;async function Ul(){let t=de();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)),ar(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=Qt(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
596
+ `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${o}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${o}`)),!t.yes){let b=await tg({message:"Continue?",initialValue:!0});(og(b)||!b)&&_e("aborted")}!c&&a===n&&it.warn(`source and destination share the same project id, so they share one secrets file (${Te(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:p,accountEmail:g}=await Xt(i,d),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:g,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};it.step(`registering project on ${i}\u2026`);let h;try{h=await Ee(i,p,f)}catch(b){if(b instanceof E&&b.status===409){it.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await M(i,p,a)}catch(y){throw y instanceof E&&_e(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if(b instanceof E&&b.status===403)_e(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(b instanceof E)_e(`target HUB \u2192 ${b.status} ${b.message}`);else throw b}it.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),De({hubUrl:i,cliToken:p,projectId:a,accountEmail:g},s);let S={...u??{},hubUrl:i,cliToken:p,projectId:a};if(delete S.sandboxPins,K(S),it.success(`profile '${s}' \u2192 ${Te(a)}`),c){let b=$e(s);Zm(b)&&(eg(b),it.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}ng(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as yl,readFileSync as wl}from"node:fs";import{join as Nn}from"node:path";import{confirm as sg,intro as ag,isCancel as cg,log as On,outro as lg,spinner as ug}from"@clack/prompts";import{parse as kl}from"yaml";import{simpleGit as pg}from"simple-git";function Oe(t){On.error(t),process.exit(1)}function dg(t){let e=Nn(t,"regimen.yaml");if(!yl(e))return"assisted";try{return kl(wl(e,"utf-8"))?.automation?.level==="full"?"full":"assisted"}catch{return"assisted"}}function fg(t){let e=Nn(t,"project.yaml");try{let n=kl(wl(e,"utf-8"))?.youtrack?.project_key;return typeof n=="string"&&n.trim()?n.trim():void 0}catch{return}}async function mg(t){if(!yl(Nn(t,".git")))throw new Error(`${t} is not a git clone \u2014 the Context Repo clone is required to restore (re-run \`codepipe clone <id>\` or \`codepipe init\` if it is missing).`);let e=pg(t),r;try{r=(await e.remote(["get-url","origin"])||"").toString().trim()}catch(i){throw new Error(`could not read the Context Repo remote: ${i instanceof Error?i.message:String(i)}`)}if(!r)throw new Error(`the Context Repo clone at ${t} has no 'origin' remote.`);let o=ce(r);if(!o)throw new Error(`could not parse the Context Repo remote '${r}' \u2014 only github.com / gitlab.com / bitbucket.org are supported.`);let n="main";try{let i=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();i&&i!=="HEAD"&&(n=i)}catch{}return{host:o.host,owner:o.owner,name:o.repoName,cloneUrl:r,branch:n}}async function gg(t,e){let r=dg(t),o=fg(t),n=await mg(t);return{projectId:e.projectId,name:e.name,automationLevel:r,repos:e.repos.map(i=>({name:i.name,host:i.host,owner:i.owner,repoName:i.repoName,defaultBranch:i.defaultBranch,...i.mountAs&&i.mountAs!==i.name?{mountAs:i.mountAs}:{}})),contextRepo:n,...o?{youtrackProjectKey:o}:{}}}async function bl(t){ag("codepipe project restore \u2014 re-register this project on its HUB from local state");let e;try{e=se()}catch(u){Oe(`could not read .codepipe/project.yaml: ${u instanceof Error?u.message:String(u)}`)}e||Oe("no project workspace here \u2014 run `codepipe project restore` from the project folder (the one that holds `.codepipe/`).");let{contextDir:r,spec:o}=e,n=t.cliProfile??o.projectId,i=ue(n);i||Oe(`profile '${n}' is not initialised on this machine (~/.codepipe/profiles/${n}/config.json is missing) \u2014 cannot restore without the saved HUB URL and CLI token.`),i.projectId!==o.projectId&&Oe(`this folder is the workspace of project '${o.projectId}', but profile '${n}' is bound to '${i.projectId}' \u2014 pass the right --profile or restore from the matching folder.`);let s;try{s=await gg(r,o)}catch(u){Oe(u instanceof Error?u.message:String(u))}let a=s.contextRepo;if(On.message(`restore project '${o.projectId}' on ${i.hubUrl}
597
+ name : ${o.name}
598
+ automation : ${s.automationLevel}
599
+ youtrack key : ${s.youtrackProjectKey??"(none)"}
600
+ repos : ${o.repos.length===0?"(none)":o.repos.map(u=>`${u.host}:${u.owner}/${u.repoName}`).join(", ")}
601
+ context repo : ${a.host}:${a.owner}/${a.name}@${a.branch}
602
+ \u2022 the Context Repo is reused as-is (not re-provisioned)
603
+ \u2022 task/job history is NOT restored \u2014 the project starts clean on the HUB`),!t.yes){let u=await sg({message:"Continue?",initialValue:!0});(cg(u)||!u)&&Oe("aborted")}let c=ug();c.start(`registering project on ${i.hubUrl}\u2026`);let l;try{l=await Ee(i.hubUrl,i.cliToken,s),c.stop(`project ${l.projectId} restored (${l.provisioningStatus})`)}catch(u){if(c.stop("registration failed",1),u instanceof E&&u.status===409){On.warn(`project ${o.projectId} already exists on ${i.hubUrl} \u2014 nothing to restore.`);try{l=await M(i.hubUrl,i.cliToken,o.projectId)}catch(d){throw d instanceof E&&Oe(`HUB \u2192 ${d.status} ${d.message}`),d}}else if(u instanceof E&&u.status===401)Oe("HUB rejected the saved CLI token (401). It may have been revoked \u2014 re-run `codepipe init` in this folder to sign in again.");else if(u instanceof E&&u.status===403)Oe(`project ${o.projectId} exists on ${i.hubUrl} under a different owner \u2014 it cannot be restored under this account.`);else if(u instanceof E)Oe(`HUB \u2192 ${u.status} ${u.message}`);else throw u}lg(`done. next: \`codepipe up\` from this folder \u2014 starts the daemon and a worker on ${i.hubUrl}.`)}import{existsSync as Un,rmSync as hg,statSync as yg}from"node:fs";import{join as To,relative as wg,resolve as kg}from"node:path";import{cancel as bg,intro as xl,isCancel as $g,log as V,outro as vl,text as bt}from"@clack/prompts";import{simpleGit as Sl}from"simple-git";function pe(t){bg(t),process.exit(1)}function $t(t){return $g(t)&&pe("aborted"),typeof t=="string"?t:""}async function $l(t){try{let e=await Sl(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function xg(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function vg(t,e){let r=U(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(xg(r,e)){V.message(`reusing existing ${e} credentials`);return}if(V.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let o=$t(await bt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),n=$t(await bt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:o,apiToken:n}}else{let o=$t(await bt({message:`${e} access token (read access to the repo)`,validate:n=>n.trim()?void 0:"required"})).trim();e==="github"?r.github={token:o}:r.gitlab={token:o}}K(r),V.success(`saved ${e} credentials`)}async function Cl(t){let e=ge(t.profile);xl(`codepipe repo add \u2192 project ${e.projectId}`);let r=se()??void 0,o;try{o=(await M(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){pe(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let n=t.target?.trim();if(!n){let y=await $l(process.cwd());y?(n=process.cwd(),V.message(`using the current directory (${y})`)):n=$t(await bt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:w=>w.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Un(n)&&yg(n).isDirectory()){i=kg(n);let y=await $l(i);y||pe(`${i} is not a git repository (no origin remote)`);let w=ce(y);w||pe(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=w,s=y,V.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let y=ce(n);y||pe(`"${n}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,s=n,V.message(`${a}: ${c}/${l}`)}let u=$t(await bt({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:y=>y.trim()?void 0:"required"})).trim();o.some(y=>y.name===u)&&pe(`a repo named "${u}" is already registered`);let d=$t(await bt({message:"default branch (optional)",placeholder:"main"})).trim(),p=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let y=wg(r.root,i);p=y===""?".":y}let g=$t(await bt({message:"mount_as (directory relative to the workspace root)",placeholder:p,initialValue:p})).trim()||p;o.some(y=>(y.mountAs??y.name)===g)&&pe(`mount_as "${g}" is already used by another repo`),await vg(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:g,...d?{defaultBranch:d}:{}};if(!i){let y=r?To(r.root,g):ke(e.projectId,u);if(Un(To(y,".git")))V.message(`already cloned at ${y}`);else{V.info(`cloning ${s} \u2192 ${y} \u2026`);try{await Sl().clone(s,y),V.success(`cloned into ${y}`)}catch(w){pe(`clone failed: ${w instanceof Error?w.message.trim():String(w)}
604
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await fa(e.hubUrl,e.cliToken,e.projectId,f)}catch(y){y instanceof E&&pe(`HUB \u2192 ${y.status} ${y.message}`),pe(y instanceof Error?y.message:String(y))}let{updated:S,errors:b}=ur(e.projectId,h.repos,r?.contextDir);for(let y of S)V.message(`updated ${y}`);for(let y of b)V.warn(`could not update ${y.path}: ${y.error}`);V.success(`added "${u}" \u2014 project now has ${h.repos.length} repo(s)`),vl("done")}async function Rl(t){let e=ge(t.profile);xl(`codepipe repo remove \u2192 project ${e.projectId}`);let r=se()??void 0,o;try{let c=(await M(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);o=c?c.mountAs??c.name:void 0}catch{}let n;try{n=await ma(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof E&&(a.status===404&&pe(`no repo named "${t.name}" in this project`),pe(`HUB \u2192 ${a.status} ${a.message}`)),pe(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=ur(e.projectId,n.repos,r?.contextDir);for(let a of i)V.message(`updated ${a}`);for(let a of s)V.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(o===".")V.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&o?To(r.root,o):ke(e.projectId,t.name);if(Un(To(a,".git")))try{hg(a,{recursive:!0,force:!0}),V.message(`deleted local clone ${a}`)}catch(c){V.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else V.message(`no local clone found to purge (${a})`)}V.success(`removed "${t.name}" \u2014 ${n.repos.length} repo(s) left`),vl("done")}async function Tl(t){let e=ge(t.profile),r;try{r=(await M(e.hubUrl,e.cliToken,e.projectId)).repos}catch(o){console.error(`could not read project from HUB: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let o of r){let n=o.mountAs??o.name,i=o.defaultBranch?` @${o.defaultBranch}`:"";console.log(` ${o.name} ${o.host}:${o.owner}/${o.repoName}${i} \u2192 ${n}`)}}import{spawn as Sg}from"node:child_process";import{existsSync as Il}from"node:fs";import{homedir as Cg,hostname as Rg}from"node:os";import{join as Io}from"node:path";async function Tg(t,e,r){let o=ne(e);if(!o)return!0;if(o.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${$e(e)} points at a different HUB (${o.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let n;try{n=await oa(t.hubUrl.replace(/\/$/,""),o.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(n==="unsupported")return console.log(`[up] worker already registered as ${o.sandboxId} (${o.name})`),!1;if(n==="ok")return console.log(`[up] worker already registered as ${o.sandboxId} (${o.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${o.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${$e(e)} still holds its token.
605
+ Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${o.sandboxId} \u2014 replacing the registration`),Ci(t.projectId,o.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${o.sandboxId}`),!0}async function Ig(t,e,r){let o=ne(e)!==null;if(!await Tg(t,e,r))return;console.log(o?"[up] re-registering the worker \u2014 requesting an account-issued token from HUB":"[up] no worker registration \u2014 requesting an account-issued token from HUB");let n;try{({secret:n}=await ao(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof E&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof E&&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 E?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 gt({hub:t.hubUrl,token:n,name:r.name??`${Rg()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...o?{force:!0}:{},...e?{profile:e}:{}})}function jg(t,e){let r=ne(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=Pe(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=Fr(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 Pg(t,e){let r=process.cwd(),o=Io(r,Re);if(Br(t.projectId,r)){console.log(`[up] using the workspace context at ${o}`);return}if(Il(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 M(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await An(r);if(!li(r,i?.parsed??null,n.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=U(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await fo({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=Io(Cg(),".codepipe",e?Io("profiles",e,"context-config"):"context-config");if(Yr(c.contextDir,l,a),!Il(Io(c.contextDir,"project.yaml"))){Et(c.contextDir);let u={projectId:t.projectId,name:n.name,automationLevel:n.automationLevel,repos:n.repos,...n.youtrackProjectKey?{youtrackProjectKey:n.youtrackProjectKey}:{}};lr(c.contextDir,je(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${o}`)}async function jl(t){let{cfg:e,profile:r}=Gr(t.profile);await Pg(e,r),await Ig(e,r,t),jg(e.projectId,r);let o=process.argv[1];if(!o)throw new Error("cannot resolve the codepipe entry script for child processes");let n=(g,f)=>{let h=S=>b=>{for(let y of b.toString("utf-8").split(`
606
+ `))y.length>0&&S.write(`${f} ${y}
607
+ `)};g.stdout?.on("data",h(process.stdout)),g.stderr?.on("data",h(process.stderr))},i=(g,f)=>{let h=Sg(process.execPath,[o,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return n(h,g),h};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=g=>{if(!l){l=!0,console.log(`
608
+ [up] ${g} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(g);setTimeout(()=>{for(let{name:f,child:h}of c)h.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),h.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let d=c.map(({name:g,child:f})=>new Promise(h=>{f.on("exit",(S,b)=>h({name:g,code:S??(b?1:0)}))})),p=await Promise.race(d);l||(console.log(`[up] ${p.name} exited (code ${p.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(d),process.exit(p.code)}import{existsSync as Gl,mkdirSync as Ng,readFileSync as Ug,writeFileSync as Lg}from"node:fs";import{homedir as Dg}from"node:os";import{dirname as Bg,join as Fl}from"node:path";import*as er from"node:readline";import{existsSync as Bn,readFileSync as Eg,writeFileSync as Ag}from"node:fs";import{join as Pr}from"node:path";import{simpleGit as Dn}from"simple-git";var Pl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],_g="apply-queue.json";function El(t){return Pr(t,_g)}function Zt(t){let e=El(t);if(!Bn(e))return{};try{return JSON.parse(Eg(e,"utf-8"))}catch{return{}}}function Al(t,e){Ag(El(t),JSON.stringify(e,null,2)+`
609
+ `)}async function _l(t,e,r,o,n){let i;try{i=await la(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(p){return{ok:!1,message:`claim failed: ${p instanceof Error?p.message:String(p)}`}}let s=[];for(let p of i.repos){let g=t.spec.repos.find(b=>b.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let f=Pr(t.root,g.mountAs);if(!Bn(Pr(f,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Dn(f).status()).isClean())return{ok:!1,message:`${g.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:p,spec:g,dir:f})}let a=[];for(let p of s){let g=Dn(p.dir),f=await Og(g),h=p.claimRepo;try{await g.fetch()}catch(y){return await Ln(a,n),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${jr(y)}`}}let S=`origin/${h.baseRef}`,b;try{b=await Qr(g,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(y){return await Ln(a,n),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${jr(y)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:f,branch:h.branchName,baseSha:S,deliveryCommit:b,startPoint:S})}let c=[];for(let p of a)try{if(o==="apply"){await p.git.checkout(["-B",p.branch,p.startPoint]),await p.git.raw([...Pl,"cherry-pick",p.deliveryCommit]);let g=(await p.git.revparse(["HEAD"])).trim();c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha,appliedSha:g})}else await p.git.checkout(["--detach",p.startPoint]),await p.git.raw([...Pl,"cherry-pick","--no-commit",p.deliveryCommit]),await p.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha})}catch(g){return await p.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Ln(a,n),{ok:!1,message:`apply failed in ${p.mountAs}: ${jr(g)} (rolled back all repos)`}}let l=Zt(t.contextDir);l[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},Al(t.contextDir,l);let u=c.map(p=>p.mountAs).join(", "),d=o==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${o==="apply"?"applied":"unstashed"} ${r} in ${u}
610
+ ${d}
611
+ or: /abort ${r} --reason "..."`}}function Mn(t,e){let r=Zt(t);r[e]&&(delete r[e],Al(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}: ${jr(o)} \u2014 check manually`)}}async function Ol(t,e,r){let n=Zt(t.contextDir)[e];if(n){for(let i of n.repos){let s=Pr(t.root,i.mountAs);if(!Bn(Pr(s,".git")))continue;let a=Dn(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${jr(u)} \u2014 check manually`)}}Mn(t.contextDir,e)}}async function Og(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function jr(t){return t instanceof Error?t.message.trim():String(t)}var jo=Fl(Dg(),".codepipe","history"),Nl=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Hl=500,Ul=40;async function Kl(){let t=se();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)),cr(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=Zt(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
605
612
  \u26A0 unfinished local apply: ${o.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
606
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=Zt.createInterface({input:process.stdin,output:process.stdout,completer:vg,history:Hg(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};Qi(s=>$t(i,s)),i.daemon=uo({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>$t(i,s),warn:s=>$t(i,s)},onEvent:s=>Lg(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Bn(i),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await Sg(i,a)){Al(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Bn(i),n.prompt()}),n.on("close",()=>{Al(i)})}function vg(t){let e=Rl.filter(r=>r.startsWith(t));return[e.length?e:Rl,t]}async function Sg(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return Cg(),!1;case"/status":return await Tg(t),!1;case"/tasks":return await Rg(t,o),!1;case"/task":return await Ig(t,o),!1;case"/sync":return await jg(t),!1;case"/logs":return Dg(t,o),!1;case"/monitor":return Bg(t),!1;case"/apply":return await jl(t,o,"apply"),!1;case"/unstash":return await jl(t,o,"unstash"),!1;case"/applied":return await Pg(t,o),!1;case"/abort":return await Eg(t,o),!1;case"/approve":return await Pl(t,o,"approve"),!1;case"/merge":return await Pl(t,o,"merge"),!1;case"/login":return _g(t,o),!1;case"/secret":return Og(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Cg(){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(`
607
- `))}async function Tg(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=_l(Ol(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function Rg(t,e){let r=Mg(e,"--phase");try{let o=await oa(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){Er(o)}}async function Ig(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await na(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){Er(o)}}async function jg(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 jl(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}let n=await Cl(t.ws,t.secrets,o,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${n.message}`)}async function Pg(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=Qt(t.ws.contextDir)[r],i=Gg(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,f;if(l>0?(u=c.slice(0,l),f=c.slice(l+1)):(f=c,u=n?.repos.length===1?Ag(t,n.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let p=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!p){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:u,url:f,number:Number(p[1])})}try{let c=await sa(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Ln(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Er(c)}}async function Pl(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await ca(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){Er(n)}}async function Eg(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=Fg(e,"--reason")||"local apply aborted";await Tl(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await aa(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){Er(n)}}function Ag(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function _g(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},K(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 Og(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(`
608
- `)}`:" (none)");return}if(r==="set"){let i=n.join(" ");if(!o||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}Ng(t.secrets,o,i),K(t.secrets),ar(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}Ug(t.secrets,o),K(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function Ng(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 Ug(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 Lg(t,e){switch(e.kind){case"connected":t.connection="connecting",$t(t,"[hub] connected");break;case"registered":t.connection="registered",$t(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Pr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",$t(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Pr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Pr(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?$t(t,`[hub] action ${e.actionType} done`):Pr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function $t(t,e){t.logBuffer.push(e),t.logBuffer.length>Nl&&t.logBuffer.shift(),t.follow&&Pr(t,e)}function Dg(t,e){let r=e[0];if(r==="follow"||r==="on"){Dn(t,!0);return}if(r==="off"){Dn(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(Nl,Number(r)||Il)):Il,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 Bg(t){Dn(t,!t.follow)}function Dn(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Pr(t,e){Zt.cursorTo(process.stdout,0),Zt.clearLine(process.stdout,0),process.stdout.write(e+`
609
- `),t.unread+=1,Bn(t),t.rl.prompt(!0)}function Bn(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var El=!1;function Al(t){El||(El=!0,Kg(t.rl),t.daemon.stop(),console.log(`
610
- bye.`),setTimeout(()=>process.exit(0),150))}function Mg(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Gg(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 Fg(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Er(t){t instanceof A?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Hg(){if(!_l(Io))return[];try{return kg(Io,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Kg(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{wg(xg(Io),{recursive:!0}),bg(Io,r.slice().reverse().join(`
613
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=er.createInterface({input:process.stdin,output:process.stdout,completer:Mg,history:sh(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};rs(s=>xt(i,s)),i.daemon=po({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>xt(i,s),warn:s=>xt(i,s)},onEvent:s=>eh(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Fn(i),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await Gg(i,a)){Ml(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Fn(i),n.prompt()}),n.on("close",()=>{Ml(i)})}function Mg(t){let e=Nl.filter(r=>r.startsWith(t));return[e.length?e:Nl,t]}async function Gg(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return Fg(),!1;case"/status":return await Hg(t),!1;case"/tasks":return await Kg(t,o),!1;case"/task":return await Wg(t,o),!1;case"/sync":return await qg(t),!1;case"/logs":return th(t,o),!1;case"/monitor":return rh(t),!1;case"/apply":return await Ll(t,o,"apply"),!1;case"/unstash":return await Ll(t,o,"unstash"),!1;case"/applied":return await Yg(t,o),!1;case"/abort":return await Vg(t,o),!1;case"/approve":return await Dl(t,o,"approve"),!1;case"/merge":return await Dl(t,o,"merge"),!1;case"/login":return Jg(t,o),!1;case"/secret":return Xg(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Fg(){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(`
614
+ `))}async function Hg(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=Gl(Fl(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function Kg(t,e){let r=oh(e,"--phase");try{let o=await aa(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){Ar(o)}}async function Wg(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await ca(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){Ar(o)}}async function qg(t){let e=await Cr(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 Ll(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}let n=await _l(t.ws,t.secrets,o,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${n.message}`)}async function Yg(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=Zt(t.ws.contextDir)[r],i=nh(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,d;if(l>0?(u=c.slice(0,l),d=c.slice(l+1)):(d=c,u=n?.repos.length===1?zg(t,n.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${d}`);return}let p=d.match(/(?:pull|pull-requests)\/(\d+)/);if(!p){console.log(` cannot parse PR number from ${d}`);return}a.push({repoName:u,url:d,number:Number(p[1])})}try{let c=await ua(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Mn(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Ar(c)}}async function Dl(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await da(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){Ar(n)}}async function Vg(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=ih(e,"--reason")||"local apply aborted";await Ol(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await pa(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){Ar(n)}}function zg(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Jg(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},K(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 Xg(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(`
615
+ `)}`:" (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}Qg(t.secrets,o,i),K(t.secrets),cr(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}Zg(t.secrets,o),K(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function Qg(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 Zg(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 eh(t,e){switch(e.kind){case"connected":t.connection="connecting",xt(t,"[hub] connected");break;case"registered":t.connection="registered",xt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Er(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",xt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Er(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Er(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?xt(t,`[hub] action ${e.actionType} done`):Er(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function xt(t,e){t.logBuffer.push(e),t.logBuffer.length>Hl&&t.logBuffer.shift(),t.follow&&Er(t,e)}function th(t,e){let r=e[0];if(r==="follow"||r==="on"){Gn(t,!0);return}if(r==="off"){Gn(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(Hl,Number(r)||Ul)):Ul,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 rh(t){Gn(t,!t.follow)}function Gn(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Er(t,e){er.cursorTo(process.stdout,0),er.clearLine(process.stdout,0),process.stdout.write(e+`
616
+ `),t.unread+=1,Fn(t),t.rl.prompt(!0)}function Fn(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Bl=!1;function Ml(t){Bl||(Bl=!0,ah(t.rl),t.daemon.stop(),console.log(`
617
+ bye.`),setTimeout(()=>process.exit(0),150))}function oh(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function nh(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 ih(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Ar(t){t instanceof E?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function sh(){if(!Gl(jo))return[];try{return Ug(jo,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function ah(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{Ng(Bg(jo),{recursive:!0}),Lg(jo,r.slice().reverse().join(`
611
618
  `)+`
612
- `)}catch{}}import{hostname as Wg}from"node:os";import{cancel as qg,confirm as Ll,intro as Yg,isCancel as Ml,log as er,multiselect as Vg,outro as Dl,password as zg,select as Mn,text as Gn}from"@clack/prompts";function Ar(t){qg(t),process.exit(1)}function tr(t){return Ml(t)&&Ar("aborted"),t}function jo(t){return Ml(t)&&Ar("aborted"),typeof t=="string"?t:""}function Fn(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Bl(t,e){try{let{secret:r}=await so(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&Ar("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 Jg(t,e){if(tr(await Mn({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 ea(t,e);if(n.length>0)return tr(await Vg({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}));er.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){er.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return jo(await Gn({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){Yg("codepipe worker \u2014 set up this machine as a runner");let e=ne(t.profile);e&&(er.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),tr(await Ll({message:"re-register this worker?",initialValue:!1}))||Ar("keeping the existing registration"));let r=we(t.profile)??we(),o=jo(await Gn({message:"HUB URL",placeholder:ve,initialValue:L("HUB_URL")??r?.hubUrl??ve,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=tr(await Mn({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 Bl(o,a),er.success("account-issued registration token minted");else if(i==="login"){let p=await zt();a=(await Jt(o,p)).cliToken,s=await Bl(o,a),er.success("account-issued registration token minted")}else s=jo(await zg({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Ar("a registration token is required");let c=await Jg(o,a),l=jo(await Gn({message:"worker name",initialValue:Wg(),validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=tr(await Mn({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 mt({hub:o,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),er.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!tr(await Ll({message:"start the claim-loop now?",initialValue:!0}))){Dl("registered. start later with `codepipe worker`.");return}Dl("starting the claim-loop\u2026"),await vr(t.profile?{profile:t.profile}:{})}function Qg(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return L("PROFILE")}var V=Qg();ui(V);fi();var le=new Xg;le.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(pe).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await Ul()}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 tl({configPath:t.config,skipVerify:t.skipVerify===!0}):await Wc({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await vi({...t,profile:V})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await qc({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 Ea({profile:V})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await Lc({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 sl({profile:V,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await bc({profile:V})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await $l({profile:V,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Gl=le.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Gl.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??L("HUB_URL")??we(V)?.hubUrl??ve,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Fn()){await Hn({profile:V});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let o=L("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??L("WORKER_NAME"),i=t.llm??L("WORKER_LLM");await mt({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...V?{profile:V}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Gl.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ne(V)&&Fn()){await Hn({profile:V});return}await vr(V?{profile:V}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Fl=le.command("project").description("Manage CodePipe projects");Fl.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await ul({profile:V})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Fl.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await dl({...t,cliProfile:V})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Kn=le.command("repo").description("Manage the project's git repositories");Kn.command("add").description("Add a repo to this project (a path to an existing clone, or a clone URL)").argument("[target]","Path to an already-cloned repo, or a repo clone URL").action(async t=>{try{await yl({profile:V,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Kn.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await wl({profile:V,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Kn.command("list").description("List the project's repos").action(async()=>{try{await kl({profile:V})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.parseAsync();
619
+ `)}catch{}}import{hostname as ch}from"node:os";import{cancel as lh,confirm as Wl,intro as uh,isCancel as Vl,log as tr,multiselect as ph,outro as ql,password as dh,select as Hn,text as Kn}from"@clack/prompts";function _r(t){lh(t),process.exit(1)}function rr(t){return Vl(t)&&_r("aborted"),t}function Po(t){return Vl(t)&&_r("aborted"),typeof t=="string"?t:""}function Wn(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Yl(t,e){try{let{secret:r}=await ao(t,e);return r}catch(r){throw r instanceof E&&r.status===404&&_r("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function fh(t,e){if(rr(await Hn({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 na(t,e);if(n.length>0)return rr(await ph({message:"pick the projects (space to toggle, enter to confirm)",options:n.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));tr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){tr.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return Po(await Kn({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 qn(t){uh("codepipe worker \u2014 set up this machine as a runner");let e=ne(t.profile);e&&(tr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),rr(await Wl({message:"re-register this worker?",initialValue:!1}))||_r("keeping the existing registration"));let r=ue(t.profile)??ue(),o=Po(await Kn({message:"HUB URL",placeholder:ve,initialValue:L("HUB_URL")??r?.hubUrl??ve,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=rr(await Hn({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 Yl(o,a),tr.success("account-issued registration token minted");else if(i==="login"){let p=await Jt();a=(await Xt(o,p)).cliToken,s=await Yl(o,a),tr.success("account-issued registration token minted")}else s=Po(await dh({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||_r("a registration token is required");let c=await fh(o,a),l=Po(await Kn({message:"worker name",initialValue:ch(),validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=rr(await Hn({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await gt({hub:o,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),tr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!rr(await Wl({message:"start the claim-loop now?",initialValue:!0}))){ql("registered. start later with `codepipe worker`.");return}ql("starting the claim-loop\u2026"),await Sr(t.profile?{profile:t.profile}:{})}function gh(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return L("PROFILE")}var Y=gh();mi(Y);yi();var de=new mh;de.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(me).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 Kl()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});de.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 il({configPath:t.config,skipVerify:t.skipVerify===!0}):await zc({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});de.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Ti({...t,profile:Y})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});de.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 Jc({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});de.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Na({profile:Y})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});de.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 Gc({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});de.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 ul({profile:Y,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});de.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Sc({profile:Y})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});de.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await jl({profile:Y,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var zl=de.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");zl.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??L("HUB_URL")??ue(Y)?.hubUrl??ve,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Wn()){await qn({profile:Y});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let o=L("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??L("WORKER_NAME"),i=t.llm??L("WORKER_LLM");await gt({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...Y?{profile:Y}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});zl.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ne(Y)&&Wn()){await qn({profile:Y});return}await Sr(Y?{profile:Y}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Yn=de.command("project").description("Manage CodePipe projects");Yn.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await ml({profile:Y})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Yn.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await hl({...t,cliProfile:Y})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Vn=de.command("repo").description("Manage the project's git repositories");Vn.command("add").description("Add a repo to this project (a path to an existing clone, or a clone URL)").argument("[target]","Path to an already-cloned repo, or a repo clone URL").action(async t=>{try{await Cl({profile:Y,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Vn.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await Rl({profile:Y,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Vn.command("list").description("List the project's repos").action(async()=>{try{await Tl({profile:Y})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Yn.command("restore").description("Re-register this project on its HUB from local state (recovery; no full init wizard)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await bl({yes:t.yes===!0,cliProfile:Y})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});de.parseAsync();