@code-partner/codepipe 0.1.135-dev.46.g2a7d2a7 → 0.1.135

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 +97 -97
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,35 +1,35 @@
1
1
  #!/usr/bin/env node
2
- var ce="0.1.135-dev.46.g2a7d2a7",ge="https://hub.dev.codepipe.dev";var he=3,il=3;function wr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=il&&t<=he}var Se=".devpipe-context.yaml",_o=[{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",Se]}];function kr(t=1){return`# CodePipe Context Repo format version.
2
+ var ce="0.1.135",ge="https://hub.codepipe.dev";var he=3,cl=3;function kr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=cl&&t<=he}var ye=".codepipe-context.yaml",Kt=".devpipe-context.yaml",Oo=[{version:1,summary:"ADR section: adr/ scaffold (README, template, derived INDEX) + the format-version stamp itself",addedPaths:["adr/README.md","adr/0000-template.md","adr/INDEX.md",ye]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[ye]}];function br(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 Oo(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 No(t,e=_o){let r=[];for(let n of e)if(!(n.version<=t))for(let o of n.addedPaths)r.includes(o)||r.push(o);return r}function Uo(t,e=_o){return e.filter(r=>r.version>t)}function br(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Qe=/^[a-z][a-z0-9-]{1,30}$/,sl="-codepipe-ctx";function Ce(t){return`${t}${sl}`}var al=[{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 $r(t){for(let e of al){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Kt={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function dt(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}var Ze="x-bitbucket-api-token-auth";function xr(t){switch(t){case Kt.gitlab:return"oauth2";case Kt.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Lo=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Am}from"commander";import{homedir as Fo}from"node:os";import{mkdirSync as yl,readFileSync as wl,writeFileSync as kl,existsSync as vn}from"node:fs";import{dirname as Ko,join as Cr,resolve as bl}from"node:path";import{fileURLToPath as $l}from"node:url";import{existsSync as vr,readFileSync as Bo,readdirSync as ll,writeFileSync as ul}from"node:fs";import{dirname as pl,join as Oe}from"node:path";import{parse as dl}from"yaml";import{existsSync as Do,renameSync as cl}from"node:fs";function et(t,e,r=n=>console.error(n)){if(Do(e)||!Do(t))return!1;try{return cl(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var ye=".codepipe",xn=".devpipe";function fl(t=process.cwd()){let e=t;for(;;){if(vr(Oe(e,ye,"project.yaml")))return e;if(vr(Oe(e,xn,"project.yaml")))return et(Oe(e,xn),Oe(e,ye))&&gl(e),e;let r=pl(e);if(r===e)return null;e=r}}function ml(t){let e=Oe(t,ye);return vr(e)?e:Oe(t,xn)}function gl(t){let e=Oe(t,".gitignore");if(!vr(e))return;let r=Bo(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
6
- `);n!==r&&ul(e,n)}function tt(t=process.cwd()){let e=fl(t);if(!e)return null;let r=ml(e),n=hl(Bo(Oe(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Mo(t,e,r){return ll(t).filter(o=>o!==".DS_Store").length===0?!0:e?r.some(o=>o.host===e.host&&o.owner===e.owner&&o.repoName===e.repoName):!1}function Sr(t,e=process.cwd()){try{let r=tt(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function hl(t){let e=dl(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){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:n,repos:i}}function Go(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 Ho=bl(Ko($l(import.meta.url)),"..");function Wo(t){let e=Cr(Ho,".env");if(vn(e)&&process.loadEnvFile(e),t){let r=Cr(Ho,"profiles",t,".env");vn(r)&&process.loadEnvFile(r)}}function ft(t){let e=L("CONFIG");return e||(t?Cr(Fo(),".codepipe","profiles",t,"config.json"):Cr(Fo(),".codepipe","config.json"))}function Te(t){let e=ft(t);if(!vn(e))return null;let r=wl(e,"utf-8");return JSON.parse(r)}function rt(t,e){let r=ft(e);yl(Ko(r),{recursive:!0}),kl(r,JSON.stringify(t,null,2)+`
7
- `,{mode:384})}function Tr(t){if(t)return{cfg:Ne(t),profile:t};let e;try{e=tt()?.spec.projectId||void 0}catch{}if(e){let r=Te(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:Ne(void 0),profile:void 0}}function Ne(t){let e=Te(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${ft(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as Yo}from"node:os";import{join as qo}from"node:path";function Vo(){et(qo(Yo(),".devpipe"),qo(Yo(),".codepipe"))}import{homedir as Jo}from"node:os";import{existsSync as zo,mkdirSync as Xo,readFileSync as Qo,writeFileSync as Zo}from"node:fs";import{dirname as ei,join as ti}from"node:path";function Rr(t,e,r){let n=B(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,W(n),"pinned")}function ri(t,e){let r=B(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],W(r),!0):!1}function nt(t){return ti(Jo(),".codepipe","secrets",`${t}.json`)}function B(t){let e=nt(t);return zo(e)?JSON.parse(Qo(e,"utf-8")):null}function W(t){let e=nt(t.projectId);Xo(ei(e),{recursive:!0}),Zo(e,JSON.stringify(t,null,2)+`
8
- `,{mode:384})}function Ir(){return ti(Jo(),".codepipe","shared.json")}function Sn(){let t=Ir();return zo(t)?JSON.parse(Qo(t,"utf-8")):null}function ni(t){let e=Ir();Xo(ei(e),{recursive:!0}),Zo(e,JSON.stringify(t,null,2)+`
9
- `,{mode:384})}function mt(t){let e=B(t)?.claude?.oauthToken;return e||Sn()?.claude?.oauthToken}function Wt(t){let e=(r,n)=>{n&&!process.env[r]&&(process.env[r]=n)};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 gt(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function oi(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=Te(e);r&&!t.force&&(console.error(`already configured at ${ft(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");rt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...B(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};W(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${ft(e)}`)}import{homedir as Qn}from"node:os";import{join as tr}from"node:path";import{appendFileSync as xl,existsSync as ii,mkdirSync as vl,renameSync as si,statSync as Sl,unlinkSync as Cl}from"node:fs";import{Writable as Tl}from"node:stream";import{join as Rl}from"node:path";var ai={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},ht=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&vl(e.dir,{recursive:!0}),this.currentPath=Rl(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 No(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 Uo(t,e=Oo){let r=[];for(let n of e)if(!(n.version<=t))for(let o of n.addedPaths)r.includes(o)||r.push(o);return r}function Lo(t,e=Oo){return e.filter(r=>r.version>t)}function $r(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Qe=/^[a-z][a-z0-9-]{1,30}$/,ll="-codepipe-ctx";function Ce(t){return`${t}${ll}`}var ul=[{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 xr(t){for(let e of ul){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Wt={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function dt(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}var Ze="x-bitbucket-api-token-auth";function vr(t){switch(t){case Wt.gitlab:return"oauth2";case Wt.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Do=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as _m}from"commander";import{homedir as Ho}from"node:os";import{mkdirSync as bl,readFileSync as $l,writeFileSync as xl,existsSync as Cn}from"node:fs";import{dirname as Wo,join as Tr,resolve as vl}from"node:path";import{fileURLToPath as Sl}from"node:url";import{existsSync as Sr,readFileSync as Mo,readdirSync as dl,writeFileSync as fl}from"node:fs";import{dirname as ml,join as Oe}from"node:path";import{parse as gl}from"yaml";import{existsSync as Bo,renameSync as pl}from"node:fs";function et(t,e,r=n=>console.error(n)){if(Bo(e)||!Bo(t))return!1;try{return pl(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var we=".codepipe",Sn=".devpipe";function hl(t=process.cwd()){let e=t;for(;;){if(Sr(Oe(e,we,"project.yaml")))return e;if(Sr(Oe(e,Sn,"project.yaml")))return et(Oe(e,Sn),Oe(e,we))&&wl(e),e;let r=ml(e);if(r===e)return null;e=r}}function yl(t){let e=Oe(t,we);return Sr(e)?e:Oe(t,Sn)}function wl(t){let e=Oe(t,".gitignore");if(!Sr(e))return;let r=Mo(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
6
+ `);n!==r&&fl(e,n)}function tt(t=process.cwd()){let e=hl(t);if(!e)return null;let r=yl(e),n=kl(Mo(Oe(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Go(t,e,r){return dl(t).filter(o=>o!==".DS_Store").length===0?!0:e?r.some(o=>o.host===e.host&&o.owner===e.owner&&o.repoName===e.repoName):!1}function Cr(t,e=process.cwd()){try{let r=tt(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function kl(t){let e=gl(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){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:n,repos:i}}function Fo(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 Ko=vl(Wo(Sl(import.meta.url)),"..");function Yo(t){let e=Tr(Ko,".env");if(Cn(e)&&process.loadEnvFile(e),t){let r=Tr(Ko,"profiles",t,".env");Cn(r)&&process.loadEnvFile(r)}}function ft(t){let e=L("CONFIG");return e||(t?Tr(Ho(),".codepipe","profiles",t,"config.json"):Tr(Ho(),".codepipe","config.json"))}function Te(t){let e=ft(t);if(!Cn(e))return null;let r=$l(e,"utf-8");return JSON.parse(r)}function rt(t,e){let r=ft(e);bl(Wo(r),{recursive:!0}),xl(r,JSON.stringify(t,null,2)+`
7
+ `,{mode:384})}function Rr(t){if(t)return{cfg:Ne(t),profile:t};let e;try{e=tt()?.spec.projectId||void 0}catch{}if(e){let r=Te(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:Ne(void 0),profile:void 0}}function Ne(t){let e=Te(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${ft(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as qo}from"node:os";import{join as Vo}from"node:path";function Jo(){et(Vo(qo(),".devpipe"),Vo(qo(),".codepipe"))}import{homedir as zo}from"node:os";import{existsSync as Xo,mkdirSync as Qo,readFileSync as Zo,writeFileSync as ei}from"node:fs";import{dirname as ti,join as ri}from"node:path";function Ir(t,e,r){let n=B(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,W(n),"pinned")}function ni(t,e){let r=B(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],W(r),!0):!1}function nt(t){return ri(zo(),".codepipe","secrets",`${t}.json`)}function B(t){let e=nt(t);return Xo(e)?JSON.parse(Zo(e,"utf-8")):null}function W(t){let e=nt(t.projectId);Qo(ti(e),{recursive:!0}),ei(e,JSON.stringify(t,null,2)+`
8
+ `,{mode:384})}function Pr(){return ri(zo(),".codepipe","shared.json")}function Tn(){let t=Pr();return Xo(t)?JSON.parse(Zo(t,"utf-8")):null}function oi(t){let e=Pr();Qo(ti(e),{recursive:!0}),ei(e,JSON.stringify(t,null,2)+`
9
+ `,{mode:384})}function mt(t){let e=B(t)?.claude?.oauthToken;return e||Tn()?.claude?.oauthToken}function Yt(t){let e=(r,n)=>{n&&!process.env[r]&&(process.env[r]=n)};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 gt(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function ii(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=Te(e);r&&!t.force&&(console.error(`already configured at ${ft(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");rt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...B(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};W(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${ft(e)}`)}import{homedir as Zn}from"node:os";import{join as rr}from"node:path";import{appendFileSync as Cl,existsSync as si,mkdirSync as Tl,renameSync as ai,statSync as Rl,unlinkSync as Il}from"node:fs";import{Writable as Pl}from"node:stream";import{join as El}from"node:path";var ci={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},ht=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Tl(e.dir,{recursive:!0}),this.currentPath=El(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
- `;xl(this.currentPath,r,"utf-8")}asWritable(){return new Tl({write:(e,r,n)=>{try{let o=typeof e=="string"?e:e.toString("utf-8");for(let i of o.split(/\r?\n/))i&&this.writeLine(i);n()}catch(o){n(o)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!ii(this.currentPath)||Sl(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;ii(n)&&(r>=this.cfg.maxFiles?Cl(n):si(n,`${this.currentPath}.${r+1}`))}si(this.currentPath,`${this.currentPath}.1`)}}};function Pr(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Il(process.env[`${t}_MAX_BYTES`]??String(ai.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):ai.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Il(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),n=(e[2]??"").toLowerCase();return n==="g"?r*1024**3:n==="m"?r*1024**2:n==="k"?r*1024:r}function jr(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...i)=>{n(...i);try{t.writeLine(Pl(o,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 Pl(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:jl(o)).join(" ");return`${r} ${t} ${n}`}function jl(t){try{return JSON.stringify(t)}catch{return String(t)}}import{join as Ep}from"node:path";import"ws";import{createHash as El}from"node:crypto";import{existsSync as Al,readFileSync as _l}from"node:fs";import{homedir as Ol,hostname as Cn}from"node:os";import{join as Nl}from"node:path";function ci(t){return El("sha256").update(t).digest("hex").slice(0,12)}function Ul(){let t=L("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Nl(Ol(),".claude","credentials.json");if(!Al(e))return;let r=JSON.parse(_l(e,"utf-8")),n=[r.email,r.account?.email,r.user?.email];for(let o of n)if(typeof o=="string"&&o.includes("@"))return o.trim().toLowerCase()}catch{}}function li(t){let e=Ul(),r=L("ACCOUNT_ID")?.trim(),n=L("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=mt(t);return o?{accountId:`acct-${ci(o)}`,label:n||Cn(),...e?{email:e}:{}}:{accountId:`acct-${ci(`host:${Cn()}`)}`,label:n||Cn(),...e?{email:e}:{}}}import{existsSync as Ll}from"node:fs";import{join as Dl}from"node:path";import{simpleGit as Bl}from"simple-git";async function ui(t,e){if(!Ll(Dl(t,".git")))return{status:"skipped"};let r=Bl(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Ml(o)}`}}let n=await r.status();if(!n.isClean())return{status:"warn",reason:"uncommitted changes \u2014 working copy left as-is"};if(n.current!==e)return{status:"warn",reason:`on '${n.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 Ml(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Tn,readFileSync as pi,readdirSync as Gl,watch as Fl}from"node:fs";import{join as Rn}from"node:path";var Er=class{constructor(e,r,n,o,i=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;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(Tn(this.contextDir))try{this.watcher=Fl(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=Rn(this.contextDir,e);if(!Tn(r))return null;try{return pi(r,"utf-8")}catch{return null}}readPrompts(){let e=Rn(this.contextDir,"prompts"),r={};if(!Tn(e))return r;let n;try{n=Gl(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=pi(Rn(e,o),"utf-8")}catch{}}return r}};import{existsSync as wi,readFileSync as ki,readdirSync as Ql}from"node:fs";import{join as bi}from"node:path";import{simpleGit as Zl}from"simple-git";import{existsSync as Yl,mkdirSync as ql,writeFileSync as mi}from"node:fs";import{dirname as Vl,isAbsolute as Jl,join as hi,normalize as An}from"node:path";import{simpleGit as yi}from"simple-git";import{existsSync as Ue,mkdirSync as di,readFileSync as In,writeFileSync as yt}from"node:fs";import{homedir as Hl}from"node:os";import{join as we}from"node:path";import{simpleGit as Kl}from"simple-git";var wt=["project.yaml","regimen.yaml"];function Yt(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=we(t,o);Ue(s)||(yt(s,i),r.push(o))}return r}function ot(t,e,r){let n=we(Hl(),".codepipe","profiles",t,"context-config");return di(n,{recursive:!0}),yt(we(n,"project.yaml"),e.projectYaml),yt(we(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Ar(t,e,r){if(Ue(e))for(let n of wt){let o=we(e,n),i=we(t,n);if(!(!Ue(o)||Ue(i)))try{yt(i,In(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${n}: ${s instanceof Error?s.message:String(s)}`)}}}var Wl=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function kt(t){let e=we(t,".gitignore"),r=Ue(e)?In(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(wt.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
11
+ `;Cl(this.currentPath,r,"utf-8")}asWritable(){return new Pl({write:(e,r,n)=>{try{let o=typeof e=="string"?e:e.toString("utf-8");for(let i of o.split(/\r?\n/))i&&this.writeLine(i);n()}catch(o){n(o)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!si(this.currentPath)||Rl(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;si(n)&&(r>=this.cfg.maxFiles?Il(n):ai(n,`${this.currentPath}.${r+1}`))}ai(this.currentPath,`${this.currentPath}.1`)}}};function Er(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=jl(process.env[`${t}_MAX_BYTES`]??String(ci.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):ci.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function jl(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),n=(e[2]??"").toLowerCase();return n==="g"?r*1024**3:n==="m"?r*1024**2:n==="k"?r*1024:r}function jr(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...i)=>{n(...i);try{t.writeLine(Al(o,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 Al(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:_l(o)).join(" ");return`${r} ${t} ${n}`}function _l(t){try{return JSON.stringify(t)}catch{return String(t)}}import{join as Ap}from"node:path";import"ws";import{createHash as Ol}from"node:crypto";import{existsSync as Nl,readFileSync as Ul}from"node:fs";import{homedir as Ll,hostname as Rn}from"node:os";import{join as Dl}from"node:path";function li(t){return Ol("sha256").update(t).digest("hex").slice(0,12)}function Bl(){let t=L("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Dl(Ll(),".claude","credentials.json");if(!Nl(e))return;let r=JSON.parse(Ul(e,"utf-8")),n=[r.email,r.account?.email,r.user?.email];for(let o of n)if(typeof o=="string"&&o.includes("@"))return o.trim().toLowerCase()}catch{}}function ui(t){let e=Bl(),r=L("ACCOUNT_ID")?.trim(),n=L("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=mt(t);return o?{accountId:`acct-${li(o)}`,label:n||Rn(),...e?{email:e}:{}}:{accountId:`acct-${li(`host:${Rn()}`)}`,label:n||Rn(),...e?{email:e}:{}}}import{existsSync as Ml}from"node:fs";import{join as Gl}from"node:path";import{simpleGit as Fl}from"simple-git";async function pi(t,e){if(!Ml(Gl(t,".git")))return{status:"skipped"};let r=Fl(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Hl(o)}`}}let n=await r.status();if(!n.isClean())return{status:"warn",reason:"uncommitted changes \u2014 working copy left as-is"};if(n.current!==e)return{status:"warn",reason:`on '${n.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 Hl(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as In,readFileSync as di,readdirSync as Kl,watch as Wl}from"node:fs";import{join as Pn}from"node:path";var Ar=class{constructor(e,r,n,o,i=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;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(In(this.contextDir))try{this.watcher=Wl(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=Pn(this.contextDir,e);if(!In(r))return null;try{return di(r,"utf-8")}catch{return null}}readPrompts(){let e=Pn(this.contextDir,"prompts"),r={};if(!In(e))return r;let n;try{n=Kl(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=di(Pn(e,o),"utf-8")}catch{}}return r}};import{existsSync as ki,readFileSync as bi,readdirSync as tu}from"node:fs";import{join as $i}from"node:path";import{simpleGit as ru}from"simple-git";import{existsSync as Jl,mkdirSync as zl,writeFileSync as gi}from"node:fs";import{dirname as Xl,isAbsolute as Ql,join as yi,normalize as On}from"node:path";import{simpleGit as wi}from"simple-git";import{existsSync as Ue,mkdirSync as fi,readFileSync as En,writeFileSync as yt}from"node:fs";import{homedir as Yl}from"node:os";import{join as ke}from"node:path";import{simpleGit as ql}from"simple-git";var wt=["project.yaml","regimen.yaml"];function qt(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=ke(t,o);Ue(s)||(yt(s,i),r.push(o))}return r}function ot(t,e,r){let n=ke(Yl(),".codepipe","profiles",t,"context-config");return fi(n,{recursive:!0}),yt(ke(n,"project.yaml"),e.projectYaml),yt(ke(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function _r(t,e,r){if(Ue(e))for(let n of wt){let o=ke(e,n),i=ke(t,n);if(!(!Ue(o)||Ue(i)))try{yt(i,En(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${n}: ${s instanceof Error?s.message:String(s)}`)}}}var Vl=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function kt(t){let e=ke(t,".gitignore"),r=Ue(e)?En(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(wt.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
12
12
  `)?"":`
13
- `;return yt(e,r+i+Wl.join(`
13
+ `;return yt(e,r+i+Vl.join(`
14
14
  `)+`
15
- `),!0}async function fi(t,e){try{if(!Ue(we(t,".git")))return;let r=Kl(t),n=(await r.raw(["ls-files","--",...wt])).split(`
16
- `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;kt(t),await r.raw(["rm","--cached","--quiet","--",...n]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await En(t),e.info(`[config] migrated ${n.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 Pn(t){let e=new Map;for(let r of wt){let n=we(t,r);Ue(n)&&e.set(r,In(n))}return e}function jn(t,e){di(t,{recursive:!0});for(let[r,n]of e){let o=we(t,r);Ue(o)||yt(o,n)}}var gi=3,zl=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function bt(t,e,r){if(!Yl(hi(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Le(t,i.path);ql(Vl(s),{recursive:!0}),i.encoding==="base64"?mi(s,Buffer.from(i.content,"base64")):mi(s,i.content)}let n=yi(t);await n.add(["-A","--","."]),await n.raw(["reset","-q","--",...wt]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await En(t))}async function En(t){let e=yi(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=gi;n++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let i=await Xl(e);if(i.length>0&&i.every(s=>zl.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 ${gi} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Xl(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
- `).map(r=>r.trim()).filter(Boolean)}function Le(t,e){if(Jl(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=An(hi(t,e)),n=An(t+"/");if(r!==An(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var eu=/^(\d{4})-(.+)\.md$/,tu="0000-template.md";function ru(t){let e=t.split(`
18
- `),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=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:n,status:o("Status"),date:o("Date")}}function nu(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
19
- `),a=s.findIndex(C=>C.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 C=g;C<s.length;C++){let R=(s[C]??"").trim();if(R===""){g=C+1;continue}let k=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(R);if(!k)break;let b=(k[1]??"").trim().toLowerCase(),_=(k[2]??"").trim(),O=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(R);O&&(p=parseInt(O[1]??"",10)),b==="tasks"&&(f=_),l.has(b)||u.push(R),g=C+1}let d=f?f.includes(n)?f:`${f}, ${n}`:n,y=s.slice(g).join(`
20
- `).replace(/^\n+/,""),S=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${d}`,...u,"",y].join(`
21
- `);return{content:S.endsWith(`
22
- `)?S:S+`
23
- `,supersedes:p}}function ou(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
24
-
25
- - **Status:** superseded by ADR-${r}`):n}function iu(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((n,o)=>n.num-o.num)){let n=String(r.num).padStart(4,"0"),o=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${n} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${o}`)}return e.join(`
15
+ `),!0}async function mi(t,e){try{if(!Ue(ke(t,".git")))return;let r=ql(t),n=(await r.raw(["ls-files","--",...wt])).split(`
16
+ `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;kt(t),await r.raw(["rm","--cached","--quiet","--",...n]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await _n(t),e.info(`[config] migrated ${n.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 jn(t){let e=new Map;for(let r of wt){let n=ke(t,r);Ue(n)&&e.set(r,En(n))}return e}function An(t,e){fi(t,{recursive:!0});for(let[r,n]of e){let o=ke(t,r);Ue(o)||yt(o,n)}}var hi=3,Zl=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function bt(t,e,r){if(!Jl(yi(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Le(t,i.path);zl(Xl(s),{recursive:!0}),i.encoding==="base64"?gi(s,Buffer.from(i.content,"base64")):gi(s,i.content)}let n=wi(t);await n.add(["-A","--","."]),await n.raw(["reset","-q","--",...wt]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await _n(t))}async function _n(t){let e=wi(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=hi;n++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let i=await eu(e);if(i.length>0&&i.every(s=>Zl.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 ${hi} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function eu(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
+ `).map(r=>r.trim()).filter(Boolean)}function Le(t,e){if(Ql(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=On(yi(t,e)),n=On(t+"/");if(r!==On(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var nu=/^(\d{4})-(.+)\.md$/,ou="0000-template.md";function iu(t){let e=t.split(`
18
+ `),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=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:n,status:o("Status"),date:o("Date")}}function su(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
19
+ `),a=s.findIndex(S=>S.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 S=g;S<s.length;S++){let R=(s[S]??"").trim();if(R===""){g=S+1;continue}let k=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(R);if(!k)break;let b=(k[1]??"").trim().toLowerCase(),_=(k[2]??"").trim(),O=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(R);O&&(p=parseInt(O[1]??"",10)),b==="tasks"&&(f=_),l.has(b)||u.push(R),g=S+1}let d=f?f.includes(n)?f:`${f}, ${n}`:n,h=s.slice(g).join(`
20
+ `).replace(/^\n+/,""),C=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${d}`,...u,"",h].join(`
21
+ `);return{content:C.endsWith(`
22
+ `)?C:C+`
23
+ `,supersedes:p}}function au(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
24
+
25
+ - **Status:** superseded by ADR-${r}`):n}function cu(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((n,o)=>n.num-o.num)){let n=String(r.num).padStart(4,"0"),o=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${n} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${o}`)}return e.join(`
26
26
  `)+`
27
- `}async function $i(t,e,r,n=new Date().toISOString().slice(0,10)){try{await Zl(t).pull(void 0,void 0,["--rebase"])}catch{}let o=[],i=[];for(let d of r){let y=Le(t,`tasks/${e}/adr/DRAFT-${d}.md`);if(!wi(y)){i.push(d);continue}o.push({slug:d,content:ki(y,"utf-8")})}let s=bi(t,"adr"),a=new Map;if(wi(s))for(let d of Ql(s)){let y=eu.exec(d);!y||d===tu||a.set(d,{num:parseInt(y[1]??"",10),slug:y[2]??"",content:ki(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 o){if([...a.entries()].find(([,b])=>b.slug===d.slug&&b.content.includes(e))){f.push(d.slug);continue}let S=c++,C=`${String(S).padStart(4,"0")}-${d.slug}.md`,{content:R,supersedes:k}=nu(d.content,S,d.slug,e,n);if(l.set(C,R),a.set(C,{num:S,slug:d.slug,content:R}),u.push(`adr/${C}`),k!==null){let b=[...a.keys()].find(_=>_.startsWith(`${String(k).padStart(4,"0")}-`));if(b&&b!==C){let _=ou(l.get(b)??a.get(b).content,S);l.set(b,_),a.set(b,{...a.get(b),content:_})}}}if(u.length===0)return{promoted:u,skipped:f,missing:i};let p=[...a.entries()].map(([d,y])=>({num:y.num,file:d,header:ru(y.content)}));l.set("INDEX.md",iu(p));let g=[...l.entries()].map(([d,y])=>({path:`adr/${d}`,content:y}));return await bt(t,g,`adr(${e}): promote ${o.map(d=>d.slug).join(", ")}`),{promoted:u,skipped:f,missing:i}}import{existsSync as xi,readFileSync as au}from"node:fs";import{join as vi}from"node:path";function cu(t){let e=vi(t,Se);if(!xi(e))return 0;try{return Oo(au(e,"utf-8"))}catch{return 0}}function lu(t,e,r,n=1){let o=e<n,i=o?No(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function _r(t,e){return lu(e,cu(t),r=>xi(vi(t,r)))}import{existsSync as Su,mkdirSync as Cu,mkdtempSync as Tu,rmSync as Ru,writeFileSync as Ri}from"node:fs";import{tmpdir as Iu}from"node:os";import{dirname as Pu,join as Ln}from"node:path";import{simpleGit as Dn}from"simple-git";var it=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function Si(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
28
- `+t.slice(t.length-e)}async function De(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=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(n.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let i=(await n.json()).login??"ok",s=n.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 Or(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o;try{o=await fetch(n,{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(o.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(o.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!o.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${o.status} ${o.statusText}`);if((await o.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function Be(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o;try{o=await fetch(n,{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(o.ok)return t;if(o.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await uu(o);throw o.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):o.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):o.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${o.status} ${o.statusText}${i}`)}async function uu(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Me(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(n){throw new Error(`cannot reach gitlab.com (${n instanceof Error?n.message:String(n)})`)}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 Ti(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 n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}var _n=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 n=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(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new it(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.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,n,o){let i=n==="squash"?"squash":n==="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:o})});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,n){if(n&&n.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:n}})});if(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}let o=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(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},On=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=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(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=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(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new it(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.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 n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),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 n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});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(`${o}/actions/runs/${f.id}/jobs?per_page=50`,{headers:n});if(!p.ok)continue;let g=(await p.json()).jobs??[];for(let d of g.filter(y=>y.conclusion==="failure")){let y=await fetch(`${o}/actions/jobs/${d.id}/logs`,{headers:n});if(!y.ok)continue;let S=await y.text();u.push(`### CI job: ${d.name}
27
+ `}async function xi(t,e,r,n=new Date().toISOString().slice(0,10)){try{await ru(t).pull(void 0,void 0,["--rebase"])}catch{}let o=[],i=[];for(let d of r){let h=Le(t,`tasks/${e}/adr/DRAFT-${d}.md`);if(!ki(h)){i.push(d);continue}o.push({slug:d,content:bi(h,"utf-8")})}let s=$i(t,"adr"),a=new Map;if(ki(s))for(let d of tu(s)){let h=nu.exec(d);!h||d===ou||a.set(d,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:bi($i(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 o){if([...a.entries()].find(([,b])=>b.slug===d.slug&&b.content.includes(e))){f.push(d.slug);continue}let C=c++,S=`${String(C).padStart(4,"0")}-${d.slug}.md`,{content:R,supersedes:k}=su(d.content,C,d.slug,e,n);if(l.set(S,R),a.set(S,{num:C,slug:d.slug,content:R}),u.push(`adr/${S}`),k!==null){let b=[...a.keys()].find(_=>_.startsWith(`${String(k).padStart(4,"0")}-`));if(b&&b!==S){let _=au(l.get(b)??a.get(b).content,C);l.set(b,_),a.set(b,{...a.get(b),content:_})}}}if(u.length===0)return{promoted:u,skipped:f,missing:i};let p=[...a.entries()].map(([d,h])=>({num:h.num,file:d,header:iu(h.content)}));l.set("INDEX.md",cu(p));let g=[...l.entries()].map(([d,h])=>({path:`adr/${d}`,content:h}));return await bt(t,g,`adr(${e}): promote ${o.map(d=>d.slug).join(", ")}`),{promoted:u,skipped:f,missing:i}}import{existsSync as vi,readFileSync as uu}from"node:fs";import{join as Si}from"node:path";function pu(t){for(let e of[ye,Kt]){let r=Si(t,e);if(vi(r))try{return No(uu(r,"utf-8"))}catch{return 0}}return 0}function du(t,e,r,n=2){let o=e<n,i=o?Uo(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Or(t,e){return du(e,pu(t),r=>vi(Si(t,r)))}import{existsSync as Ii,mkdirSync as Ru,mkdtempSync as Iu,rmSync as Pi,writeFileSync as Ei}from"node:fs";import{tmpdir as Pu}from"node:os";import{dirname as Eu,join as Ur}from"node:path";import{simpleGit as Bn}from"simple-git";var it=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function Ci(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
28
+ `+t.slice(t.length-e)}async function De(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=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(n.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let i=(await n.json()).login??"ok",s=n.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 Nr(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o;try{o=await fetch(n,{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(o.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(o.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!o.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${o.status} ${o.statusText}`);if((await o.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function Be(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o;try{o=await fetch(n,{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(o.ok)return t;if(o.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await fu(o);throw o.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):o.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):o.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${o.status} ${o.statusText}${i}`)}async function fu(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Me(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(n){throw new Error(`cannot reach gitlab.com (${n instanceof Error?n.message:String(n)})`)}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 Ri(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 n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}var Nn=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 n=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(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new it(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.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,n,o){let i=n==="squash"?"squash":n==="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:o})});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,n){if(n&&n.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:n}})});if(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}let o=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(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Un=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=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(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=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(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new it(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.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 n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),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 n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});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(`${o}/actions/runs/${f.id}/jobs?per_page=50`,{headers:n});if(!p.ok)continue;let g=(await p.json()).jobs??[];for(let d of g.filter(h=>h.conclusion==="failure")){let h=await fetch(`${o}/actions/jobs/${d.id}/logs`,{headers:n});if(!h.ok)continue;let C=await h.text();u.push(`### CI job: ${d.name}
29
29
 
30
- ${Si(S,8e3)}`)}}return u.length===0?void 0:Si(u.join(`
30
+ ${Ci(C,8e3)}`)}}return u.length===0?void 0:Ci(u.join(`
31
31
 
32
- `),16e3)}catch{return}}async mergePR(e,r,n,o){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:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){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,n){if(n&&n.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:n})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let o=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(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Nn=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 n=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(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new it(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.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=pu(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,n,o){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o})});if(!i.ok)throw new Error(`gitlab merge MR !${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);return s?.merge_commit_sha?{mergedSha:s.merge_commit_sha}:{}}async closePR(e,r,n){if(n&&n.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:n})});if(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}let o=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(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};function pu(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 Un=class{name="mock";async createPullRequest(e,r){let n=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${n}`,number:n}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){throw new Error(Ci(e,r,"merge"))}async closePR(e,r,n){throw new Error(Ci(e,r,"close"))}};function Ci(t,e,r){let n=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 ${n}`}function Re(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new On(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new _n(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Nn(e)}return new Un}function $t(t,e,r,n){return[{path:"README.md",content:$u(t,e)},{path:".gitignore",content:hu()},{path:"CLAUDE.md",content:wu(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:yu()},{path:"knowledge/README.md",content:ku()},{path:"knowledge/build.yaml",content:bu()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:gu()},{path:"adr/README.md",content:du()},{path:"adr/0000-template.md",content:fu()},{path:"adr/INDEX.md",content:mu()},{path:Se,content:kr()}]}function du(){return`# ADR \u2014 architecture decision records
32
+ `),16e3)}catch{return}}async mergePR(e,r,n,o){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:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){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,n){if(n&&n.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:n})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let o=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(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Ln=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 n=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(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new it(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.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=mu(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,n,o){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o})});if(!i.ok)throw new Error(`gitlab merge MR !${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);return s?.merge_commit_sha?{mergedSha:s.merge_commit_sha}:{}}async closePR(e,r,n){if(n&&n.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:n})});if(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}let o=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(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};function mu(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 Dn=class{name="mock";async createPullRequest(e,r){let n=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${n}`,number:n}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){throw new Error(Ti(e,r,"merge"))}async closePR(e,r,n){throw new Error(Ti(e,r,"close"))}};function Ti(t,e,r){let n=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 ${n}`}function Re(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Un(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Nn(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Ln(e)}return new Dn}function $t(t,e,r,n){return[{path:"README.md",content:Su(t,e)},{path:".gitignore",content:ku()},{path:"CLAUDE.md",content:$u(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:bu()},{path:"knowledge/README.md",content:xu()},{path:"knowledge/build.yaml",content:vu()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:wu()},{path:"adr/README.md",content:gu()},{path:"adr/0000-template.md",content:hu()},{path:"adr/INDEX.md",content:yu()},{path:ye,content:br()}]}function gu(){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 fu(){return`# ADR-NNNN: <title>
60
+ `}function hu(){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 mu(){return`# ADR index
82
+ `}function yu(){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 gu(){return`# Audit
87
+ `}function wu(){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 ke(t,e,r,n){return{projectYaml:xu(t,r,n),regimenYaml:vu(t.automationLevel,e)}}function hu(){return`# codepipe project config is local to each member's workspace
96
+ `}function be(t,e,r,n){return{projectYaml:Cu(t,r,n),regimenYaml:Tu(t.automationLevel,e)}}function ku(){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 yu(){return`# Index prompt
103
+ `}function bu(){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 wu(t){return`# Project context for the CodePipe agent
160
+ `}function $u(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 ku(){return`# Knowledge
188
+ `}function xu(){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 bu(){return`# BUILD phase config. Discovered & maintained by the agent.
205
+ `}function vu(){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 $u(t,e){return`# ${e.name}
221
+ `}function Su(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 xu(t,e,r){let n=e?`
247
+ `}function Cu(t,e,r){let n=e?`
248
248
  tracker_url: ${e}`:`
249
249
  # tracker_url: https://your.youtrack.cloud`,o=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 vu(t,e){let r=t==="full",n=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
313
+ `}function Tu(t,e){let r=t==="full",n=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
314
314
  automation:
315
315
  level: ${t}
316
316
 
@@ -425,26 +425,26 @@ 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 ju(t){return`codepipe/context-migration-v${t}`}function Eu(t){let e=Uo(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 \`${Se}\` stamp. Hand-edited files are never touched.`,"","## Format changes",""];for(let n of e){r.push(`- **v${n.version}** \u2014 ${n.summary}`);for(let o of n.addedPaths)r.push(` - \`${o}\``)}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 Ii(t,e,r,n){let o=Dn(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=_r(t,e);if(!i.outdated)return i;let s=ju(i.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await Au(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.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=Re(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.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:Eu(i)});return n.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function Au(t,e,r,n,o,i,s){let a=Dn(t),c=Tu(Ln(Iu(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map($t(l,u).map(d=>[d.path,d.content])),p=0;for(let d of n.missingPaths){if(d===Se)continue;let y=f.get(d);if(y==null){s.warn(`[ctx] migration: no template for ${d} \u2014 skipped`);continue}let S=Ln(c,d);Su(S)||(Cu(Pu(S),{recursive:!0}),Ri(S,y),p++)}Ri(Ln(c,Se),kr(n.currentVersion)),p++;let g=Dn(c);await g.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await g.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await g.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${p} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Ru(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{createCipheriv as _u,createDecipheriv as Ou,createHash as Nu,createPrivateKey as Uu,createPublicKey as Bn,diffieHellman as Pi,generateKeyPairSync as ji,hkdfSync as Ei,randomBytes as Lu}from"node:crypto";var Ai=Buffer.from("devpipe-sealedbox-v1","utf-8");function Nr(){let{publicKey:t,privateKey:e}=ji("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function be(t){let e=Buffer.from(t,"base64");return(Nu("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function xt(t,e){let r=Bn({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=ji("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Pi({privateKey:o,publicKey:r}),c=Buffer.from(Ei("sha256",a,Buffer.concat([i,s]),Ai,32)),l=Lu(12),u=_u("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 Ur(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 n=Uu({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Bn({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Bn(n).export({type:"spki",format:"der"}),a=Pi({privateKey:n,publicKey:o}),c=Buffer.from(Ei("sha256",a,Buffer.concat([i,s]),Ai,32)),l=Ou("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 Du(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 n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function _i(t,e,r,n){let o=Du(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.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&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.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(o),s=[];for(let a of t.sandboxes){let c=Rr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.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"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=xt(a.publicKey,i)}catch(u){n.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 Ui}from"node:crypto";import{readFileSync as Bu}from"node:fs";import Ge from"node:tls";var Li=typeof Ge.getCACertificates=="function"&&typeof Ge.setDefaultCACertificates=="function",Oi=!1,Ni=new Map,Di=t=>console.warn(t);function Mu(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Bi(t=Di){if(Oi)return;Oi=!0;let e=L("EXTRA_CA_FILE");if(!(!e||!Li))try{let r=Mu(Bu(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Ge.setDefaultCACertificates([...Ge.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 Mi(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 Gu(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
430
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Fu(t,e,r){return new Promise((n,o)=>{let i=Ge.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 Ui(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Mn(t,e,r){return new Promise(n=>{let o=Ge.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function Hu(t){try{let e=await fetch(t);return e.ok?new Ui(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Gi(t,e=443,r=Di){let n=`${t}:${e}`,o=Ni.get(n);if(o)return o;let i=Ku(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Ni.set(n,i),i}async function Ku(t,e,r){if(!Li)return!1;let n=8e3;if(await Mn(t,e,n))return!0;let o=await Fu(t,e,n),i=Ge.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Gu(o);if(!c)break;let l=await Hu(c);if(!l)break;if(s.push(l.toString()),Ge.setDefaultCACertificates([...i,...s]),await Mn(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return Mn(t,e,n)}function Ie(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function de(t,e,r){Bi();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,i={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,i)}catch(s){if(Mi(s)&&await Gi(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var Fi=t=>new Promise(e=>setTimeout(e,t));function Wu(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Yu(){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 Wi(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Yu(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await de(t,r,n)}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<o&&Wu(l.status,u)){await Fi(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Fi(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Fe(t){let e;try{e=await de(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}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 Yi(t){try{let e=await de(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var qt="Stage",Hi=new Map;async function qu(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Hi.get(o);if(i)return i;let s=await de(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===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return Hi.set(o,l.id),l.id}async function qi(t,e,r,n=qt){let o=await qu(t,e,r,n);await Wi(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function Vi(t,e,r){return await(await Wi(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Ki=new Map;async function Ji(t,e){let r=Ki.get(e);if(r)return r;let n=await de(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Ki.set(e,i.id),i.id}async function zi(t,e,r,n,o,i=qt){let s=await Ji(t,e),a=await de(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$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 Xi(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await de(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}var Qi="attachments(id,name,url,size,mimeType)",Vu="links(direction,linkType(name),issues(idReadable))",Zi=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Qi},${Vu}`,Ju=`id,text,created,author(login),${Qi}`;function es(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 ts(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function rs(t,e){let r=e.stageField??qt,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${Zi}&$top=200`,s=await de(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>is(c,r))}async function ns(t,e,r=qt){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Zi}`,o=await de(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return is(await o.json(),r)}async function os(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Ju}&$top=500`,o=await de(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.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=es(s.attachments);return c&&(a.attachments=c),a})}function zu(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function is(t,e=qt){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.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=es(t.attachments);a&&(s.attachments=a);let c=zu(t.links);return c&&(s.links=c),s}async function ss(t,e){let r=await Ji(t,e),n=await de(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o){if(s.$type!=="StateProjectCustomField"||!s.field?.name)continue;let a=(s.bundle?.values??[]).filter(c=>c.name&&c.archived!==!0).map(c=>c.name);i.push({name:s.field.name,values:a})}return i}function fe(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function as(t,e){let r=B(t),n=[],o=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Fe({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:fe(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:fe(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await De(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"github",ok:!1,detail:fe(c)}),o.push({kind:"github",present:!0,ok:!1,detail:fe(c),checkedAt:i()})}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Be(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"bitbucket",ok:!1,detail:fe(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:fe(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Me(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"gitlab",ok:!1,detail:fe(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:fe(c),checkedAt:i()})}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.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 Or(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(f){n.push({name:`repo:${u.name}`,ok:!1,detail:fe(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Or(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){n.push({name:"context-repo",ok:!1,detail:fe(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Or(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){o.push({kind:"contextWrite",present:!0,ok:!1,detail:fe(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=mt(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Gn(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Gn(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=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 n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function Vt(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Jt(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function zt(t,e=process.env){if(!t)return!1;let r=`https://${Ze}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Fn(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function cs(t,e=process.env){return Fn(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Vt(t,e),e)}function ls(t,e=process.env){return Fn(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Jt(t,e),e)}function us(t,e=process.env){return Fn(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Ze}:${encodeURIComponent(t)}@bitbucket.org/`,()=>zt(t,e),e)}function ps(t){let e=B(t);if(!e)return null;if(!e.sealKey){let r=Nr();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},W(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:be(e.sealKey.publicKey)}}async function ds(t,e,r,n){let o;try{o=JSON.parse(Ur(n,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=B(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await De(o.token);return i.github={token:o.token},vt(i,()=>{process.env.GH_TOKEN=o.token,cs(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Me(o.token);return i.gitlab={token:o.token},vt(i,()=>{process.env.GITLAB_TOKEN=o.token,ls(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Be(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},vt(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,us(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Fe({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},vt(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Gn(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},vt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},vt(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 vt(t,e){W(t),e()}import{existsSync as Xu,readFileSync as Qu,statSync as fs}from"node:fs";var ms=2*1024*1024;function Zu(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function gs(t,e){let r=Le(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!Xu(r)||!fs(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=fs(r);if(n>ms)throw new Error(`file too large: ${e} is ${n} bytes (limit ${ms})`);let o=Qu(r);return Zu(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{existsSync as ep,readFileSync as tp,writeFileSync as rp}from"node:fs";import{join as np}from"node:path";import{parseDocument as op}from"yaml";var hs=64;async function ys(t,e){if(!Number.isInteger(e)||e<1||e>hs)throw new Error(`maxJobs must be an integer in [1, ${hs}], got ${e}`);let r=np(t,"regimen.yaml");if(!ep(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let n=op(tp(r,"utf-8"));return n.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(n.setIn(["parallelism","max_jobs"],e),rp(r,n.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as Hn,readFileSync as Kn,writeFileSync as ip}from"node:fs";import{join as Lr}from"node:path";import{parseDocument as Wn}from"yaml";async function ws(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=Lr(t,"project.yaml");if(!Hn(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Wn(Kn(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=Lr(t,"regimen.yaml");if(!Hn(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Wn(Kn(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)ip(Lr(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Yn(t){if(!t)return"Stage";try{let e=Lr(t,"project.yaml");if(!Hn(e))return"Stage";let n=Wn(Kn(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var ks=t=>console.log(t);function bs(t){ks=t}function Xt(t,e="info"){ks(t,e)}import{homedir as sp}from"node:os";import{existsSync as ap,mkdirSync as cp}from"node:fs";import{join as qn}from"node:path";import{simpleGit as $s}from"simple-git";function Zt(t,e,r){let n=r??qn(sp(),".codepipe","repos");return qn(n,t,e)}async function Dr(t,e,r={}){let n=Zt(t,e.name,r.baseDir),o=r.cloneUrlOverride??lp(e);if(!ap(qn(n,".git"))){cp(n,{recursive:!0});let a=$s();Xt(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
431
- ${l.trim()}`)}}let i=$s(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
432
- ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Qt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var xs=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function Br(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&Xt(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await Qt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Qt(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([...xs,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function vs(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await Qt(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Qt(t,o)){let s=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}async function Ss(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:f}=r,p=await vs(t,i,()=>Br(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let g=`origin/${c}`;if(await Qt(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([...xs,"cherry-pick",p])}catch(C){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let R=C instanceof Error?C.message:String(C);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
433
- ${R.trim()}`)}}let y=(await t.revparse(["HEAD"])).trim(),S=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(S),await t.push([n,"--delete",o]).catch(()=>{}),{commit:y}}async function Cs(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await vs(t,i,()=>Br(t,{contextRepoCloneUrl:n,deliveryRef:o,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 Ts(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:i,deleteBranch:s}=r,a=`origin/${n}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):i==="rebase"?(await t.checkout(["-B",n,a]),await t.rebase([o]),await t.checkout(o),await t.merge(["--ff-only",n])):await t.merge(["--no-ff",a,"-m",`Merge branch '${n}'`]),await t.push(["origin",o]),s&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function lp(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 Mr=new Map;async function Vn(t,e){let n=(Mr.get(t)??Promise.resolve()).catch(()=>{}).then(e);Mr.set(t,n);try{return await n}finally{Mr.get(t)===n&&Mr.delete(t)}}async function Rs(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;Xt(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Vn(`${i}/${r.name}`,async()=>{let s=await Dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Zt(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 Z({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Vn(`${i}/${r.name}`,async()=>{let s=await Dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Zt(i,r.name,t.baseDir),{commit:c,pushed:l}=await Cs(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return Z({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return K("no repo spec");let i=Re(r),s=await i.createPullRequest(r,e);return Z({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return K("no repo spec");let i=Re(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return Z({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return K("no repo spec");let i=Re(r);return await i.closePR(r,e.prNumber,e.comment),Z({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Vn(`${i}/${r.name}`,async()=>{let s=await Dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Zt(i,r.name,t.baseDir),{mergedSha:c}=await Ts(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return Z({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return Z({stub:!0});case"tracker_status":{let i=Ie();return i?t.trackerIssueId?(await qi(i,t.trackerIssueId,e.newStatus,Yn(t.contextDir)),Z({issueId:t.trackerIssueId,newStatus:e.newStatus})):K("no tracker_issue_id provided"):K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=Ie();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return K("no tracker_issue_id provided");let s=await Vi(i,t.trackerIssueId,e.body);return Z({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ie();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return K("no projectKey in create_tracker_issue action");let{id:s,key:a}=await zi(i,e.projectKey,e.title,e.body,e.targetStatus,Yn(t.contextDir));return Z({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ie();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Xi(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return K(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return Z({applied:s})}case"set_parallelism":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await ys(t.contextDir,e.maxJobs);return Z({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await ws(t.contextDir,e);return Z({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),Z({reported:!0})):K("no context repo clone on this CLI");case"read_context_file":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=gs(t.contextDir,e.path);return Z({path:e.path,...i})}}}catch(i){return K(i instanceof Error?i.message:String(i))}}function Z(t){return{status:"done",result:t}}function K(t){return{status:"failed",error:t}}import{existsSync as Ms,readFileSync as Gs}from"node:fs";import{join as Fs}from"node:path";import{homedir as up}from"node:os";import{existsSync as pp,mkdirSync as dp,readFileSync as fp,writeFileSync as mp}from"node:fs";import{dirname as gp,join as hp}from"node:path";function Jn(){return L("FARM_PINS")??hp(up(),".codepipe","farm-pins.json")}function Is(){let t=Jn();if(!pp(t))return{};try{return JSON.parse(fp(t,"utf-8"))}catch{return{}}}function yp(t){let e=Jn();dp(gp(e),{recursive:!0}),mp(e,JSON.stringify(t,null,2)+`
434
- `,{mode:384})}function wp(t){return Is()[t]}function Gr(t,e){let r=Is();r[t]=e,yp(r)}function Fr(t,e){let r=be(e),n=wp(t);if(n&&n!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${Jn()}.`);return r}import kp from"ws";function Hr(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new kp(r)}var N=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};async function St(t,e,r){return He(t,e,"/projects",r)}async function Ps(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Kr(t,e,r,n){return He(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function js(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 N(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function Wr(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Es(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var er=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function As(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 n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new er(e)}if(!r.ok)throw new N(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function _s(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new N(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Os(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Ns(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new N(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Us(t,e,r,n){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Ls(t,e,r,n,o){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function Ds(t,e,r,n,o){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function Bs(t,e,r,n,o){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Yr(t,e,r,n){return He(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function zn(t,e,r,n){await He(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Q(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function He(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new N(o.status,s,a)}return s}async function Hs(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=be(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Fr(e.farmId,e.farmPublicKey);let s=B(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await Q(t.hubUrl,t.cliToken,t.projectId),c;if(r){let p=Fs(r,"project.yaml"),g=Fs(r,"regimen.yaml");Ms(p)&&Ms(g)?c={projectYaml:Gs(p,"utf-8"),regimenYaml:Gs(g,"utf-8")}:n.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=xt(e.farmPublicKey,JSON.stringify(l));Gr(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await Kr(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}:{}}:o(f.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}var qr=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}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 n=[];for(let s of r.prs){let a=Re(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof it){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 o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Re(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:n}),this.lastSig.set(e,o);let i=bp(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function bp(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 Ks,readFileSync as $p,readdirSync as xp}from"node:fs";function vp(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Rp(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Sp(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Tp(Cp(t,i,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function Ws(t,e,r){if(r.length===0)return;let n=vp(t,e,r),o=r.map(i=>i.issue.key);await bt(t,n,`sync(${o.join(", ")}): task data`)}function Sp(t,e,r){let n=new Date(t.updatedAt).toISOString(),o=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${n}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){o.push("## Attachments","");for(let i of r)o.push(`- [${i}](attachments/${encodeURI(i)})`);o.push("")}return o.join(`
435
- `)}function Cp(t,e,r){let n=new Map,o=Le(t,`tasks/${e}/comments.jsonl`);if(Ks(o))for(let i of $p(o,"utf-8").split(`
436
- `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.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=$r(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Tp(t){return t.map(e=>JSON.stringify(e)).join(`
428
+ `}function ju(t){return`codepipe/context-migration-v${t}`}function Au(t){let e=Lo(t.templateVersion),r=[`CodePipe context format migration: **v${t.templateVersion} \u2192 v${t.currentVersion}**.`,"","Additive only \u2014 this PR creates files your context is missing and updates",`the \`${ye}\` stamp (renamed from \`${Kt}\``,"when the legacy file is present). Hand-edited files are never touched.","","## Format changes",""];for(let n of e){r.push(`- **v${n.version}** \u2014 ${n.summary}`);for(let o of n.addedPaths)r.push(` - \`${o}\``)}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 ji(t,e,r,n){let o=Bn(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Or(t,e);if(!i.outdated)return i;let s=ju(i.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await _u(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.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=Re(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.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:Au(i)});return n.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function _u(t,e,r,n,o,i,s){let a=Bn(t),c=Iu(Ur(Pu(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map($t(l,u).map(h=>[h.path,h.content])),p=0;for(let h of n.missingPaths){if(h===ye)continue;let C=f.get(h);if(C==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let S=Ur(c,h);Ii(S)||(Ru(Eu(S),{recursive:!0}),Ei(S,C),p++)}Ei(Ur(c,ye),br(n.currentVersion)),p++;let g=Ur(c,Kt);Ii(g)&&(Pi(g,{force:!0}),p++);let d=Bn(c);await d.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await d.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await d.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${p} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Pi(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{createCipheriv as Ou,createDecipheriv as Nu,createHash as Uu,createPrivateKey as Lu,createPublicKey as Mn,diffieHellman as Ai,generateKeyPairSync as _i,hkdfSync as Oi,randomBytes as Du}from"node:crypto";var Ni=Buffer.from("devpipe-sealedbox-v1","utf-8");function Lr(){let{publicKey:t,privateKey:e}=_i("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function $e(t){let e=Buffer.from(t,"base64");return(Uu("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function xt(t,e){let r=Mn({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=_i("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Ai({privateKey:o,publicKey:r}),c=Buffer.from(Oi("sha256",a,Buffer.concat([i,s]),Ni,32)),l=Du(12),u=Ou("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 Dr(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 n=Lu({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Mn({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Mn(n).export({type:"spki",format:"der"}),a=Ai({privateKey:n,publicKey:o}),c=Buffer.from(Oi("sha256",a,Buffer.concat([i,s]),Ni,32)),l=Nu("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 Bu(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 n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function Ui(t,e,r,n){let o=Bu(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.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&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.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(o),s=[];for(let a of t.sandboxes){let c=Ir(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.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"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=xt(a.publicKey,i)}catch(u){n.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 Bi}from"node:crypto";import{readFileSync as Mu}from"node:fs";import Ge from"node:tls";var Mi=typeof Ge.getCACertificates=="function"&&typeof Ge.setDefaultCACertificates=="function",Li=!1,Di=new Map,Gi=t=>console.warn(t);function Gu(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Fi(t=Gi){if(Li)return;Li=!0;let e=L("EXTRA_CA_FILE");if(!(!e||!Mi))try{let r=Gu(Mu(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Ge.setDefaultCACertificates([...Ge.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 Hi(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 Fu(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
430
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Hu(t,e,r){return new Promise((n,o)=>{let i=Ge.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 Bi(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Gn(t,e,r){return new Promise(n=>{let o=Ge.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function Ku(t){try{let e=await fetch(t);return e.ok?new Bi(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ki(t,e=443,r=Gi){let n=`${t}:${e}`,o=Di.get(n);if(o)return o;let i=Wu(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Di.set(n,i),i}async function Wu(t,e,r){if(!Mi)return!1;let n=8e3;if(await Gn(t,e,n))return!0;let o=await Hu(t,e,n),i=Ge.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Fu(o);if(!c)break;let l=await Ku(c);if(!l)break;if(s.push(l.toString()),Ge.setDefaultCACertificates([...i,...s]),await Gn(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return Gn(t,e,n)}function Ie(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function de(t,e,r){Fi();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,i={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,i)}catch(s){if(Hi(s)&&await Ki(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var Wi=t=>new Promise(e=>setTimeout(e,t));function Yu(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function qu(){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 Vi(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=qu(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await de(t,r,n)}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<o&&Yu(l.status,u)){await Wi(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Wi(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Fe(t){let e;try{e=await de(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Ji(t){try{let e=await de(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var Vt="Stage",Yi=new Map;async function Vu(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Yi.get(o);if(i)return i;let s=await de(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===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return Yi.set(o,l.id),l.id}async function zi(t,e,r,n=Vt){let o=await Vu(t,e,r,n);await Vi(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function Xi(t,e,r){return await(await Vi(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var qi=new Map;async function Qi(t,e){let r=qi.get(e);if(r)return r;let n=await de(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return qi.set(e,i.id),i.id}async function Zi(t,e,r,n,o,i=Vt){let s=await Qi(t,e),a=await de(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$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,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await de(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}var ts="attachments(id,name,url,size,mimeType)",Ju="links(direction,linkType(name),issues(idReadable))",rs=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${ts},${Ju}`,zu=`id,text,created,author(login),${ts}`;function ns(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 os(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function is(t,e){let r=e.stageField??Vt,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${rs}&$top=200`,s=await de(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>cs(c,r))}async function ss(t,e,r=Vt){let n=`/api/issues/${encodeURIComponent(e)}?fields=${rs}`,o=await de(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return cs(await o.json(),r)}async function as(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${zu}&$top=500`,o=await de(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.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=ns(s.attachments);return c&&(a.attachments=c),a})}function Xu(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function cs(t,e=Vt){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.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=ns(t.attachments);a&&(s.attachments=a);let c=Xu(t.links);return c&&(s.links=c),s}async function ls(t,e){let r=await Qi(t,e),n=await de(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o){if(s.$type!=="StateProjectCustomField"||!s.field?.name)continue;let a=(s.bundle?.values??[]).filter(c=>c.name&&c.archived!==!0).map(c=>c.name);i.push({name:s.field.name,values:a})}return i}function fe(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function us(t,e){let r=B(t),n=[],o=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Fe({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:fe(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:fe(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await De(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"github",ok:!1,detail:fe(c)}),o.push({kind:"github",present:!0,ok:!1,detail:fe(c),checkedAt:i()})}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Be(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"bitbucket",ok:!1,detail:fe(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:fe(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Me(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"gitlab",ok:!1,detail:fe(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:fe(c),checkedAt:i()})}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.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 Nr(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(f){n.push({name:`repo:${u.name}`,ok:!1,detail:fe(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Nr(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){n.push({name:"context-repo",ok:!1,detail:fe(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Nr(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){o.push({kind:"contextWrite",present:!0,ok:!1,detail:fe(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=mt(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Fn(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Fn(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=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 n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function Jt(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function zt(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Xt(t,e=process.env){if(!t)return!1;let r=`https://${Ze}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Hn(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function ps(t,e=process.env){return Hn(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Jt(t,e),e)}function ds(t,e=process.env){return Hn(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>zt(t,e),e)}function fs(t,e=process.env){return Hn(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Ze}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Xt(t,e),e)}function ms(t){let e=B(t);if(!e)return null;if(!e.sealKey){let r=Lr();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},W(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:$e(e.sealKey.publicKey)}}async function gs(t,e,r,n){let o;try{o=JSON.parse(Dr(n,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=B(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await De(o.token);return i.github={token:o.token},vt(i,()=>{process.env.GH_TOKEN=o.token,ps(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Me(o.token);return i.gitlab={token:o.token},vt(i,()=>{process.env.GITLAB_TOKEN=o.token,ds(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Be(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},vt(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,fs(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Fe({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},vt(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Fn(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},vt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},vt(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 vt(t,e){W(t),e()}import{existsSync as Qu,readFileSync as Zu,statSync as hs}from"node:fs";var ys=2*1024*1024;function ep(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function ws(t,e){let r=Le(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!Qu(r)||!hs(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=hs(r);if(n>ys)throw new Error(`file too large: ${e} is ${n} bytes (limit ${ys})`);let o=Zu(r);return ep(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{existsSync as tp,readFileSync as rp,writeFileSync as np}from"node:fs";import{join as op}from"node:path";import{parseDocument as ip}from"yaml";var ks=64;async function bs(t,e){if(!Number.isInteger(e)||e<1||e>ks)throw new Error(`maxJobs must be an integer in [1, ${ks}], got ${e}`);let r=op(t,"regimen.yaml");if(!tp(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let n=ip(rp(r,"utf-8"));return n.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(n.setIn(["parallelism","max_jobs"],e),np(r,n.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as Kn,readFileSync as Wn,writeFileSync as sp}from"node:fs";import{join as Br}from"node:path";import{parseDocument as Yn}from"yaml";async function $s(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=Br(t,"project.yaml");if(!Kn(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Yn(Wn(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=Br(t,"regimen.yaml");if(!Kn(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Yn(Wn(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)sp(Br(t,i.path),i.content);return{files:r.map(i=>i.path)}}function qn(t){if(!t)return"Stage";try{let e=Br(t,"project.yaml");if(!Kn(e))return"Stage";let n=Yn(Wn(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var xs=t=>console.log(t);function vs(t){xs=t}function Qt(t,e="info"){xs(t,e)}import{homedir as ap}from"node:os";import{existsSync as cp,mkdirSync as lp}from"node:fs";import{join as Vn}from"node:path";import{simpleGit as Ss}from"simple-git";function er(t,e,r){let n=r??Vn(ap(),".codepipe","repos");return Vn(n,t,e)}async function Mr(t,e,r={}){let n=er(t,e.name,r.baseDir),o=r.cloneUrlOverride??up(e);if(!cp(Vn(n,".git"))){lp(n,{recursive:!0});let a=Ss();Qt(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
431
+ ${l.trim()}`)}}let i=Ss(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
432
+ ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Zt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var Cs=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function Gr(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&Qt(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await Zt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Zt(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...Cs,"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 n=`refs/codepipe/deliveries/${e}`;if(await Zt(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Zt(t,o)){let s=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}async function Rs(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:f}=r,p=await Ts(t,i,()=>Gr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let g=`origin/${c}`;if(await Zt(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([...Cs,"cherry-pick",p])}catch(S){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let R=S instanceof Error?S.message:String(S);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
433
+ ${R.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),C=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(C),await t.push([n,"--delete",o]).catch(()=>{}),{commit:h}}async function Is(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await Ts(t,i,()=>Gr(t,{contextRepoCloneUrl:n,deliveryRef:o,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 Ps(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:i,deleteBranch:s}=r,a=`origin/${n}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):i==="rebase"?(await t.checkout(["-B",n,a]),await t.rebase([o]),await t.checkout(o),await t.merge(["--ff-only",n])):await t.merge(["--no-ff",a,"-m",`Merge branch '${n}'`]),await t.push(["origin",o]),s&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function up(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 Fr=new Map;async function Jn(t,e){let n=(Fr.get(t)??Promise.resolve()).catch(()=>{}).then(e);Fr.set(t,n);try{return await n}finally{Fr.get(t)===n&&Fr.delete(t)}}async function Es(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;Qt(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Jn(`${i}/${r.name}`,async()=>{let s=await Mr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=er(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 Z({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Jn(`${i}/${r.name}`,async()=>{let s=await Mr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=er(i,r.name,t.baseDir),{commit:c,pushed:l}=await Is(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return Z({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return K("no repo spec");let i=Re(r),s=await i.createPullRequest(r,e);return Z({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return K("no repo spec");let i=Re(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return Z({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return K("no repo spec");let i=Re(r);return await i.closePR(r,e.prNumber,e.comment),Z({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Jn(`${i}/${r.name}`,async()=>{let s=await Mr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=er(i,r.name,t.baseDir),{mergedSha:c}=await Ps(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return Z({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return Z({stub:!0});case"tracker_status":{let i=Ie();return i?t.trackerIssueId?(await zi(i,t.trackerIssueId,e.newStatus,qn(t.contextDir)),Z({issueId:t.trackerIssueId,newStatus:e.newStatus})):K("no tracker_issue_id provided"):K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=Ie();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return K("no tracker_issue_id provided");let s=await Xi(i,t.trackerIssueId,e.body);return Z({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ie();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return K("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Zi(i,e.projectKey,e.title,e.body,e.targetStatus,qn(t.contextDir));return Z({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ie();if(!i)return K("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 K(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return Z({applied:s})}case"set_parallelism":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await bs(t.contextDir,e.maxJobs);return Z({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await $s(t.contextDir,e);return Z({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),Z({reported:!0})):K("no context repo clone on this CLI");case"read_context_file":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=ws(t.contextDir,e.path);return Z({path:e.path,...i})}}}catch(i){return K(i instanceof Error?i.message:String(i))}}function Z(t){return{status:"done",result:t}}function K(t){return{status:"failed",error:t}}import{existsSync as Hs,readFileSync as Ks}from"node:fs";import{join as Ws}from"node:path";import{homedir as pp}from"node:os";import{existsSync as dp,mkdirSync as fp,readFileSync as mp,writeFileSync as gp}from"node:fs";import{dirname as hp,join as yp}from"node:path";function zn(){return L("FARM_PINS")??yp(pp(),".codepipe","farm-pins.json")}function js(){let t=zn();if(!dp(t))return{};try{return JSON.parse(mp(t,"utf-8"))}catch{return{}}}function wp(t){let e=zn();fp(hp(e),{recursive:!0}),gp(e,JSON.stringify(t,null,2)+`
434
+ `,{mode:384})}function kp(t){return js()[t]}function Hr(t,e){let r=js();r[t]=e,wp(r)}function Kr(t,e){let r=$e(e),n=kp(t);if(n&&n!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${zn()}.`);return r}import bp from"ws";function Wr(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new bp(r)}var N=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};async function St(t,e,r){return He(t,e,"/projects",r)}async function As(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Yr(t,e,r,n){return He(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function _s(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 N(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function qr(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Os(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var tr=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function Ns(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 n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new tr(e)}if(!r.ok)throw new N(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Us(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new N(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Ls(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Ds(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new N(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Bs(t,e,r,n){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Ms(t,e,r,n,o){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function Gs(t,e,r,n,o){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function Fs(t,e,r,n,o){return He(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Vr(t,e,r,n){return He(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Xn(t,e,r,n){await He(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Q(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function He(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new N(o.status,s,a)}return s}async function Ys(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=$e(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Kr(e.farmId,e.farmPublicKey);let s=B(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await Q(t.hubUrl,t.cliToken,t.projectId),c;if(r){let p=Ws(r,"project.yaml"),g=Ws(r,"regimen.yaml");Hs(p)&&Hs(g)?c={projectYaml:Ks(p,"utf-8"),regimenYaml:Ks(g,"utf-8")}:n.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=xt(e.farmPublicKey,JSON.stringify(l));Hr(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await Yr(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}:{}}:o(f.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}var Jr=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}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 n=[];for(let s of r.prs){let a=Re(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof it){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 o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Re(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:n}),this.lastSig.set(e,o);let i=$p(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function $p(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 qs,readFileSync as xp,readdirSync as vp}from"node:fs";function Sp(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Ip(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Cp(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Rp(Tp(t,i,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function Vs(t,e,r){if(r.length===0)return;let n=Sp(t,e,r),o=r.map(i=>i.issue.key);await bt(t,n,`sync(${o.join(", ")}): task data`)}function Cp(t,e,r){let n=new Date(t.updatedAt).toISOString(),o=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${n}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){o.push("## Attachments","");for(let i of r)o.push(`- [${i}](attachments/${encodeURI(i)})`);o.push("")}return o.join(`
435
+ `)}function Tp(t,e,r){let n=new Map,o=Le(t,`tasks/${e}/comments.jsonl`);if(qs(o))for(let i of xp(o,"utf-8").split(`
436
+ `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.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=xr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Rp(t){return t.map(e=>JSON.stringify(e)).join(`
437
437
  `)+(t.length>0?`
438
- `:"")}function Rp(t,e,r){let n=[],o=Le(t,`tasks/${e}/attachments`);if(Ks(o))for(let i of xp(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var Vr=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}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=Ie();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 n=Date.now(),o;try{let k=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await rs(r,{projectKey:e.projectKey,columns:k,...e.stageField?{stageField:e.stageField}:{},...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(k){this.log.warn(`[yt-sync] listIssues failed: ${k instanceof Error?k.message:String(k)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let k of o){if(s.add(k.id),a.has(k.status))continue;let b=await qs(r,k.id,e.sinceMs,this.log);b&&i.set(k.id,b)}let c=[];for(let k of e.offBoardIssueIds){if(s.has(k))continue;let b=await qs(r,k,e.sinceMs,this.log);if(b&&b.length>0&&i.set(k,b),e.requireAssignee||b&&b.length>0){let _=await jp(r,k,e.stageField,this.log);if(_)c.push(_);else if(b&&b.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(k=>!a.has(k.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(k=>({issue:k,comments:i.get(k.id)??[],attachments:u.get(k.id)??[]}));try{await Ws(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let k of f)this.shippedAttachments.add(k)}catch(k){let b=k instanceof Error?k.message:String(k);this.abandonTick(`context task sync failed: ${b}`);return}let g=this.options.isSelfComment??(()=>!1),d=[],y=[];for(let[k,b]of i){let _=b.filter(I=>!g(I.id));if(_.length===0)continue;d.push({issueId:k,comments:_.map(Ip)});let O=_.flatMap(I=>{let h=$r(I.body);return h?[{commentId:I.id,author:I.author,name:h.name,args:h.args,createdAt:I.createdAt}]:[]});O.length>0&&y.push({issueId:k,commands:O})}let S={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Ys),commentsBatch:d,...y.length>0?{commandsBatch:y}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Ys)}:{},observedAtMs:n};this.send(S);let C=d.reduce((k,b)=>k+b.comments.length,0),R=y.reduce((k,b)=>k+b.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${C} commands=${R} (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,n){let o=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 ts(n,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=Pp(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&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Ys(t){let{description:e,...r}=t;return r}function Ip(t){let{body:e,...r}=t;return r}function Pp(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 jp(t,e,r,n){try{return await ns(t,e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function qs(t,e,r,n){try{return await os(t,e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Xn="npm i -g @code-partner/codepipe@latest";function Jr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${ce} (protocol ${he})`);let n=d=>e.onEvent?.(d),o=e.workspace;o?.contextDir&&fi(o.contextDir,r);let i=Vs("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Vs("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=Hr(t.hubUrl,t.cliToken),y=null,S=new qr(i,I=>{d.readyState===d.OPEN&&d.send(JSON.stringify(I))},r),C=new Vr(s,I=>{d.readyState===d.OPEN&&d.send(JSON.stringify(I))},r,{contextDir:o?.contextDir??null,isSelfComment:I=>f.has(I)}),R=null,k=async()=>{try{let I;try{let v=await Q(t.hubUrl,t.cliToken,t.projectId);I={repos:v.repos,contextRepo:v.contextRepo}}catch(v){r.warn(`[readiness] could not fetch project summary for push checks: ${v instanceof Error?v.message:String(v)}`)}let h=await as(t.projectId,I);if(d.readyState!==d.OPEN)return;let m={type:"cli_readiness",projectId:t.projectId,ready:h.ready,checks:h.checks,creds:h.creds,checkedAt:h.checkedAt};if(d.send(JSON.stringify(m)),h.ready)r.info("[readiness] ready");else{let v=h.checks.filter(x=>!x.ok).map(x=>`${x.name}(${x.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${v.join(", ")}`)}}catch(I){r.warn(`[readiness] check failed: ${I instanceof Error?I.message:String(I)}`)}},b=()=>{k(),R=setInterval(()=>void k(),a),typeof R.unref=="function"&&R.unref()},_=()=>{R&&(clearInterval(R),R=null)},O=o?.contextDir?new Er(o.contextDir,t.projectId,I=>{d.readyState===d.OPEN&&d.send(JSON.stringify(I))},r):null;return d.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let I=li(t.projectId),h=L("ORIGIN")==="farm"?"farm":"local",m=L("FARM_ID"),v=t.accountEmail??I.email,x;try{let T=ps(t.projectId);T&&(x=T.publicKey,r.info(`[cred-channel] key fingerprint: ${T.fingerprint}`))}catch(T){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${T instanceof Error?T.message:String(T)}`)}let w={type:"register",projectId:t.projectId,platformVersion:ce,protocolVersion:he,accountId:I.accountId,accountLabel:I.label,origin:h,inFlightActionIds:[...u],...v?{accountEmail:v}:{},...h==="farm"&&m?{farmId:m}:{},...x?{sealPublicKey:x}:{}};d.send(JSON.stringify(w))}),d.on("message",async I=>{let h=I.toString("utf-8");if(h==="pong"||h==="ping")return;let m;try{m=JSON.parse(h)}catch{return}if(!m||typeof m!="object")return;let v=m.type;if(v==="registered"){let w=m;if(w.ok){if(r.info(`[ws] registered for project ${w.projectId}`),n({kind:"registered",projectId:w.projectId??t.projectId}),S.start(),O?.start(),b(),o?.contextDir){let T=o.contextDir;try{let P=_r(T,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.outdated&&(r.warn(`[ctx] context format outdated: v${P.templateVersion} \u2192 v${P.currentVersion}`+(P.missingPaths.length>0?` (missing: ${P.missingPaths.join(", ")})`:"")),l||(l=!0,(async()=>{try{let U;try{U=(await Q(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let ie=await Ii(T,t.projectId,U,r);d.readyState===d.OPEN&&d.send(JSON.stringify(ie))}catch(U){r.warn(`[ctx] context migration failed (non-fatal): ${U instanceof Error?U.message:String(U)}`)}})()))}catch(P){r.warn(`[ctx] context-format detect failed (non-fatal): ${P instanceof Error?P.message:String(P)}`)}}}else r.warn(`[ws] register rejected: ${w.reason??"unknown"}`),n({kind:"register_rejected",reason:w.reason??"unknown"}),c=!0,d.close();return}if(v==="hello"){let w=m;y=wr(w.protocolVersion);let T=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${T}`),y||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ce}, protocol ${he}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Xn}`),n({kind:"incompatible",hubVersion:typeof w.platformVersion=="string"?w.platformVersion:null,hubProtocol:typeof w.protocolVersion=="number"?w.protocolVersion:null,updateCommand:Xn}));return}if(v==="tracking_targets"){S.setTargets(m.targets);return}if(v==="youtrack_sync_request"){C.setRequest(m);return}if(v==="sync_local"){await Ap(m,o,d,r);return}if(v==="context_write"){await _p(m,o,d,r);return}if(v==="adr_promote"){await Op(m,o,d,r);return}if(v==="cred_update"){let w=m,T=B(t.projectId),P=T?.sealKey?await ds(t.projectId,w.kind,w.sealed,T.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},U={type:"cred_update_result",updateId:w.updateId,projectId:t.projectId,ok:P.ok,...P.detail?{detail:P.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(U)),P.ok?(r.info(`[cred] ${w.kind} replaced${P.detail?` \u2014 ${P.detail}`:""}`),k()):r.warn(`[cred] ${w.kind} replacement rejected: ${P.detail??"unknown"}`);return}if(v==="move_to_farm"){let w=m;r.info(`[farm-move] request to move ${t.projectId} onto farm ${w.farmName} (${w.farmId})`);let T=await Hs(t,w,o?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(T)),T.ok?r.info(`[farm-move] done \u2014 farm daemon ${T.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${T.error??"unknown error"}`);return}if(v==="tracker_fields_request"){let w=m,T={type:"tracker_fields_result",requestId:w.requestId,projectId:t.projectId,ok:!1},P=Ie();if(!P)T.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{T.fields=await ss(P,w.projectKey),T.ok=!0}catch(U){T.error=U instanceof Error?U.message:String(U)}d.readyState===d.OPEN&&d.send(JSON.stringify(T)),T.ok||r.warn(`[yt-fields] listing failed: ${T.error??"unknown"}`);return}if(v==="sandbox_keys"){let w=B(t.projectId);if(!w){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let T=mt(t.projectId),P=_i(m,w,T,r);for(let U of P)d.readyState===d.OPEN&&d.send(JSON.stringify(U));return}if(v!=="dispatch_action")return;let x=m;if(y===!1){let w=`refused: HUB protocol incompatible with CLI v${ce} (protocol ${he})`;d.send(JSON.stringify({type:"action_result",actionId:x.actionId,status:"failed",error:w})),r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 REFUSED: ${w}`),r.warn(`[exec] update the CLI to clear this: ${Xn}`),n({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:!1,error:w});return}u.add(x.actionId);try{let w=await Rs({action:x.action,repo:x.repo,trackerIssueId:x.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:O?()=>O.reportNow():void 0}).catch(U=>({status:"failed",error:U instanceof Error?U.message:String(U)}));x.action.type==="tracker_comment"&&w.status==="done"&&"result"in w&&typeof w.result?.commentId=="string"&&f.add(w.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:x.actionId,...w}));let T=w.status!=="failed",P=!T&&"error"in w?w.error:void 0;T?r.info(`[exec] ${x.actionId} (${x.action.type}) \u2192 done`):r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 FAILED: ${P??"?"}`),n({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:T,...P?{error:P}:{}})}finally{u.delete(x.actionId)}}),d.on("close",(I,h)=>{let m=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${I}${m?` reason=${m}`:""}`),S.stop(),C.stop(),O?.stop(),_(),m==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:I}),!c&&setTimeout(()=>{p=g()},2e3)}),d.on("error",I=>r.warn(`[ws] error: ${I.message}`)),d}return{stop(){c=!0,p.close()}}}async function Ap(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let i=e.repos.find(l=>l.name===o.repoName),s=Ep(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await ui(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function _p(t,e,r,n){let o=(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){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await bt(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function Op(t,e,r,n){let o=(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){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=await $i(e.contextDir,t.taskKey,t.slugs);if(n.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(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${s}`),o("failed",s);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function Vs(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as ta,mkdirSync as ra}from"node:fs";import{dirname as na}from"node:path";import{simpleGit as Ct}from"simple-git";import{execFileSync as Np}from"node:child_process";import{mkdtempSync as Up,mkdirSync as Lp,readFileSync as Js,rmSync as Dp,writeFileSync as Bp}from"node:fs";import{tmpdir as Mp}from"node:os";import{dirname as Gp,join as zs}from"node:path";function Xs(t="codepipe-context"){let e=Up(zs(Mp(),"codepipe-ssh-")),r=zs(e,"id_ed25519");try{return Np("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Js(r,"utf-8"),publicKey:Js(`${r}.pub`,"utf-8").trim()}}finally{Dp(e,{recursive:!0,force:!0})}}async function Qs(t,e,r,n="codepipe-context"){let o=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:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function Zs(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 ea(t,e){Lp(Gp(t),{recursive:!0});let r=e.endsWith(`
438
+ `:"")}function Ip(t,e,r){let n=[],o=Le(t,`tasks/${e}/attachments`);if(qs(o))for(let i of vp(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var zr=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}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=Ie();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 n=Date.now(),o;try{let k=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await is(r,{projectKey:e.projectKey,columns:k,...e.stageField?{stageField:e.stageField}:{},...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(k){this.log.warn(`[yt-sync] listIssues failed: ${k instanceof Error?k.message:String(k)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let k of o){if(s.add(k.id),a.has(k.status))continue;let b=await zs(r,k.id,e.sinceMs,this.log);b&&i.set(k.id,b)}let c=[];for(let k of e.offBoardIssueIds){if(s.has(k))continue;let b=await zs(r,k,e.sinceMs,this.log);if(b&&b.length>0&&i.set(k,b),e.requireAssignee||b&&b.length>0){let _=await jp(r,k,e.stageField,this.log);if(_)c.push(_);else if(b&&b.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(k=>!a.has(k.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(k=>({issue:k,comments:i.get(k.id)??[],attachments:u.get(k.id)??[]}));try{await Vs(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let k of f)this.shippedAttachments.add(k)}catch(k){let b=k instanceof Error?k.message:String(k);this.abandonTick(`context task sync failed: ${b}`);return}let g=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[k,b]of i){let _=b.filter(I=>!g(I.id));if(_.length===0)continue;d.push({issueId:k,comments:_.map(Pp)});let O=_.flatMap(I=>{let y=xr(I.body);return y?[{commentId:I.id,author:I.author,name:y.name,args:y.args,createdAt:I.createdAt}]:[]});O.length>0&&h.push({issueId:k,commands:O})}let C={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Js),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Js)}:{},observedAtMs:n};this.send(C);let S=d.reduce((k,b)=>k+b.comments.length,0),R=h.reduce((k,b)=>k+b.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${S} commands=${R} (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,n){let o=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 os(n,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=Ep(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&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Js(t){let{description:e,...r}=t;return r}function Pp(t){let{body:e,...r}=t;return r}function Ep(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 jp(t,e,r,n){try{return await ss(t,e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function zs(t,e,r,n){try{return await as(t,e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Qn="npm i -g @code-partner/codepipe@latest";function Xr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${ce} (protocol ${he})`);let n=d=>e.onEvent?.(d),o=e.workspace;o?.contextDir&&mi(o.contextDir,r);let i=Xs("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Xs("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=Wr(t.hubUrl,t.cliToken),h=null,C=new Jr(i,I=>{d.readyState===d.OPEN&&d.send(JSON.stringify(I))},r),S=new zr(s,I=>{d.readyState===d.OPEN&&d.send(JSON.stringify(I))},r,{contextDir:o?.contextDir??null,isSelfComment:I=>f.has(I)}),R=null,k=async()=>{try{let I;try{let v=await Q(t.hubUrl,t.cliToken,t.projectId);I={repos:v.repos,contextRepo:v.contextRepo}}catch(v){r.warn(`[readiness] could not fetch project summary for push checks: ${v instanceof Error?v.message:String(v)}`)}let y=await us(t.projectId,I);if(d.readyState!==d.OPEN)return;let m={type:"cli_readiness",projectId:t.projectId,ready:y.ready,checks:y.checks,creds:y.creds,checkedAt:y.checkedAt};if(d.send(JSON.stringify(m)),y.ready)r.info("[readiness] ready");else{let v=y.checks.filter(x=>!x.ok).map(x=>`${x.name}(${x.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${v.join(", ")}`)}}catch(I){r.warn(`[readiness] check failed: ${I instanceof Error?I.message:String(I)}`)}},b=()=>{k(),R=setInterval(()=>void k(),a),typeof R.unref=="function"&&R.unref()},_=()=>{R&&(clearInterval(R),R=null)},O=o?.contextDir?new Ar(o.contextDir,t.projectId,I=>{d.readyState===d.OPEN&&d.send(JSON.stringify(I))},r):null;return d.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let I=ui(t.projectId),y=L("ORIGIN")==="farm"?"farm":"local",m=L("FARM_ID"),v=t.accountEmail??I.email,x;try{let T=ms(t.projectId);T&&(x=T.publicKey,r.info(`[cred-channel] key fingerprint: ${T.fingerprint}`))}catch(T){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${T instanceof Error?T.message:String(T)}`)}let w={type:"register",projectId:t.projectId,platformVersion:ce,protocolVersion:he,accountId:I.accountId,accountLabel:I.label,origin:y,inFlightActionIds:[...u],...v?{accountEmail:v}:{},...y==="farm"&&m?{farmId:m}:{},...x?{sealPublicKey:x}:{}};d.send(JSON.stringify(w))}),d.on("message",async I=>{let y=I.toString("utf-8");if(y==="pong"||y==="ping")return;let m;try{m=JSON.parse(y)}catch{return}if(!m||typeof m!="object")return;let v=m.type;if(v==="registered"){let w=m;if(w.ok){if(r.info(`[ws] registered for project ${w.projectId}`),n({kind:"registered",projectId:w.projectId??t.projectId}),C.start(),O?.start(),b(),o?.contextDir){let T=o.contextDir;try{let P=Or(T,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.outdated&&(r.warn(`[ctx] context format outdated: v${P.templateVersion} \u2192 v${P.currentVersion}`+(P.missingPaths.length>0?` (missing: ${P.missingPaths.join(", ")})`:"")),l||(l=!0,(async()=>{try{let U;try{U=(await Q(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let ie=await ji(T,t.projectId,U,r);d.readyState===d.OPEN&&d.send(JSON.stringify(ie))}catch(U){r.warn(`[ctx] context migration failed (non-fatal): ${U instanceof Error?U.message:String(U)}`)}})()))}catch(P){r.warn(`[ctx] context-format detect failed (non-fatal): ${P instanceof Error?P.message:String(P)}`)}}}else r.warn(`[ws] register rejected: ${w.reason??"unknown"}`),n({kind:"register_rejected",reason:w.reason??"unknown"}),c=!0,d.close();return}if(v==="hello"){let w=m;h=kr(w.protocolVersion);let T=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${T}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ce}, protocol ${he}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Qn}`),n({kind:"incompatible",hubVersion:typeof w.platformVersion=="string"?w.platformVersion:null,hubProtocol:typeof w.protocolVersion=="number"?w.protocolVersion:null,updateCommand:Qn}));return}if(v==="tracking_targets"){C.setTargets(m.targets);return}if(v==="youtrack_sync_request"){S.setRequest(m);return}if(v==="sync_local"){await _p(m,o,d,r);return}if(v==="context_write"){await Op(m,o,d,r);return}if(v==="adr_promote"){await Np(m,o,d,r);return}if(v==="cred_update"){let w=m,T=B(t.projectId),P=T?.sealKey?await gs(t.projectId,w.kind,w.sealed,T.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},U={type:"cred_update_result",updateId:w.updateId,projectId:t.projectId,ok:P.ok,...P.detail?{detail:P.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(U)),P.ok?(r.info(`[cred] ${w.kind} replaced${P.detail?` \u2014 ${P.detail}`:""}`),k()):r.warn(`[cred] ${w.kind} replacement rejected: ${P.detail??"unknown"}`);return}if(v==="move_to_farm"){let w=m;r.info(`[farm-move] request to move ${t.projectId} onto farm ${w.farmName} (${w.farmId})`);let T=await Ys(t,w,o?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(T)),T.ok?r.info(`[farm-move] done \u2014 farm daemon ${T.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${T.error??"unknown error"}`);return}if(v==="tracker_fields_request"){let w=m,T={type:"tracker_fields_result",requestId:w.requestId,projectId:t.projectId,ok:!1},P=Ie();if(!P)T.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{T.fields=await ls(P,w.projectKey),T.ok=!0}catch(U){T.error=U instanceof Error?U.message:String(U)}d.readyState===d.OPEN&&d.send(JSON.stringify(T)),T.ok||r.warn(`[yt-fields] listing failed: ${T.error??"unknown"}`);return}if(v==="sandbox_keys"){let w=B(t.projectId);if(!w){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let T=mt(t.projectId),P=Ui(m,w,T,r);for(let U of P)d.readyState===d.OPEN&&d.send(JSON.stringify(U));return}if(v!=="dispatch_action")return;let x=m;if(h===!1){let w=`refused: HUB protocol incompatible with CLI v${ce} (protocol ${he})`;d.send(JSON.stringify({type:"action_result",actionId:x.actionId,status:"failed",error:w})),r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 REFUSED: ${w}`),r.warn(`[exec] update the CLI to clear this: ${Qn}`),n({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:!1,error:w});return}u.add(x.actionId);try{let w=await Es({action:x.action,repo:x.repo,trackerIssueId:x.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:O?()=>O.reportNow():void 0}).catch(U=>({status:"failed",error:U instanceof Error?U.message:String(U)}));x.action.type==="tracker_comment"&&w.status==="done"&&"result"in w&&typeof w.result?.commentId=="string"&&f.add(w.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:x.actionId,...w}));let T=w.status!=="failed",P=!T&&"error"in w?w.error:void 0;T?r.info(`[exec] ${x.actionId} (${x.action.type}) \u2192 done`):r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 FAILED: ${P??"?"}`),n({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:T,...P?{error:P}:{}})}finally{u.delete(x.actionId)}}),d.on("close",(I,y)=>{let m=y?.toString("utf-8")??"";if(r.info(`[ws] closed code=${I}${m?` reason=${m}`:""}`),C.stop(),S.stop(),O?.stop(),_(),m==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:I}),!c&&setTimeout(()=>{p=g()},2e3)}),d.on("error",I=>r.warn(`[ws] error: ${I.message}`)),d}return{stop(){c=!0,p.close()}}}async function _p(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let i=e.repos.find(l=>l.name===o.repoName),s=Ap(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await pi(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function Op(t,e,r,n){let o=(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){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await bt(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function Np(t,e,r,n){let o=(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){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=await xi(e.contextDir,t.taskKey,t.slugs);if(n.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(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${s}`),o("failed",s);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function Xs(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as oa,mkdirSync as ia}from"node:fs";import{dirname as sa}from"node:path";import{simpleGit as Ct}from"simple-git";import{execFileSync as Up}from"node:child_process";import{mkdtempSync as Lp,mkdirSync as Dp,readFileSync as Qs,rmSync as Bp,writeFileSync as Mp}from"node:fs";import{tmpdir as Gp}from"node:os";import{dirname as Fp,join as Zs}from"node:path";function ea(t="codepipe-context"){let e=Lp(Zs(Gp(),"codepipe-ssh-")),r=Zs(e,"id_ed25519");try{return Up("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Qs(r,"utf-8"),publicKey:Qs(`${r}.pub`,"utf-8").trim()}}finally{Bp(e,{recursive:!0,force:!0})}}async function ta(t,e,r,n="codepipe-context"){let o=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:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function ra(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function na(t,e){Dp(Fp(t),{recursive:!0});let r=e.endsWith(`
439
439
  `)?e:e+`
440
- `;return Bp(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Fp(t,e,r="x-access-token"){let n=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,o=t.match(/^git@([^:]+):(.+)$/);if(o)return`https://${n}@${o[1]}/${o[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${n}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${n}@${s[1]}`:t}function Hp(t,e){return e?.contextWrite?.token?{user:xr(t),secret:e.contextWrite.token}:t===Kt.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Kt.bitbucket?e?.bitbucket?.apiToken?{user:Ze,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function zr(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await Q(e.hubUrl,e.cliToken,e.projectId)}catch(c){return o.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=Hp(dt(s.cloneUrl),r);if(a){let c=await Kp({ctx:s,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await Wp({ctx:s,contextDir:n,privateKey:r.contextSsh.privateKey,log:o});if(c)return c;o.warn("[ctx] SSH deploy-key clone failed")}return o.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 Kp(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Fp(e.cloneUrl,n.secret,n.user),s=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(ta(`${r}/.git`)){let l=Ct(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Pn(r);await l.reset(["--hard",`origin/${s}`]),jn(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else ra(na(r),{recursive:!0}),await Ct().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await oa(r)}catch(l){return o.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function Wp(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=ea(i,n),a=Zs(e.cloneUrl),c=e.branch;try{if(ta(`${r}/.git`)){let l=Ct(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=Pn(r);await l.reset(["--hard",`origin/${c}`]),jn(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ra(na(r),{recursive:!0}),await Ct().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ct(r).addConfig("core.sshCommand",s,!1,"local"),o.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 o.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function oa(t){let e=Ct(t);await e.raw(["config","user.email"]).then(n=>n.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}async function ia(t={profile:void 0}){let{cfg:e,profile:r}=Tr(t.profile),n=B(e.projectId);n&&Wt(n),Vt(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Jt(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),zt(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=tr(Qn(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Pr("CLI_LOG",i,o);if(s.enabled){let p=new ht(s);jr(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=Sr(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=tr(Qn(),".codepipe",r?tr("profiles",r,"context"):"context");if(await zn(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await zr({cfg:e,secrets:n,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),a||await zn(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=tr(Qn(),".codepipe",r?tr("profiles",r,"context-config"):"context-config");Ar(a.contextDir,g,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=Jr(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 Qp}from"node:os";import{spawnSync as Yp}from"node:child_process";function qp(){try{return Yp("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function sa(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:qp(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Tt}from"node:os";import{mkdirSync as Vp,readFileSync as aa,writeFileSync as Jp,existsSync as Zn}from"node:fs";import{dirname as zp,join as Ke}from"node:path";Zn(".env")&&process.loadEnvFile(".env");function Pe(t){let e=L("SANDBOX_CONFIG");if(e)return e;let r=Ke(Tt(),".codepipe","worker");return t?Ke(r,"profiles",t,"config.json"):Ke(r,"config.json")}function ca(){return Ke(Tt(),".devpipe-sandbox","config.json")}function Xr(){et(Ke(Tt(),".devpipe"),Ke(Tt(),".codepipe")),L("SANDBOX_CONFIG")||et(Ke(Tt(),".devpipe-sandbox"),Ke(Tt(),".codepipe-sandbox"))}function ee(t){let e=Pe(t);return Zn(e)?JSON.parse(aa(e,"utf-8")):!t&&!L("SANDBOX_CONFIG")&&Zn(ca())?JSON.parse(aa(ca(),"utf-8")):null}function la(t,e){let r=Pe(e);Vp(zp(r),{recursive:!0}),Jp(r,JSON.stringify(t,null,2)+`
442
- `,{mode:384})}import Xp from"ws";var Rt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e){if(!this.token)throw new Error("no sandbox token");let r={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};return e&&(r.signal=e),fetch(`${this.hubUrl}/jobs/claim`,r)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){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,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);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 Xp(e)}};async function st(t){Xr();let e=ee(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Pe(t.profile)}.`),process.exit(1));let r=t.name??Qp(),n=sa({projects:t.projects??[],llm:t.llm??null}),o=new Rt(t.hub.replace(/\/$/,"")),i=Nr(),s=be(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});la({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Pe(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as Dd,readFileSync as io,readdirSync as Bd,writeFileSync as Md}from"node:fs";import{dirname as Gd,join as ar,resolve as Fd}from"node:path";import{spawn as Zp}from"node:child_process";import{existsSync as ed}from"node:fs";var It=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Qr=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},td=5e3,rr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.signal?.aborted)throw new Qr;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 n=[],o=[],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 y=id(d.rate_limit_info);y&&(!l||y.utilization>l.utilization)&&(l=y);return}if(d.type==="assistant"){let y=d.message;typeof y?.model=="string"&&(c=y.model);let S=y?.usage;S&&(a+=1,s.input+=oe(S.input_tokens),s.output+=oe(S.output_tokens),s.cacheRead+=oe(S.cache_read_input_tokens),s.cacheCreate+=oe(S.cache_creation_input_tokens))}}},f=e.role,p=e.onActivity,g=d=>{if(p)for(let y of ad(d,e.workspaceDir))try{p(y)}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,y)=>{let S=Zp(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 C=!1,R=null,k=()=>{C=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),S.kill("SIGTERM"),R=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),S.kill("SIGKILL")},td)};e.signal?.addEventListener("abort",k,{once:!0});let b=()=>{R&&clearTimeout(R),e.signal?.removeEventListener("abort",k)},_="";S.stdout.on("data",O=>{n.push(O),_+=O;let I;for(;(I=_.indexOf(`
443
- `))!==-1;){let h=_.slice(0,I).trim();if(_=_.slice(I+1),h){let m=ua(h);u(m),m&&g(m)}}}),S.stderr.on("data",O=>{n.push(O),o.push(O);for(let I of O.split(`
444
- `)){let h=I.trim();h&&console.warn(`[claude:stderr] ${h}`)}}),S.on("error",O=>{b(),y(O)}),S.on("close",O=>{if(b(),C){y(new Qr);return}if(_.trim()){let h=ua(_.trim());u(h),h&&g(h)}let I=i?.is_error===!0;if(O!==0||I){let h=typeof i?.api_error_status=="number"?i.api_error_status:void 0,m=typeof i?.subtype=="string"?i.subtype:void 0,v=typeof i?.result=="string"?i.result:void 0;y(new It(rd(O,i,o.join("")),{code:O,apiErrorStatus:h,subtype:m,resultText:v,retryAfterMs:nd(i)}));return}console.log("[claude] exit code=0"),d({artifactPaths:[],log:n.join(""),usage:sd(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&ed(n))}};function ua(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 n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${We(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=od(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let n=e.message;for(let o of n?.content??[])if(o.type==="tool_result")if(o.is_error===!0){let i=da(o.content);console.log(`[claude] tool_result (error)${i?`: ${We(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${We(JSON.stringify(e),200)}`),e}function rd(t,e,r){let n=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let o=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;o?n.push(We(o,500)):typeof s=="string"&&s!=="success"&&n.push(s),typeof i=="number"&&n.push(`(api_status=${i})`)}return n.length===1&&r.trim()&&n.push(We(r.trim().split(`
440
+ `;return Mp(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Hp(t,e,r="x-access-token"){let n=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,o=t.match(/^git@([^:]+):(.+)$/);if(o)return`https://${n}@${o[1]}/${o[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${n}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${n}@${s[1]}`:t}function Kp(t,e){return e?.contextWrite?.token?{user:vr(t),secret:e.contextWrite.token}:t===Wt.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Wt.bitbucket?e?.bitbucket?.apiToken?{user:Ze,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Qr(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await Q(e.hubUrl,e.cliToken,e.projectId)}catch(c){return o.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=Kp(dt(s.cloneUrl),r);if(a){let c=await Wp({ctx:s,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await Yp({ctx:s,contextDir:n,privateKey:r.contextSsh.privateKey,log:o});if(c)return c;o.warn("[ctx] SSH deploy-key clone failed")}return o.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 Wp(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Hp(e.cloneUrl,n.secret,n.user),s=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(oa(`${r}/.git`)){let l=Ct(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=jn(r);await l.reset(["--hard",`origin/${s}`]),An(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else ia(sa(r),{recursive:!0}),await Ct().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await aa(r)}catch(l){return o.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function Yp(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=na(i,n),a=ra(e.cloneUrl),c=e.branch;try{if(oa(`${r}/.git`)){let l=Ct(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=jn(r);await l.reset(["--hard",`origin/${c}`]),An(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ia(sa(r),{recursive:!0}),await Ct().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ct(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await aa(r),{root:r,contextDir:r,repos:[]}}catch(l){return o.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function aa(t){let e=Ct(t);await e.raw(["config","user.email"]).then(n=>n.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}async function ca(t={profile:void 0}){let{cfg:e,profile:r}=Rr(t.profile),n=B(e.projectId);n&&Yt(n),Jt(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),zt(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Xt(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=rr(Zn(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Er("CLI_LOG",i,o);if(s.enabled){let p=new ht(s);jr(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=Cr(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=rr(Zn(),".codepipe",r?rr("profiles",r,"context"):"context");if(await Xn(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Qr({cfg:e,secrets:n,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),a||await Xn(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=rr(Zn(),".codepipe",r?rr("profiles",r,"context-config"):"context-config");_r(a.contextDir,g,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=Xr(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 Zp}from"node:os";import{spawnSync as qp}from"node:child_process";function Vp(){try{return qp("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function la(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Vp(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Tt}from"node:os";import{mkdirSync as Jp,readFileSync as ua,writeFileSync as zp,existsSync as eo}from"node:fs";import{dirname as Xp,join as Ke}from"node:path";eo(".env")&&process.loadEnvFile(".env");function Pe(t){let e=L("SANDBOX_CONFIG");if(e)return e;let r=Ke(Tt(),".codepipe","worker");return t?Ke(r,"profiles",t,"config.json"):Ke(r,"config.json")}function pa(){return Ke(Tt(),".devpipe-sandbox","config.json")}function Zr(){et(Ke(Tt(),".devpipe"),Ke(Tt(),".codepipe")),L("SANDBOX_CONFIG")||et(Ke(Tt(),".devpipe-sandbox"),Ke(Tt(),".codepipe-sandbox"))}function ee(t){let e=Pe(t);return eo(e)?JSON.parse(ua(e,"utf-8")):!t&&!L("SANDBOX_CONFIG")&&eo(pa())?JSON.parse(ua(pa(),"utf-8")):null}function da(t,e){let r=Pe(e);Jp(Xp(r),{recursive:!0}),zp(r,JSON.stringify(t,null,2)+`
442
+ `,{mode:384})}import Qp from"ws";var Rt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e){if(!this.token)throw new Error("no sandbox token");let r={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};return e&&(r.signal=e),fetch(`${this.hubUrl}/jobs/claim`,r)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){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,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);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 Qp(e)}};async function st(t){Zr();let e=ee(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Pe(t.profile)}.`),process.exit(1));let r=t.name??Zp(),n=la({projects:t.projects??[],llm:t.llm??null}),o=new Rt(t.hub.replace(/\/$/,"")),i=Lr(),s=$e(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});da({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Pe(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as Bd,readFileSync as so,readdirSync as Md,writeFileSync as Gd}from"node:fs";import{dirname as Fd,join as cr,resolve as Hd}from"node:path";import{spawn as ed}from"node:child_process";import{existsSync as td}from"node:fs";var It=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},en=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},rd=5e3,nr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.signal?.aborted)throw new en;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 n=[],o=[],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=sd(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 C=h?.usage;C&&(a+=1,s.input+=oe(C.input_tokens),s.output+=oe(C.output_tokens),s.cacheRead+=oe(C.cache_read_input_tokens),s.cacheCreate+=oe(C.cache_creation_input_tokens))}}},f=e.role,p=e.onActivity,g=d=>{if(p)for(let h of cd(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 C=ed(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});C.stdout.setEncoding("utf-8"),C.stderr.setEncoding("utf-8");let S=!1,R=null,k=()=>{S=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),C.kill("SIGTERM"),R=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),C.kill("SIGKILL")},rd)};e.signal?.addEventListener("abort",k,{once:!0});let b=()=>{R&&clearTimeout(R),e.signal?.removeEventListener("abort",k)},_="";C.stdout.on("data",O=>{n.push(O),_+=O;let I;for(;(I=_.indexOf(`
443
+ `))!==-1;){let y=_.slice(0,I).trim();if(_=_.slice(I+1),y){let m=fa(y);u(m),m&&g(m)}}}),C.stderr.on("data",O=>{n.push(O),o.push(O);for(let I of O.split(`
444
+ `)){let y=I.trim();y&&console.warn(`[claude:stderr] ${y}`)}}),C.on("error",O=>{b(),h(O)}),C.on("close",O=>{if(b(),S){h(new en);return}if(_.trim()){let y=fa(_.trim());u(y),y&&g(y)}let I=i?.is_error===!0;if(O!==0||I){let y=typeof i?.api_error_status=="number"?i.api_error_status:void 0,m=typeof i?.subtype=="string"?i.subtype:void 0,v=typeof i?.result=="string"?i.result:void 0;h(new It(nd(O,i,o.join("")),{code:O,apiErrorStatus:y,subtype:m,resultText:v,retryAfterMs:od(i)}));return}console.log("[claude] exit code=0"),d({artifactPaths:[],log:n.join(""),usage:ad(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&td(n))}};function fa(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 n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${We(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=id(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let n=e.message;for(let o of n?.content??[])if(o.type==="tool_result")if(o.is_error===!0){let i=ga(o.content);console.log(`[claude] tool_result (error)${i?`: ${We(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${We(JSON.stringify(e),200)}`),e}function nd(t,e,r){let n=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let o=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;o?n.push(We(o,500)):typeof s=="string"&&s!=="success"&&n.push(s),typeof i=="number"&&n.push(`(api_status=${i})`)}return n.length===1&&r.trim()&&n.push(We(r.trim().split(`
445
445
  `).slice(-5).join(`
446
- `),500)),n.join(" \u2014 ")}function nd(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:"",n=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(r),o=n?Number(n[1]??n[2]):NaN;return Number.isFinite(o)&&o>0?o*1e3:void 0}function da(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function od(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=${We(r,80)}`}return""}function We(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function oe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function id(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=oe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:oe(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:n,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(o.surpassedThreshold=e.surpassedThreshold),o}function sd(t,e,r,n){let o=br(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=oe(i.input_tokens),o.outputTokens=oe(i.output_tokens),o.cacheReadInputTokens=oe(i.cache_read_input_tokens),o.cacheCreationInputTokens=oe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=oe(t?.total_cost_usd),o.numTurns=t&&oe(t.num_turns)>0?oe(t.num_turns):r,o.durationMs=oe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}var pa=200;function ad(t,e){let r=Date.now(),n=t.type;if(n==="system"){let o=String(t.subtype??"").trim();return o?[{ts:r,kind:"system",text:o}]:[]}if(n==="assistant"){let o=t.message,i=[];for(let s of o?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:We(c,pa)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,f=cd(u,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?We(da(s.content),pa):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(n==="result"){let o=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",...o?{text:o}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function cd(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 ld,writeFileSync as nr}from"node:fs";import{dirname as ud,join as or}from"node:path";function fa(t,e,r){let n=or(t,e);ld(ud(n),{recursive:!0}),nr(n,r)}var ir=class{name(){return"mock"}async run(e){let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=pd(n,o,i);nr(or(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;nr(or(e.workspaceDir,"SOLUTION.md"),dd(n,o,i,a)),s.push("SOLUTION.md"),nr(or(e.workspaceDir,"QUESTIONS.md"),fd(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;fa(e.workspaceDir,"changes/sample.patch",md(n,o,a)),s.push("changes/sample.patch"),fa(e.workspaceDir,"diff-summary.md",gd(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(nr(or(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
447
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:br()}}};function pd(t,e,r){return`# ${t} \u2014 Estimate
446
+ `),500)),n.join(" \u2014 ")}function od(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:"",n=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(r),o=n?Number(n[1]??n[2]):NaN;return Number.isFinite(o)&&o>0?o*1e3:void 0}function ga(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function id(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=${We(r,80)}`}return""}function We(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function oe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function sd(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=oe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:oe(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:n,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(o.surpassedThreshold=e.surpassedThreshold),o}function ad(t,e,r,n){let o=$r(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=oe(i.input_tokens),o.outputTokens=oe(i.output_tokens),o.cacheReadInputTokens=oe(i.cache_read_input_tokens),o.cacheCreationInputTokens=oe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=oe(t?.total_cost_usd),o.numTurns=t&&oe(t.num_turns)>0?oe(t.num_turns):r,o.durationMs=oe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}var ma=200;function cd(t,e){let r=Date.now(),n=t.type;if(n==="system"){let o=String(t.subtype??"").trim();return o?[{ts:r,kind:"system",text:o}]:[]}if(n==="assistant"){let o=t.message,i=[];for(let s of o?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:We(c,ma)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,f=ld(u,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?We(ga(s.content),ma):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(n==="result"){let o=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",...o?{text:o}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function ld(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 ud,writeFileSync as or}from"node:fs";import{dirname as pd,join as ir}from"node:path";function ha(t,e,r){let n=ir(t,e);ud(pd(n),{recursive:!0}),or(n,r)}var sr=class{name(){return"mock"}async run(e){let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=dd(n,o,i);or(ir(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;or(ir(e.workspaceDir,"SOLUTION.md"),fd(n,o,i,a)),s.push("SOLUTION.md"),or(ir(e.workspaceDir,"QUESTIONS.md"),md(n)),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",gd(n,o,a)),s.push("changes/sample.patch"),ha(e.workspaceDir,"diff-summary.md",hd(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(or(ir(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
447
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:$r()}}};function dd(t,e,r){return`# ${t} \u2014 Estimate
448
448
 
449
449
  **Title:** ${e}
450
450
 
@@ -465,7 +465,7 @@ production-grade estimates.)
465
465
  ${r.split(`
466
466
  `).slice(0,8).join(`
467
467
  `).trim()||"(empty)"}
468
- `}function dd(t,e,r,n){let o=n?`
468
+ `}function fd(t,e,r,n){let o=n?`
469
469
  ## Reviewer rework instruction
470
470
 
471
471
  > ${n.split(`
@@ -494,10 +494,10 @@ TBD (mock runner does not yet inspect project code).
494
494
  ${r.split(`
495
495
  `).slice(0,8).join(`
496
496
  `).trim()||"(empty)"}
497
- `}function fd(t){return`# ${t} \u2014 Open questions
497
+ `}function md(t){return`# ${t} \u2014 Open questions
498
498
 
499
499
  (none \u2014 mock runner did not surface ambiguities.)
500
- `}function md(t,e,r){let n=r?` (rework: ${r.split(`
500
+ `}function gd(t,e,r){let n=r?` (rework: ${r.split(`
501
501
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
502
502
  index 0000000..1111111 100644
503
503
  --- a/CHANGELOG.md
@@ -508,7 +508,7 @@ index 0000000..1111111 100644
508
508
  +- mock-runner placeholder change for slice 5 testing.
509
509
  +
510
510
  # Changelog
511
- `}function gd(t,e,r){return`# ${t} \u2014 Diff summary
511
+ `}function hd(t,e,r){return`# ${t} \u2014 Diff summary
512
512
 
513
513
  **Title:** ${e}
514
514
  ${r?`
@@ -519,82 +519,82 @@ ${r?`
519
519
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
520
520
 
521
521
  (Mock-runner output. Replace with claude-headless for production patches.)
522
- `}function ma(t){switch(t){case"mock":return new ir;case"claude-headless":return new rr;default:return null}}function ya(t=process.env){return{maxAttempts:Zr(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Zr(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Zr(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Zr(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var hd=new Set([429,500,502,503,529]),ga=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,yd=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,wd=new Set(["error_max_turns"]);function kd(t){if(t instanceof It){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return yd.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&wd.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:hd.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:ga.test(s)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:n??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return ga.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var ha=/(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 wa(t){if(t instanceof It){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&ha.test(n)}let e=t instanceof Error?t.message:String(t);return ha.test(e)}function bd(t,e,r){if(typeof r=="number"&&r>0)return Math.min(r,e.maxDelayMs);let n=e.baseDelayMs*2**(t-1),o=Math.min(n,e.maxDelayMs);return Math.round(o/2+Math.random()*(o/2))}async function ka(t,e,r){let n=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),o=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=kd(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=bd(s,r.policy,c.retryAfterMs);if(Date.now()+u>o)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 n(u)}}function Zr(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as $d,rmSync as xd,writeFileSync as ba}from"node:fs";import{tmpdir as vd}from"node:os";import{join as eo}from"node:path";function en(t){return`[url "https://${t}/"]
522
+ `}function ya(t){switch(t){case"mock":return new sr;case"claude-headless":return new nr;default:return null}}function ba(t=process.env){return{maxAttempts:tn(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:tn(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:tn(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:tn(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var yd=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,wd=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,kd=new Set(["error_max_turns"]);function bd(t){if(t instanceof It){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return wd.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&kd.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:yd.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:n??`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 ka=/(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 $a(t){if(t instanceof It){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&ka.test(n)}let e=t instanceof Error?t.message:String(t);return ka.test(e)}function $d(t,e,r){if(typeof r=="number"&&r>0)return Math.min(r,e.maxDelayMs);let n=e.baseDelayMs*2**(t-1),o=Math.min(n,e.maxDelayMs);return Math.round(o/2+Math.random()*(o/2))}async function xa(t,e,r){let n=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),o=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=bd(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=$d(s,r.policy,c.retryAfterMs);if(Date.now()+u>o)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 n(u)}}function tn(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as xd,rmSync as vd,writeFileSync as va}from"node:fs";import{tmpdir as Sd}from"node:os";import{join as to}from"node:path";function rn(t){return`[url "https://${t}/"]
523
523
  insteadOf = git@${t}:
524
524
  insteadOf = ssh://git@${t}/
525
- `}var Sd=en("github.com"),Cd=en("bitbucket.org"),Td=en("gitlab.com");function $a(t,e){if(t.length===0)return null;let r=$d(eo(vd(),"devpipe-gitcreds-")),n=eo(r,"credentials"),o=eo(r,"gitconfig");return ba(n,t.join(`
525
+ `}var Cd=rn("github.com"),Td=rn("bitbucket.org"),Rd=rn("gitlab.com");function Sa(t,e){if(t.length===0)return null;let r=xd(to(Sd(),"devpipe-gitcreds-")),n=to(r,"credentials"),o=to(r,"gitconfig");return va(n,t.join(`
526
526
  `)+`
527
- `,{mode:384}),ba(o,`[credential]
527
+ `,{mode:384}),va(o,`[credential]
528
528
  helper = store --file=${n}
529
- `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{xd(r,{recursive:!0,force:!0})}catch{}}}}function to(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Sd)),t.bitbucket?.apiToken&&(e.push(`https://${Ze}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Cd)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Td)),$a(e,r)}function xa(t,e){if(t.contextWrite?.token){let r=dt(e)??"github.com",n=xr(r);return $a([`https://${n}:${t.contextWrite.token}@${r}`],[en(r)])}return to(t)}import{spawn as Sa}from"node:child_process";import{existsSync as tn,mkdirSync as rn,readFileSync as Rd,rmSync as ro,symlinkSync as Id}from"node:fs";import{homedir as Pd}from"node:os";import{dirname as nn,join as at}from"node:path";function Ca(){return at(Pd(),".codepipe-sandbox","repos")}function va(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 Ta(t,e,r,n,o){if(tn(at(t,".git"))){let i=async s=>{await z(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],o),await z(t,["reset","--hard",`origin/${s}`],o),await z(t,["clean","-fdx"],o)};try{return await i(r),r}catch(s){if(!n||n===r||!va(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}}tn(t)&&ro(t,{recursive:!0,force:!0}),rn(nn(t),{recursive:!0});try{return await z(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(i){if(!n||n===r||!va(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),tn(t)&&ro(t,{recursive:!0,force:!0}),rn(nn(t),{recursive:!0}),await z(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}}async function Ra(t){await z(t.workspacePath,["reset","--hard",t.baseSha]),await z(t.workspacePath,["clean","-fdx"])}var on="CodePipe Agent",sn="codepipe@codepartner.ee";async function Ia(t,e){let r=t.workspacePath;await z(r,["add","-A"]);let n=(await $e(r,["write-tree"])).trim(),o=(await $e(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:on,GIT_AUTHOR_EMAIL:sn,GIT_COMMITTER_NAME:on,GIT_COMMITTER_EMAIL:sn};return(await $e(r,["commit-tree",n,"-m",e],i)).trim()}async function Pa(t,e,r,n,o){try{await z(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw dt(n)==="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 ja(t,e){return $e(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Ea(t,e,r,n,o){await z(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await z(t.workspacePath,["checkout","--force",r])}async function no(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:on,GIT_AUTHOR_EMAIL:sn,GIT_COMMITTER_NAME:on,GIT_COMMITTER_EMAIL:sn};(await $e(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await z(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await z(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await z(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await $e(n,["diff","--name-only","--diff-filter=U"])).split(`
530
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await $e(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function z(t,e,r){return new Promise((n,o)=>{let i=Sa("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",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
531
- ${s.join("").trim()||"(no stderr)"}`))})})}function $e(t,e,r){return new Promise((n,o)=>{let i=Sa("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",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
532
- ${a.join("").trim()||"(no stderr)"}`))})})}function Aa(t,e){tn(t)&&ro(t,{recursive:!0,force:!0}),rn(nn(t),{recursive:!0}),Id(e,t,"dir")}async function _a(t,e,r){await z(t,["worktree","prune"]).catch(()=>{}),rn(nn(r),{recursive:!0}),await z(t,["worktree","add","--detach",r,`origin/${e}`])}async function Oa(t,e,r,n="worktree",o){if(r.length===0)return[];let i=[];for(let s of r){let a=at(Ca(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await Ta(a,s.cloneUrl,s.ref,s.defaultBranch,o)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await $e(a,["rev-parse","HEAD"])).trim(),u=at(t,"code",s.name);n==="direct"?(Aa(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await _a(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 Na(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=at(Ca(),e,"_context");console.log(`[git] context: ensure ${r.cloneUrl} @ ${r.ref} \u2192 ${i}`);try{await Ta(i,r.cloneUrl,r.ref,void 0,o)}catch(c){throw new Error(`failed to materialize context repo (${r.cloneUrl}): `+(c instanceof Error?c.message:String(c)))}let s=at(t,"context");n==="direct"?(Aa(s,i),console.log(`[git] context: linked ${s} \u2192 ${i}`)):(await _a(i,r.ref,s),console.log(`[git] context: worktree ${s} \u2190 ${i}`));let a=(await $e(i,["rev-parse","HEAD"])).trim();return{workspacePath:s,cachePath:i,baseSha:a}}async function Ua(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await z(r,["add","-A",...n]).catch(()=>{});let o;try{o=await $e(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
533
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Rd(at(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as jd}from"node:fs";import{join as Ed}from"node:path";var oo=8*1024,Pt=class extends Error{},sr="meta/build-result.json";function La(t){let e=Ed(t,sr),r;try{r=jd(e,"utf-8")}catch{throw new Pt(`BUILD produced no ${sr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Pt(`${sr} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Pt(`${sr} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Pt(`${sr}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.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 o.logTail=="string"?Ad(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let u=a.find(f=>f.exitCode!==0);u&&(l.failedStep=u.name)}return l}function Ad(t){let e=Buffer.from(t,"utf-8");return e.length<=oo?t:`\u2026 [${e.length-oo} bytes elided] \u2026
534
- `+e.subarray(e.length-oo).toString("utf-8")}import{lstatSync as _d,mkdtempSync as Od,readFileSync as Nd,readdirSync as Ba,rmSync as Da}from"node:fs";import{tmpdir as Ud}from"node:os";import{join as an,relative as Ld}from"node:path";var Ma=new Set(["code","context"]);function Ga(t){let e=Od(an(Ud(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Da(e,{recursive:!0,force:!0}),listFiles:()=>Fa(e,e),readFile:r=>Nd(an(e,r),"utf-8"),clean:()=>{for(let r of Ba(e))Ma.has(r)||Da(an(e,r),{recursive:!0,force:!0})}}}function Fa(t,e){let r=[];for(let n of Ba(e)){let o=an(e,n),i=_d(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Ma.has(n))continue;r.push(...Fa(t,o))}else r.push(Ld(t,o))}return r}var cn=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Hd=new Set(["implement","resolve-conflict"]);function Kd(t){let e=Buffer.from(t,"utf-8");if(e.length<=cn)return t;let r=Math.floor(cn/4),n=cn-r,o=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-n).toString("utf-8"),s=e.length-r-n;return`${o}
529
+ `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{vd(r,{recursive:!0,force:!0})}catch{}}}}function ro(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Cd)),t.bitbucket?.apiToken&&(e.push(`https://${Ze}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Td)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Rd)),Sa(e,r)}function Ca(t,e){if(t.contextWrite?.token){let r=dt(e)??"github.com",n=vr(r);return Sa([`https://${n}:${t.contextWrite.token}@${r}`],[rn(r)])}return ro(t)}import{spawn as Ra}from"node:child_process";import{existsSync as nn,mkdirSync as on,readFileSync as Id,rmSync as no,symlinkSync as Pd}from"node:fs";import{homedir as Ed}from"node:os";import{dirname as sn,join as at}from"node:path";function Ia(){return at(Ed(),".codepipe-sandbox","repos")}function Ta(t){let e=t instanceof Error?t.message:String(t);return/couldn't find remote ref/i.test(e)||/Remote branch .* not found/i.test(e)||/unknown revision/i.test(e)}async function Pa(t,e,r,n,o){if(nn(at(t,".git"))){let i=async s=>{await z(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],o),await z(t,["reset","--hard",`origin/${s}`],o),await z(t,["clean","-fdx"],o)};try{return await i(r),r}catch(s){if(!n||n===r||!Ta(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}}nn(t)&&no(t,{recursive:!0,force:!0}),on(sn(t),{recursive:!0});try{return await z(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(i){if(!n||n===r||!Ta(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),nn(t)&&no(t,{recursive:!0,force:!0}),on(sn(t),{recursive:!0}),await z(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}}async function Ea(t){await z(t.workspacePath,["reset","--hard",t.baseSha]),await z(t.workspacePath,["clean","-fdx"])}var an="CodePipe Agent",cn="codepipe@codepartner.ee";async function ja(t,e){let r=t.workspacePath;await z(r,["add","-A"]);let n=(await xe(r,["write-tree"])).trim(),o=(await xe(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:an,GIT_AUTHOR_EMAIL:cn,GIT_COMMITTER_NAME:an,GIT_COMMITTER_EMAIL:cn};return(await xe(r,["commit-tree",n,"-m",e],i)).trim()}async function Aa(t,e,r,n,o){try{await z(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw dt(n)==="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 _a(t,e){return xe(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Oa(t,e,r,n,o){await z(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await z(t.workspacePath,["checkout","--force",r])}async function oo(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:an,GIT_AUTHOR_EMAIL:cn,GIT_COMMITTER_NAME:an,GIT_COMMITTER_EMAIL:cn};(await xe(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await z(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await z(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await z(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await xe(n,["diff","--name-only","--diff-filter=U"])).split(`
530
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await xe(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function z(t,e,r){return new Promise((n,o)=>{let i=Ra("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",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
531
+ ${s.join("").trim()||"(no stderr)"}`))})})}function xe(t,e,r){return new Promise((n,o)=>{let i=Ra("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",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
532
+ ${a.join("").trim()||"(no stderr)"}`))})})}function Na(t,e){nn(t)&&no(t,{recursive:!0,force:!0}),on(sn(t),{recursive:!0}),Pd(e,t,"dir")}async function Ua(t,e,r){await z(t,["worktree","prune"]).catch(()=>{}),on(sn(r),{recursive:!0}),await z(t,["worktree","add","--detach",r,`origin/${e}`])}async function La(t,e,r,n="worktree",o){if(r.length===0)return[];let i=[];for(let s of r){let a=at(Ia(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await Pa(a,s.cloneUrl,s.ref,s.defaultBranch,o)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await xe(a,["rev-parse","HEAD"])).trim(),u=at(t,"code",s.name);n==="direct"?(Na(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await Ua(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 Da(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=at(Ia(),e,"_context");console.log(`[git] context: ensure ${r.cloneUrl} @ ${r.ref} \u2192 ${i}`);try{await Pa(i,r.cloneUrl,r.ref,void 0,o)}catch(c){throw new Error(`failed to materialize context repo (${r.cloneUrl}): `+(c instanceof Error?c.message:String(c)))}let s=at(t,"context");n==="direct"?(Na(s,i),console.log(`[git] context: linked ${s} \u2192 ${i}`)):(await Ua(i,r.ref,s),console.log(`[git] context: worktree ${s} \u2190 ${i}`));let a=(await xe(i,["rev-parse","HEAD"])).trim();return{workspacePath:s,cachePath:i,baseSha:a}}async function Ba(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await z(r,["add","-A",...n]).catch(()=>{});let o;try{o=await xe(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
533
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Id(at(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as jd}from"node:fs";import{join as Ad}from"node:path";var io=8*1024,Pt=class extends Error{},ar="meta/build-result.json";function Ma(t){let e=Ad(t,ar),r;try{r=jd(e,"utf-8")}catch{throw new Pt(`BUILD produced no ${ar} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Pt(`${ar} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Pt(`${ar} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Pt(`${ar}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.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 o.logTail=="string"?_d(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let u=a.find(f=>f.exitCode!==0);u&&(l.failedStep=u.name)}return l}function _d(t){let e=Buffer.from(t,"utf-8");return e.length<=io?t:`\u2026 [${e.length-io} bytes elided] \u2026
534
+ `+e.subarray(e.length-io).toString("utf-8")}import{lstatSync as Od,mkdtempSync as Nd,readFileSync as Ud,readdirSync as Fa,rmSync as Ga}from"node:fs";import{tmpdir as Ld}from"node:os";import{join as ln,relative as Dd}from"node:path";var Ha=new Set(["code","context"]);function Ka(t){let e=Nd(ln(Ld(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Ga(e,{recursive:!0,force:!0}),listFiles:()=>Wa(e,e),readFile:r=>Ud(ln(e,r),"utf-8"),clean:()=>{for(let r of Fa(e))Ha.has(r)||Ga(ln(e,r),{recursive:!0,force:!0})}}}function Wa(t,e){let r=[];for(let n of Fa(e)){let o=ln(e,n),i=Od(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Ha.has(n))continue;r.push(...Wa(t,o))}else r.push(Dd(t,o))}return r}var un=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Kd=new Set(["implement","resolve-conflict"]);function Wd(t){let e=Buffer.from(t,"utf-8");if(e.length<=un)return t;let r=Math.floor(un/4),n=un-r,o=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-n).toString("utf-8"),s=e.length-r-n;return`${o}
535
535
 
536
- \u2026 [${s} bytes elided \u2014 log capped at ${cn} bytes for upload] \u2026
536
+ \u2026 [${s} bytes elided \u2014 log capped at ${un} bytes for upload] \u2026
537
537
 
538
- ${i}`}async function cr(t={}){Xr();let e=ee(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=Pr("SANDBOX_LOG","sandbox",Fd("./logs"));if(n.enabled){let h=new ht(n);jr(h),console.log(`[log] file logging \u2192 ${h.path} (rotate at ${n.maxBytes}B, keep ${n.maxFiles})`)}console.log(`codepipe-sandbox v${ce} (protocol ${he})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let o=ma(e.llm);console.log(`llm backend: ${o?o.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 Rt(e.hubUrl,e.token),a=!1,c=new AbortController,l=null,u=null,f=!1,p=null,g=null,d=!1,y=()=>{let h=s.openControlSocket();return p=h,h.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:ce,protocolVersion:he};h.send(JSON.stringify(m))}),h.on("message",m=>{let v=m.toString("utf-8"),x=null;try{let w=JSON.parse(v);w&&typeof w=="object"&&(x=w)}catch{}if(x&&x.type==="hello"){let w=x;g=wr(w.protocolVersion);let T=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${T}`),g&&(d=!1);return}if(x&&x.type==="pause_job"){let w=typeof x.jobId=="string"?x.jobId:"";w&&w===l?(console.warn(`[ws] pause_job ${w} \u2014 aborting agent`),f=!0,u?.abort()):console.log(`[ws] pause_job ${w} \u2014 not the active job, ignoring`),w&&h.send(JSON.stringify({type:"job_paused",jobId:w}));return}console.log(`[ws] ${v}`)}),h.on("close",(m,v)=>{console.log(`[ws] closed code=${m} reason=${v?.toString()||""}`),p===h&&(p=null),!a&&setTimeout(y,2e3)}),h.on("error",m=>console.warn(`[ws] error: ${m.message}`)),h},S=y(),C=async()=>{for(;!a;){if(g===!1){d||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ce}, protocol ${he}) \u2014 not claiming jobs until versions align.`),d=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await s.claim(c.signal);if(h.status===204)continue;if(h.status===401){console.error("[claim] 401 unauthorized \u2014 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(!h.ok){console.warn(`[claim] ${h.status} \u2014 backoff 5s`),await new Promise(v=>setTimeout(v,5e3));continue}let m=await h.json();await R(s,m)}catch(h){if(c.signal.aborted)break;let m=h instanceof Error?h.message:String(h);console.warn(`[claim] error: ${m} \u2014 backoff 5s`),await new Promise(v=>setTimeout(v,5e3))}}};async function R(h,m){l=m.jobId,u=new AbortController,f=!1;let v=!1,x=null,w=null,T=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),P=async()=>{try{await h.heartbeat(m.jobId)==="claim_lost"&&(v=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(M){let pe=M instanceof Error?M.message:String(M);console.warn(`[job] ${m.jobId} heartbeat error: ${pe}`)}};P();let U=setInterval(()=>{P()},T),ie=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(b(m.prompt," \u2502 "));let me=[],Je=null,j=400,ae=25,Ee=500,xe=()=>{if(Je&&(clearTimeout(Je),Je=null),me.length===0)return;let M=me.splice(0,me.length),pe=p;if(!pe||pe.readyState!==pe.OPEN)return;let Ae={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:M};try{pe.send(JSON.stringify(Ae))}catch{}},yn=M=>{me.push(M),me.length>Ee&&me.shift(),me.length>=ae?xe():Je||(Je=setTimeout(xe,j))},ze=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,V=new Set,wn=null;try{if(!o){v||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:ie,finishedAt:new Date().toISOString()});return}let M=Ga(m.jobId);console.log(`[job] ${m.jobId} workspace=${M.dir}`);let pe=k(m,r);x=pe.gitCreds,w=pe.contextGitCreds;let Ae=x?.env,To=pe.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:pe.claudeOauthToken}:void 0,_e=[],Gt=null,kn=null;try{let E="worktree";_e=await Oa(M.dir,m.projectId,m.projectRepos,E,Ae);let A=await Na(M.dir,m.projectId,m.contextRepo,E,Ae);kn=A,Gt=A?.workspacePath??null}catch(E){let A=E instanceof Error?E.message:String(E);console.warn(`[job] ${m.jobId} materialize failed: ${A}`),v||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${A}`},startedAt:ie,finishedAt:new Date().toISOString()}),M.dispose();return}let Ro=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let E=m.contextRepo?.cloneUrl;if(!E||!Ae)throw new Error(E?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let A of m.deliveries){let H=_e.find(se=>se.name===A.name);H&&(await Ea(H,A.deliveryRef,A.deliverySha,E,Ae),console.log(`[job] ${m.jobId} ${H.name}: checked out delivery ${A.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await Ro()}catch(E){let A=E instanceof Error?E.message:String(E);console.warn(`[job] ${m.jobId} delivery checkout failed: ${A}`),v||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${A}`},startedAt:ie,finishedAt:new Date().toISOString()}),M.dispose();return}let Io=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},Po="";if(m.role==="resolve-conflict")try{let E=[];for(let A of _e){let H=Io[A.name];if(!H)continue;let se=await no(A,H,Ae);console.log(`[job] ${m.jobId} ${A.name}: merged ${H} into ${A.ref} \u2014 ${se.length} conflicted file(s)`),se.length>0?E.push(`- **${A.name}**:`,...se.map(pt=>` - \`${pt}\``)):E.push(`- **${A.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Po=`
538
+ ${i}`}async function lr(t={}){Zr();let e=ee(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=Er("SANDBOX_LOG","sandbox",Hd("./logs"));if(n.enabled){let y=new ht(n);jr(y),console.log(`[log] file logging \u2192 ${y.path} (rotate at ${n.maxBytes}B, keep ${n.maxFiles})`)}console.log(`codepipe-sandbox v${ce} (protocol ${he})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let o=ya(e.llm);console.log(`llm backend: ${o?o.name():"(none \u2014 will not claim agent jobs)"}`);let i=ba();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new Rt(e.hubUrl,e.token),a=!1,c=new AbortController,l=null,u=null,f=!1,p=null,g=null,d=!1,h=()=>{let y=s.openControlSocket();return p=y,y.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:ce,protocolVersion:he};y.send(JSON.stringify(m))}),y.on("message",m=>{let v=m.toString("utf-8"),x=null;try{let w=JSON.parse(v);w&&typeof w=="object"&&(x=w)}catch{}if(x&&x.type==="hello"){let w=x;g=kr(w.protocolVersion);let T=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${T}`),g&&(d=!1);return}if(x&&x.type==="pause_job"){let w=typeof x.jobId=="string"?x.jobId:"";w&&w===l?(console.warn(`[ws] pause_job ${w} \u2014 aborting agent`),f=!0,u?.abort()):console.log(`[ws] pause_job ${w} \u2014 not the active job, ignoring`),w&&y.send(JSON.stringify({type:"job_paused",jobId:w}));return}console.log(`[ws] ${v}`)}),y.on("close",(m,v)=>{console.log(`[ws] closed code=${m} reason=${v?.toString()||""}`),p===y&&(p=null),!a&&setTimeout(h,2e3)}),y.on("error",m=>console.warn(`[ws] error: ${m.message}`)),y},C=h(),S=async()=>{for(;!a;){if(g===!1){d||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ce}, protocol ${he}) \u2014 not claiming jobs until versions align.`),d=!0),await new Promise(y=>setTimeout(y,5e3));continue}try{let y=await s.claim(c.signal);if(y.status===204)continue;if(y.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(!y.ok){console.warn(`[claim] ${y.status} \u2014 backoff 5s`),await new Promise(v=>setTimeout(v,5e3));continue}let m=await y.json();await R(s,m)}catch(y){if(c.signal.aborted)break;let m=y instanceof Error?y.message:String(y);console.warn(`[claim] error: ${m} \u2014 backoff 5s`),await new Promise(v=>setTimeout(v,5e3))}}};async function R(y,m){l=m.jobId,u=new AbortController,f=!1;let v=!1,x=null,w=null,T=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),P=async()=>{try{await y.heartbeat(m.jobId)==="claim_lost"&&(v=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(M){let pe=M instanceof Error?M.message:String(M);console.warn(`[job] ${m.jobId} heartbeat error: ${pe}`)}};P();let U=setInterval(()=>{P()},T),ie=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(b(m.prompt," \u2502 "));let me=[],Je=null,E=400,ae=25,je=500,ve=()=>{if(Je&&(clearTimeout(Je),Je=null),me.length===0)return;let M=me.splice(0,me.length),pe=p;if(!pe||pe.readyState!==pe.OPEN)return;let Ae={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:M};try{pe.send(JSON.stringify(Ae))}catch{}},kn=M=>{me.push(M),me.length>je&&me.shift(),me.length>=ae?ve():Je||(Je=setTimeout(ve,E))},ze=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,V=new Set,bn=null;try{if(!o){v||await y.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:ie,finishedAt:new Date().toISOString()});return}let M=Ka(m.jobId);console.log(`[job] ${m.jobId} workspace=${M.dir}`);let pe=k(m,r);x=pe.gitCreds,w=pe.contextGitCreds;let Ae=x?.env,Ro=pe.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:pe.claudeOauthToken}:void 0,_e=[],Gt=null,$n=null;try{let j="worktree";_e=await La(M.dir,m.projectId,m.projectRepos,j,Ae);let A=await Da(M.dir,m.projectId,m.contextRepo,j,Ae);$n=A,Gt=A?.workspacePath??null}catch(j){let A=j instanceof Error?j.message:String(j);console.warn(`[job] ${m.jobId} materialize failed: ${A}`),v||await y.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${A}`},startedAt:ie,finishedAt:new Date().toISOString()}),M.dispose();return}let Io=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let j=m.contextRepo?.cloneUrl;if(!j||!Ae)throw new Error(j?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let A of m.deliveries){let H=_e.find(se=>se.name===A.name);H&&(await Oa(H,A.deliveryRef,A.deliverySha,j,Ae),console.log(`[job] ${m.jobId} ${H.name}: checked out delivery ${A.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await Io()}catch(j){let A=j instanceof Error?j.message:String(j);console.warn(`[job] ${m.jobId} delivery checkout failed: ${A}`),v||await y.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${A}`},startedAt:ie,finishedAt:new Date().toISOString()}),M.dispose();return}let Po=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},Eo="";if(m.role==="resolve-conflict")try{let j=[];for(let A of _e){let H=Po[A.name];if(!H)continue;let se=await oo(A,H,Ae);console.log(`[job] ${m.jobId} ${A.name}: merged ${H} into ${A.ref} \u2014 ${se.length} conflicted file(s)`),se.length>0?j.push(`- **${A.name}**:`,...se.map(pt=>` - \`${pt}\``)):j.push(`- **${A.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Eo=`
539
539
 
540
540
  ## Conflicts to resolve
541
541
 
542
- `+(E.length>0?E.join(`
542
+ `+(j.length>0?j.join(`
543
543
  `):"(no task branches to merge)")+`
544
- `}catch(E){let A=E instanceof Error?E.message:String(E);console.warn(`[job] ${m.jobId} conflict merge failed: ${A}`),v||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${A}`},startedAt:ie,finishedAt:new Date().toISOString()}),M.dispose();return}let rl=O(_(m.prompt,_e,Gt),Gt,m.taskId)+Po,bn=[..._e.map(E=>E.workspacePath),...Gt?[Gt]:[]];bn.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${bn.join(", ")}`),ze&&(wn=setInterval(()=>{let A=p;if(!A||A.readyState!==A.OPEN)return;let H;try{H=Bd(ar(M.dir,"drafts")).filter(se=>se.endsWith(".json")).sort()}catch{return}for(let se of H){if(V.has(se))continue;if(V.size>=Lo)break;let pt;try{let ne=JSON.parse(io(ar(M.dir,"drafts",se),"utf-8")),D=typeof ne.localRef=="string"?ne.localRef:"",J=typeof ne.title=="string"?ne.title:"",Xe=typeof ne.body=="string"?ne.body:"";if(!D||!J)continue;pt={localRef:D,title:J,body:Xe,...ne.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ne.links)?{links:ne.links}:{}}}catch{continue}V.add(se);let Ft={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:ze,child:pt};try{A.send(JSON.stringify(Ft))}catch{}}},1500));try{let E=await ka(o,{workspaceDir:M.dir,role:m.role,prompt:rl,addDirs:bn,metadata:m.metadata??{},...m.model?{model:m.model}:{},...To?{env:To}:{},signal:u.signal,onActivity:yn},{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{M.clean();for(let D of _e)try{await Ra(D);let J=Io[D.name];m.role==="resolve-conflict"&&J&&await no(D,J,Ae)}catch(J){let Xe=J instanceof Error?J.message:String(J);console.warn(`[job] ${m.jobId} worktree reset failed (${D.name}): ${Xe}`)}try{await Ro()}catch(D){let J=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${J}`)}},aborted:()=>v||f}),A=[];if(Hd.has(m.role)&&_e.length>0){let D=m.metadata??{},J=typeof D.commitMessage=="string"?D.commitMessage:`${m.taskId}: changes`,Xe=m.contextRepo?.cloneUrl,jo=w?.env;if(!Xe||!jo)throw new Error("delivery requested but "+(Xe?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let nl=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let ve of _e){let Ht=await Ia(ve,J);if(!Ht){console.log(`[job] ${m.jobId} ${ve.name}: no changes \u2014 no delivery`);continue}let $n=`codepipe/deliveries/${nl}/${m.jobId}/${ve.name}`;await Pa(ve,Ht,$n,Xe,jo),A.push({name:ve.name,deliveryRef:$n,deliverySha:Ht,baseSha:ve.baseSha}),console.log(`[job] ${m.jobId} ${ve.name}: delivered ${Ht.slice(0,10)} \u2192 ${$n}`);let Eo=await ja(ve,Ht);if(Eo.trim().length>0){let ol=ar("display",`${ve.name}.diff`),Ao=ar(M.dir,ol);Dd(Gd(Ao),{recursive:!0}),Md(Ao,Eo)}}}if(m.role==="resolve-conflict"&&A.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 H;m.role==="build"&&(H=La(M.dir),console.log(`[job] ${m.jobId} build verdict: ok=${H.ok}`+(H.failedStep?` failedStep=${H.failedStep}`:"")));let se=E.artifactPaths.length>0?E.artifactPaths:M.listFiles(),pt=Array.from(new Set(se)),Ft;if(kn)try{let D=await Ua(kn,m.role==="index"?["adr/SOURCES.md"]:[]);D.length>0&&(Ft=D,console.log(`[job] ${m.jobId} captured ${D.length} knowledge file(s) for Context Repo`))}catch(D){let J=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${J}`)}let ne={jobId:m.jobId,status:"succeeded",artifacts:pt.map(D=>({path:D,contentBase64:io(`${M.dir}/${D}`).toString("base64")})),...Ft?{contextWrites:Ft}:{},...A.length>0?{deliveries:A}:{},log:Kd(E.log),startedAt:ie,finishedAt:new Date().toISOString(),usage:E.usage,...E.rateLimit?{rateLimit:E.rateLimit}:{},...H?{build:H}:{}};if(v||f)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${f?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await h.submitResult(ne),console.log(`[job] ${m.jobId} done \u2014 uploaded ${ne.artifacts.length} artifact(s):`);for(let D of ne.artifacts){let J=Buffer.from(D.contentBase64,"base64").length;console.log(` \xB7 ${D.path} (${J} bytes)`)}ne.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(E){let A=E instanceof Error?E.message:String(E);if(f)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(v)console.warn(`[job] ${m.jobId} failed after claim lost (${A}) \u2014 skipping result upload`);else{let H=wa(E);console.warn(H?`[job] ${m.jobId} failed: ${A} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${A}`),await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:A},startedAt:ie,finishedAt:new Date().toISOString(),...H?{authError:!0}:{}})}}finally{M.dispose()}}finally{clearInterval(U),wn&&clearInterval(wn),xe(),l=null,u=null,x?.cleanup(),w?.cleanup()}}function k(h,m){if(!h.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${h.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let v;try{v=JSON.parse(Ur(m,h.credBundle).toString("utf-8"))}catch(P){return console.warn(`[job] ${h.jobId} failed to open credBundle: ${P instanceof Error?P.message:String(P)}`),{gitCreds:null,contextGitCreds:null}}let x=to(v);x&&console.log(`[job] ${h.jobId} cred bundle opened \u2014 git creds configured`);let w=xa(v,h.contextRepo.cloneUrl),T={gitCreds:x,contextGitCreds:w};return v.claudeOauthToken&&(T.claudeOauthToken=v.claudeOauthToken),T}function b(h,m){return h.split(`
544
+ `}catch(j){let A=j instanceof Error?j.message:String(j);console.warn(`[job] ${m.jobId} conflict merge failed: ${A}`),v||await y.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${A}`},startedAt:ie,finishedAt:new Date().toISOString()}),M.dispose();return}let il=O(_(m.prompt,_e,Gt),Gt,m.taskId)+Eo,xn=[..._e.map(j=>j.workspacePath),...Gt?[Gt]:[]];xn.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${xn.join(", ")}`),ze&&(bn=setInterval(()=>{let A=p;if(!A||A.readyState!==A.OPEN)return;let H;try{H=Md(cr(M.dir,"drafts")).filter(se=>se.endsWith(".json")).sort()}catch{return}for(let se of H){if(V.has(se))continue;if(V.size>=Do)break;let pt;try{let ne=JSON.parse(so(cr(M.dir,"drafts",se),"utf-8")),D=typeof ne.localRef=="string"?ne.localRef:"",J=typeof ne.title=="string"?ne.title:"",Xe=typeof ne.body=="string"?ne.body:"";if(!D||!J)continue;pt={localRef:D,title:J,body:Xe,...ne.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ne.links)?{links:ne.links}:{}}}catch{continue}V.add(se);let Ft={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:ze,child:pt};try{A.send(JSON.stringify(Ft))}catch{}}},1500));try{let j=await xa(o,{workspaceDir:M.dir,role:m.role,prompt:il,addDirs:xn,metadata:m.metadata??{},...m.model?{model:m.model}:{},...Ro?{env:Ro}:{},signal:u.signal,onActivity:kn},{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{M.clean();for(let D of _e)try{await Ea(D);let J=Po[D.name];m.role==="resolve-conflict"&&J&&await oo(D,J,Ae)}catch(J){let Xe=J instanceof Error?J.message:String(J);console.warn(`[job] ${m.jobId} worktree reset failed (${D.name}): ${Xe}`)}try{await Io()}catch(D){let J=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${J}`)}},aborted:()=>v||f}),A=[];if(Kd.has(m.role)&&_e.length>0){let D=m.metadata??{},J=typeof D.commitMessage=="string"?D.commitMessage:`${m.taskId}: changes`,Xe=m.contextRepo?.cloneUrl,jo=w?.env;if(!Xe||!jo)throw new Error("delivery requested but "+(Xe?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let sl=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let Se of _e){let Ht=await ja(Se,J);if(!Ht){console.log(`[job] ${m.jobId} ${Se.name}: no changes \u2014 no delivery`);continue}let vn=`codepipe/deliveries/${sl}/${m.jobId}/${Se.name}`;await Aa(Se,Ht,vn,Xe,jo),A.push({name:Se.name,deliveryRef:vn,deliverySha:Ht,baseSha:Se.baseSha}),console.log(`[job] ${m.jobId} ${Se.name}: delivered ${Ht.slice(0,10)} \u2192 ${vn}`);let Ao=await _a(Se,Ht);if(Ao.trim().length>0){let al=cr("display",`${Se.name}.diff`),_o=cr(M.dir,al);Bd(Fd(_o),{recursive:!0}),Gd(_o,Ao)}}}if(m.role==="resolve-conflict"&&A.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 H;m.role==="build"&&(H=Ma(M.dir),console.log(`[job] ${m.jobId} build verdict: ok=${H.ok}`+(H.failedStep?` failedStep=${H.failedStep}`:"")));let se=j.artifactPaths.length>0?j.artifactPaths:M.listFiles(),pt=Array.from(new Set(se)),Ft;if($n)try{let D=await Ba($n,m.role==="index"?["adr/SOURCES.md"]:[]);D.length>0&&(Ft=D,console.log(`[job] ${m.jobId} captured ${D.length} knowledge file(s) for Context Repo`))}catch(D){let J=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${J}`)}let ne={jobId:m.jobId,status:"succeeded",artifacts:pt.map(D=>({path:D,contentBase64:so(`${M.dir}/${D}`).toString("base64")})),...Ft?{contextWrites:Ft}:{},...A.length>0?{deliveries:A}:{},log:Wd(j.log),startedAt:ie,finishedAt:new Date().toISOString(),usage:j.usage,...j.rateLimit?{rateLimit:j.rateLimit}:{},...H?{build:H}:{}};if(v||f)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${f?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await y.submitResult(ne),console.log(`[job] ${m.jobId} done \u2014 uploaded ${ne.artifacts.length} artifact(s):`);for(let D of ne.artifacts){let J=Buffer.from(D.contentBase64,"base64").length;console.log(` \xB7 ${D.path} (${J} bytes)`)}ne.artifacts.length===0&&console.warn(`[job] ${m.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(j){let A=j instanceof Error?j.message:String(j);if(f)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(v)console.warn(`[job] ${m.jobId} failed after claim lost (${A}) \u2014 skipping result upload`);else{let H=$a(j);console.warn(H?`[job] ${m.jobId} failed: ${A} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${A}`),await y.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:A},startedAt:ie,finishedAt:new Date().toISOString(),...H?{authError:!0}:{}})}}finally{M.dispose()}}finally{clearInterval(U),bn&&clearInterval(bn),ve(),l=null,u=null,x?.cleanup(),w?.cleanup()}}function k(y,m){if(!y.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${y.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let v;try{v=JSON.parse(Dr(m,y.credBundle).toString("utf-8"))}catch(P){return console.warn(`[job] ${y.jobId} failed to open credBundle: ${P instanceof Error?P.message:String(P)}`),{gitCreds:null,contextGitCreds:null}}let x=ro(v);x&&console.log(`[job] ${y.jobId} cred bundle opened \u2014 git creds configured`);let w=Ca(v,y.contextRepo.cloneUrl),T={gitCreds:x,contextGitCreds:w};return v.claudeOauthToken&&(T.claudeOauthToken=v.claudeOauthToken),T}function b(y,m){return y.split(`
545
545
  `).map(v=>m+v).join(`
546
- `)}function _(h,m,v){let x=m[0]?.workspacePath??"";return h.replace(/\{\{codeDir\}\}/g,x).replace(/\{\{codeRoot\}\}/g,x?x.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,v??"")}function O(h,m,v){let x=h,w=v.includes("::")?"":v.split(":",2)[1]??"",T=P=>{if(!m||!w)return"";try{return io(ar(m,"tasks",w,P),"utf-8").trim()}catch{return""}};if(x.includes("{{solutionMd}}")){let P=T("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";x=x.replace(/\{\{solutionMd\}\}/g,()=>P)}if(x.includes("{{taskDescription}}")){let P=T("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";x=x.replace(/\{\{taskDescription\}\}/g,()=>P)}return x}let I=h=>{if(a)return;a=!0,console.log(`
547
- [${h}] shutting down`),c.abort();let m=new AbortController,v=setTimeout(()=>m.abort(),3e3);(async()=>{let x=l;if(x)try{await s.releaseJob(x,`sandbox ${h}`,m.signal),console.log(`[${h}] released job ${x}`)}catch(w){let T=w instanceof Error?w.message:String(w);console.warn(`[${h}] release failed: ${T} (sweeper will reclaim)`)}clearTimeout(v),S.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>I("SIGINT")),process.on("SIGTERM",()=>I("SIGTERM")),await C()}async function Ha(t={profile:void 0}){let e=Ne(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Hr(e.hubUrl,e.cliToken),n=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 n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await Q(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ee(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as ff}from"node:child_process";import{existsSync as _t,mkdirSync as cc,readFileSync as lc,readdirSync as mf,writeFileSync as uc}from"node:fs";import{join as ct,resolve as pc}from"node:path";import{setTimeout as lo}from"node:timers/promises";import{cancel as gf,confirm as Ot,intro as dc,isCancel as fo,log as $,outro as uo,password as Nt,select as lt,spinner as fc,text as Y}from"@clack/prompts";import{simpleGit as pn}from"simple-git";async function Et(t,e,r){return e.host==="github"?Yd(t,e,r):e.host==="gitlab"?Zd(t,e,r):tf(t,e,r)}async function Ka(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await qe(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Wa(e.githubToken,t):o}:{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 Ye(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ya(e.gitlabToken,t):o}}return e.bitbucket?(await jt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await qa(e.bitbucket,t):o}:{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 Wa(t,e){let r=!1;try{r=(await qe(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 Ya(t,e){let r=!1;try{r=(await Ye(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 qa(t,e){let r=!1;try{r=(await jt(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 Wd="https://api.github.com";async function qe(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(Wd+r,o),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 Yd(t,e,r){let n=r.githubToken;if(!n)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 o=await qd(n,e,r),i=await Jd(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=$t(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await zd(n,o.owner,o.name,a.path,i)||await Xd(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:i}}async function qd(t,e,r){let n=await qe(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await Wa(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Vd(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await qe(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 Vd(t,e){let{status:r,data:n}=await qe(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Jd(t,e,r){let{data:n}=await qe(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function zd(t,e,r,n,o){let{status:i,data:s}=await qe(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Xd(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await qe(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var Qd="https://gitlab.com/api/v4";async function Ye(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(Qd+r,o),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 Zd(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Ye(n,"GET",`/projects/${o}`);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 Ya(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Ye(n,"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 Ye(n,"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 Ye(n,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=$t(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let g=(await Ye(n,"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 Ye(n,"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 ef="https://api.bitbucket.org/2.0";async function jt(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let i=await fetch(ef+r,o),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 tf(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await jt(n,"GET",o);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 qa(n,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 jt(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=f.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=$t(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await jt(n,"GET",`${o}/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 jt(n,"POST",`${o}/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 rf={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function je(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=rf[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as nf}from"node:crypto";import{existsSync as Va,mkdirSync as of,readFileSync as Ja,readdirSync as sf,rmSync as ln,writeFileSync as af}from"node:fs";import{homedir as cf}from"node:os";import{dirname as lf,join as so}from"node:path";var uf=24*60*60*1e3;function za(){return so(cf(),".codepipe","init-drafts")}function ao(t){let e=nf("sha256").update(t).digest("hex").slice(0,16);return so(za(),`${e}.json`)}function Xa(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=uf)}function Qa(t){let e=ao(t);if(!Va(e))return null;try{let r=JSON.parse(Ja(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Xa(r.savedAt)?(ln(e,{force:!0}),null):r}catch{return null}}function co(t){ln(ao(t),{force:!0})}function Za(){let t=za();if(Va(t))for(let e of sf(t)){let r=so(t,e);try{let n=JSON.parse(Ja(r,"utf-8"));Xa(n.savedAt)&&ln(r,{force:!0})}catch{ln(r,{force:!0})}}}var At=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 n=await r();return this.set(e,n),n}clear(){co(this.cwd)}persist(){let e=ao(this.cwd);of(lf(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};af(e,JSON.stringify(r,null,2)+`
548
- `,{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 tc(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 rc}from"node:fs";import{join as nc}from"node:path";import{simpleGit as oc}from"simple-git";var pf={info:t=>console.log(t),warn:t=>console.warn(t)};async function lr(t,e,r={}){let n=r.log??pf,o=[];for(let i of e){let s=nc(t,i.mountAs),a=Go(i);if(!rc(s)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${i.mountAs}/`),await oc().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let f=u instanceof Error?u.message:String(u);n.warn(`clone failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!rc(nc(s,".git"))){n.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=oc(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!df(l,a)){n.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let f=u instanceof Error?u.message:String(u);n.warn(`fetch failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}}return o}function df(t,e){return ic(t)===ic(e)}function ic(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function sc(t={}){let e=tt();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 lr(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let n of r)console.log(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}var ac=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function F(t){gf(t),process.exit(1)}function le(t){return fo(t)&&F("aborted"),t}function G(t){return fo(t)&&F("aborted"),typeof t=="string"?t:""}async function mc(t={}){dc("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Za();let r=Qa(e),n,o=!1;r&&Object.keys(r.answers).length>0?le(await Ot({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?($.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new At(e,r),o=!0):(co(e),n=new At(e)):n=new At(e);let i=t.force===!0?null:await mo(e),s=await n.ask("target",async()=>le(await lt({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?$.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)`):o&&n.get("contextRepo")!==void 0||hc(e,t.force===!0));let c=await n.ask("hubUrl",async()=>G(await Y({message:"HUB URL",placeholder:ge,initialValue:L("HUB_URL")??ge,validate:j=>j.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>dn()),{cliToken:u,accountEmail:f}=await n.ask("bootstrap",()=>fn(c,l)),p=null;s==="farm"&&(p=await hf(c,u));let g=a?wf(a.parsed.repoName):"",d=await n.ask("projectId",async()=>G(await Y({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:j=>Qe.test(j.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>G(await Y({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:j=>j.trim().length>0?void 0:"required"})).trim()),S=await n.ask("automationLevel",async()=>le(await lt({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"}))),C=await n.ask("youtrack",()=>vc()),R=await n.ask("youtrackProjectKey",async()=>G(await Y({message:"YouTrack project key",placeholder:"DEV",validate:j=>j.trim().length>0?void 0:"required"})).trim()),k=await n.ask("youtrackWrites",async()=>le(await Ot({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),b=n.get("tokens")??{},_=()=>n.set("tokens",b),O=await n.ask("repos",()=>xf(b,l,a,{onCred:_,initial:n.get("reposPartial")??[],onProgress:j=>n.set("reposPartial",j)}));n.delete("reposPartial");let I=await vf(await n.ask("contextRepo",()=>bc(d,O,b,l)),d,O,b,l,_,j=>n.set("contextRepo",j)),{spec:h,mode:m}=I;$.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let v=await n.ask("assigneeLogin",async()=>G(await Y({message:"your YouTrack login (the assignee value)",...C.login?{initialValue:C.login}:{},validate:j=>j.trim().length>0?void 0:"required"})).trim()),x=await n.ask("claudeToken",()=>jf(s==="farm")),w={projectId:d,name:y,automationLevel:S,repos:O,youtrackProjectKey:R,ownerEmail:f};$.step(`${m==="attach"?"attaching to":"provisioning"} Context Repo ${h.owner}/${h.name} (${h.host})\u2026`);let T;try{T=await Et(w,h,{...$c(b),youtrackWrites:k,trackerUrl:C.url,mode:m,log:{info:j=>$.message(j),warn:j=>$.warn(j)}})}catch(j){F(`Context Repo provisioning failed: ${j instanceof Error?j.message:String(j)}`)}w.contextRepo=T,$.success(`Context Repo ready: ${T.owner}/${T.name}@${T.branch}`),$.step(`registering project on ${c}\u2026`);let P;try{P=await St(c,u,w)}catch(j){if(j instanceof N&&j.status===409){$.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{P=await Q(c,u,d)}catch(ae){throw ae instanceof N&&F(`HUB \u2192 ${ae.status} ${ae.message}`),ae}}else if(j instanceof N&&j.status===401)n.delete("cliToken"),F("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(j instanceof N)F(`HUB \u2192 ${j.status} ${j.message}`);else throw j}let U=P.contextRepo??T;$.success(`project ${P.projectId} ready (${P.provisioningStatus})`);let ie=await If(U),me={url:C.url,token:C.token};if(s==="farm"){let j=p,ae={...b,...ie?{contextWrite:ie}:{},...x?{claude:{oauthToken:x}}:{},youtrack:me},Ee=b.github?.token;if(U.host==="github"&&Ee)try{let V=Xs(`devpipe-${d}`);await Qs(U,Ee,V.publicKey,`devpipe-${d}`),ae.contextSsh={privateKey:V.privateKey},$.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(V){$.warn(`could not set up Context Repo SSH deploy key (${V instanceof Error?V.message:String(V)}); the farm will fall back to the token path.`)}let xe={projectId:d,config:{hubUrl:c,cliToken:u,projectId:d},secrets:ae,contextRepo:U,projectConfig:ke(w,k,C.url,v||void 0)},yn=xt(j.farm.publicKey,JSON.stringify(xe));$.step(`handing project ${d} to farm ${j.farm.name}\u2026`);let ze;try{ze=await Kr(c,u,j.farm.farmId,{projectId:d,sealedBundle:yn})}catch(V){throw V instanceof N&&F(V.status===409?`farm ${j.farm.name} is offline \u2014 start it and re-run.`:V.status===504?`farm ${j.farm.name} did not respond in time.`:`HUB \u2192 ${V.status} ${V.message}`),V}ze.ok||F(`farm rejected provisioning: ${ze.error??"unknown error"}`),await po(c,u,d,U,Ee),n.clear(),uo(`done. project ${d} is now hosted on farm ${j.farm.name} (daemon ${ze.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}xc(b),await yc(e,U.cloneUrl,U.branch),kc(e),a&&await bf(e);{let j=ct(e,ye);kt(j);let ae=ke(w,k,C.url,v||void 0),Ee=Yt(j,ae);Ee.length>0&&$.success(`local project config \u2192 .codepipe/{${Ee.join(", ")}}`),ot(d,ae,{info:xe=>$.message(xe),warn:xe=>$.warn(xe)})}await wc(e,P.repos);let Je={hubUrl:c,cliToken:u,projectId:d,...b,...ie?{contextWrite:ie}:{},...x?{claude:{oauthToken:x}}:{},youtrack:me};W(Je),rt({hubUrl:c,cliToken:u,projectId:d,accountEmail:f},d),$.success(`secrets \u2192 ${nt(d)}`),await po(c,u,d,U,b.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),n.clear(),uo("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function po(t,e,r,n,o){let i=await tc(n,o),s=ec(i),a=await lt({message:s.message,options:s.options,initialValue:s.initialValue});if(!(fo(a)||a!==s.proceedValue))try{let{jobId:c}=await Yr(t,e,r,{reindex:s.reindex});$.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){$.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function hf(t,e){let r;try{r=await Ps(t,e)}catch(c){throw c instanceof N&&F(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&F("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 o=le(await lt({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=Fr(i.farmId,i.publicKey)}catch(c){F(c instanceof Error?c.message:String(c))}return le(await Ot({message:`confirm farm ${i.name} cred-channel fingerprint:
546
+ `)}function _(y,m,v){let x=m[0]?.workspacePath??"";return y.replace(/\{\{codeDir\}\}/g,x).replace(/\{\{codeRoot\}\}/g,x?x.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,v??"")}function O(y,m,v){let x=y,w=v.includes("::")?"":v.split(":",2)[1]??"",T=P=>{if(!m||!w)return"";try{return so(cr(m,"tasks",w,P),"utf-8").trim()}catch{return""}};if(x.includes("{{solutionMd}}")){let P=T("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";x=x.replace(/\{\{solutionMd\}\}/g,()=>P)}if(x.includes("{{taskDescription}}")){let P=T("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";x=x.replace(/\{\{taskDescription\}\}/g,()=>P)}return x}let I=y=>{if(a)return;a=!0,console.log(`
547
+ [${y}] shutting down`),c.abort();let m=new AbortController,v=setTimeout(()=>m.abort(),3e3);(async()=>{let x=l;if(x)try{await s.releaseJob(x,`sandbox ${y}`,m.signal),console.log(`[${y}] released job ${x}`)}catch(w){let T=w instanceof Error?w.message:String(w);console.warn(`[${y}] release failed: ${T} (sweeper will reclaim)`)}clearTimeout(v),C.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>I("SIGINT")),process.on("SIGTERM",()=>I("SIGTERM")),await S()}async function Ya(t={profile:void 0}){let e=Ne(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Wr(e.hubUrl,e.cliToken),n=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 n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await Q(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ee(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as mf}from"node:child_process";import{existsSync as _t,mkdirSync as pc,readFileSync as dc,readdirSync as gf,writeFileSync as fc}from"node:fs";import{join as ct,resolve as mc}from"node:path";import{setTimeout as uo}from"node:timers/promises";import{cancel as hf,confirm as Ot,intro as gc,isCancel as mo,log as $,outro as po,password as Nt,select as lt,spinner as hc,text as Y}from"@clack/prompts";import{simpleGit as fn}from"simple-git";async function jt(t,e,r){return e.host==="github"?qd(t,e,r):e.host==="gitlab"?ef(t,e,r):rf(t,e,r)}async function qa(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await qe(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Va(e.githubToken,t):o}:{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 Ye(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ja(e.gitlabToken,t):o}}return e.bitbucket?(await Et(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await za(e.bitbucket,t):o}:{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 Va(t,e){let r=!1;try{r=(await qe(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 Ja(t,e){let r=!1;try{r=(await Ye(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 za(t,e){let r=!1;try{r=(await Et(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 Yd="https://api.github.com";async function qe(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(Yd+r,o),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 qd(t,e,r){let n=r.githubToken;if(!n)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 o=await Vd(n,e,r),i=await zd(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=$t(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Xd(n,o.owner,o.name,a.path,i)||await Qd(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:i}}async function Vd(t,e,r){let n=await qe(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await Va(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Jd(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await qe(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 Jd(t,e){let{status:r,data:n}=await qe(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function zd(t,e,r){let{data:n}=await qe(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Xd(t,e,r,n,o){let{status:i,data:s}=await qe(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Qd(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await qe(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var Zd="https://gitlab.com/api/v4";async function Ye(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(Zd+r,o),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 ef(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Ye(n,"GET",`/projects/${o}`);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 Ja(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Ye(n,"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 Ye(n,"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 Ye(n,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=$t(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let g=(await Ye(n,"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 Ye(n,"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 tf="https://api.bitbucket.org/2.0";async function Et(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let i=await fetch(tf+r,o),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 rf(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await Et(n,"GET",o);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 za(n,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 Et(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=f.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=$t(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await Et(n,"GET",`${o}/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 Et(n,"POST",`${o}/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 nf={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function Ee(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=nf[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as of}from"node:crypto";import{existsSync as Xa,mkdirSync as sf,readFileSync as Qa,readdirSync as af,rmSync as pn,writeFileSync as cf}from"node:fs";import{homedir as lf}from"node:os";import{dirname as uf,join as ao}from"node:path";var pf=24*60*60*1e3;function Za(){return ao(lf(),".codepipe","init-drafts")}function co(t){let e=of("sha256").update(t).digest("hex").slice(0,16);return ao(Za(),`${e}.json`)}function ec(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=pf)}function tc(t){let e=co(t);if(!Xa(e))return null;try{let r=JSON.parse(Qa(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:ec(r.savedAt)?(pn(e,{force:!0}),null):r}catch{return null}}function lo(t){pn(co(t),{force:!0})}function rc(){let t=Za();if(Xa(t))for(let e of af(t)){let r=ao(t,e);try{let n=JSON.parse(Qa(r,"utf-8"));ec(n.savedAt)&&pn(r,{force:!0})}catch{pn(r,{force:!0})}}}var At=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 n=await r();return this.set(e,n),n}clear(){lo(this.cwd)}persist(){let e=co(this.cwd);sf(uf(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};cf(e,JSON.stringify(r,null,2)+`
548
+ `,{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 oc(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 ic}from"node:fs";import{join as sc}from"node:path";import{simpleGit as ac}from"simple-git";var df={info:t=>console.log(t),warn:t=>console.warn(t)};async function ur(t,e,r={}){let n=r.log??df,o=[];for(let i of e){let s=sc(t,i.mountAs),a=Fo(i);if(!ic(s)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${i.mountAs}/`),await ac().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let f=u instanceof Error?u.message:String(u);n.warn(`clone failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!ic(sc(s,".git"))){n.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=ac(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!ff(l,a)){n.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let f=u instanceof Error?u.message:String(u);n.warn(`fetch failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}}return o}function ff(t,e){return cc(t)===cc(e)}function cc(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function lc(t={}){let e=tt();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 ur(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let n of r)console.log(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}var uc=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function F(t){hf(t),process.exit(1)}function le(t){return mo(t)&&F("aborted"),t}function G(t){return mo(t)&&F("aborted"),typeof t=="string"?t:""}async function yc(t={}){gc("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();rc();let r=tc(e),n,o=!1;r&&Object.keys(r.answers).length>0?le(await Ot({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?($.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new At(e,r),o=!0):(lo(e),n=new At(e)):n=new At(e);let i=t.force===!0?null:await go(e),s=await n.ask("target",async()=>le(await lt({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?$.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)`):o&&n.get("contextRepo")!==void 0||kc(e,t.force===!0));let c=await n.ask("hubUrl",async()=>G(await Y({message:"HUB URL",placeholder:ge,initialValue:L("HUB_URL")??ge,validate:E=>E.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>mn()),{cliToken:u,accountEmail:f}=await n.ask("bootstrap",()=>gn(c,l)),p=null;s==="farm"&&(p=await yf(c,u));let g=a?kf(a.parsed.repoName):"",d=await n.ask("projectId",async()=>G(await Y({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:E=>Qe.test(E.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await n.ask("projectName",async()=>G(await Y({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()),C=await n.ask("automationLevel",async()=>le(await lt({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"}))),S=await n.ask("youtrack",()=>Tc()),R=await n.ask("youtrackProjectKey",async()=>G(await Y({message:"YouTrack project key",placeholder:"DEV",validate:E=>E.trim().length>0?void 0:"required"})).trim()),k=await n.ask("youtrackWrites",async()=>le(await Ot({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),b=n.get("tokens")??{},_=()=>n.set("tokens",b),O=await n.ask("repos",()=>vf(b,l,a,{onCred:_,initial:n.get("reposPartial")??[],onProgress:E=>n.set("reposPartial",E)}));n.delete("reposPartial");let I=await Sf(await n.ask("contextRepo",()=>vc(d,O,b,l)),d,O,b,l,_,E=>n.set("contextRepo",E)),{spec:y,mode:m}=I;$.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let v=await n.ask("assigneeLogin",async()=>G(await Y({message:"your YouTrack login (the assignee value)",...S.login?{initialValue:S.login}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),x=await n.ask("claudeToken",()=>jf(s==="farm")),w={projectId:d,name:h,automationLevel:C,repos:O,youtrackProjectKey:R,ownerEmail:f};$.step(`${m==="attach"?"attaching to":"provisioning"} Context Repo ${y.owner}/${y.name} (${y.host})\u2026`);let T;try{T=await jt(w,y,{...Sc(b),youtrackWrites:k,trackerUrl:S.url,mode:m,log:{info:E=>$.message(E),warn:E=>$.warn(E)}})}catch(E){F(`Context Repo provisioning failed: ${E instanceof Error?E.message:String(E)}`)}w.contextRepo=T,$.success(`Context Repo ready: ${T.owner}/${T.name}@${T.branch}`),$.step(`registering project on ${c}\u2026`);let P;try{P=await St(c,u,w)}catch(E){if(E instanceof N&&E.status===409){$.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{P=await Q(c,u,d)}catch(ae){throw ae instanceof N&&F(`HUB \u2192 ${ae.status} ${ae.message}`),ae}}else if(E instanceof N&&E.status===401)n.delete("cliToken"),F("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(E instanceof N)F(`HUB \u2192 ${E.status} ${E.message}`);else throw E}let U=P.contextRepo??T;$.success(`project ${P.projectId} ready (${P.provisioningStatus})`);let ie=await Pf(U),me={url:S.url,token:S.token};if(s==="farm"){let E=p,ae={...b,...ie?{contextWrite:ie}:{},...x?{claude:{oauthToken:x}}:{},youtrack:me},je=b.github?.token;if(U.host==="github"&&je)try{let V=ea(`devpipe-${d}`);await ta(U,je,V.publicKey,`devpipe-${d}`),ae.contextSsh={privateKey:V.privateKey},$.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(V){$.warn(`could not set up Context Repo SSH deploy key (${V instanceof Error?V.message:String(V)}); the farm will fall back to the token path.`)}let ve={projectId:d,config:{hubUrl:c,cliToken:u,projectId:d},secrets:ae,contextRepo:U,projectConfig:be(w,k,S.url,v||void 0)},kn=xt(E.farm.publicKey,JSON.stringify(ve));$.step(`handing project ${d} to farm ${E.farm.name}\u2026`);let ze;try{ze=await Yr(c,u,E.farm.farmId,{projectId:d,sealedBundle:kn})}catch(V){throw V instanceof N&&F(V.status===409?`farm ${E.farm.name} is offline \u2014 start it and re-run.`:V.status===504?`farm ${E.farm.name} did not respond in time.`:`HUB \u2192 ${V.status} ${V.message}`),V}ze.ok||F(`farm rejected provisioning: ${ze.error??"unknown error"}`),await fo(c,u,d,U,je),n.clear(),po(`done. project ${d} is now hosted on farm ${E.farm.name} (daemon ${ze.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Cc(b),await bc(e,U.cloneUrl,U.branch),xc(e),a&&await $f(e);{let E=ct(e,we);kt(E);let ae=be(w,k,S.url,v||void 0),je=qt(E,ae);je.length>0&&$.success(`local project config \u2192 .codepipe/{${je.join(", ")}}`),ot(d,ae,{info:ve=>$.message(ve),warn:ve=>$.warn(ve)})}await $c(e,P.repos);let Je={hubUrl:c,cliToken:u,projectId:d,...b,...ie?{contextWrite:ie}:{},...x?{claude:{oauthToken:x}}:{},youtrack:me};W(Je),rt({hubUrl:c,cliToken:u,projectId:d,accountEmail:f},d),$.success(`secrets \u2192 ${nt(d)}`),await fo(c,u,d,U,b.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),n.clear(),po("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function fo(t,e,r,n,o){let i=await oc(n,o),s=nc(i),a=await lt({message:s.message,options:s.options,initialValue:s.initialValue});if(!(mo(a)||a!==s.proceedValue))try{let{jobId:c}=await Vr(t,e,r,{reindex:s.reindex});$.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){$.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function yf(t,e){let r;try{r=await As(t,e)}catch(c){throw c instanceof N&&F(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&F("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 o=le(await lt({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=Kr(i.farmId,i.publicKey)}catch(c){F(c instanceof Error?c.message:String(c))}return le(await Ot({message:`confirm farm ${i.name} cred-channel fingerprint:
549
549
  ${s}
550
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||F("farm fingerprint not confirmed \u2014 aborting."),Gr(i.farmId,s),{farm:i,fingerprint:s}}async function gc(t){dc(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();hc(e,t.force===!0);let r=G(await Y({message:"HUB URL",initialValue:L("HUB_URL")??ge,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await dn(),{cliToken:o,accountEmail:i}=await fn(r,n);$.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await Q(r,o,t.projectId)}catch(f){throw f instanceof N&&F(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||F(`project ${t.projectId} has no Context Repo on HUB`);let a=await vc(),c={},l=new Set(s.repos.map(f=>f.host));l.add(s.contextRepo.host);for(let f of l)await un(f,c,f===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===f)?.owner,n);xc(c),await yc(e,s.contextRepo.cloneUrl,s.contextRepo.branch),kc(e);{let f=ct(e,ye);kt(f);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=ke(p,!0,a.url),d=Yt(f,g);d.length>0&&$.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),ot(t.projectId,g,{info:y=>$.message(y),warn:y=>$.warn(y)})}await wc(e,s.repos);let u={hubUrl:r,cliToken:o,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};W(u),rt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),$.success(`secrets \u2192 ${nt(t.projectId)}`),await po(r,o,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),uo("done.")}function hc(t,e){if(!_t(t)){cc(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=mf(t).filter(o=>!r.has(o));n.length!==0&&(e||F(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function mo(t){if(!_t(ct(t,".git")))return null;try{let r=(await pn(t).remote(["get-url","origin"])||"").toString().trim(),n=r?je(r):null;return n?{parsed:n,defaultBranch:await yf(t)}:null}catch{return null}}async function yf(t){let e=pn(t);try{let n=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(n)return n}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function wf(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Qe.test(e)?e:""}function kf(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function bf(t){let e=ct(t,".gitignore"),r=_t(e)?lc(e,"utf-8"):"";if(kf(r))return;if(!le(await Ot({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){$.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
550
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||F("farm fingerprint not confirmed \u2014 aborting."),Hr(i.farmId,s),{farm:i,fingerprint:s}}async function wc(t){gc(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();kc(e,t.force===!0);let r=G(await Y({message:"HUB URL",initialValue:L("HUB_URL")??ge,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await mn(),{cliToken:o,accountEmail:i}=await gn(r,n);$.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await Q(r,o,t.projectId)}catch(f){throw f instanceof N&&F(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||F(`project ${t.projectId} has no Context Repo on HUB`);let a=await Tc(),c={},l=new Set(s.repos.map(f=>f.host));l.add(s.contextRepo.host);for(let f of l)await dn(f,c,f===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===f)?.owner,n);Cc(c),await bc(e,s.contextRepo.cloneUrl,s.contextRepo.branch),xc(e);{let f=ct(e,we);kt(f);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=be(p,!0,a.url),d=qt(f,g);d.length>0&&$.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),ot(t.projectId,g,{info:h=>$.message(h),warn:h=>$.warn(h)})}await $c(e,s.repos);let u={hubUrl:r,cliToken:o,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};W(u),rt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),$.success(`secrets \u2192 ${nt(t.projectId)}`),await fo(r,o,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),po("done.")}function kc(t,e){if(!_t(t)){pc(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=gf(t).filter(o=>!r.has(o));n.length!==0&&(e||F(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function go(t){if(!_t(ct(t,".git")))return null;try{let r=(await fn(t).remote(["get-url","origin"])||"").toString().trim(),n=r?Ee(r):null;return n?{parsed:n,defaultBranch:await wf(t)}:null}catch{return null}}async function wf(t){let e=fn(t);try{let n=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(n)return n}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function kf(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Qe.test(e)?e:""}function bf(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function $f(t){let e=ct(t,".gitignore"),r=_t(e)?dc(e,"utf-8"):"";if(bf(r))return;if(!le(await Ot({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){$.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
551
551
  `)?"":`
552
- `;uc(e,r+o+`
552
+ `;fc(e,r+o+`
553
553
  # codepipe workspace (added by \`codepipe init\`)
554
554
  .codepipe/
555
- `),$.success(`.codepipe/ added to ${pc(e)}`)}function $f(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=ff(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function dn(){let t="";try{t=(await pn().raw(["config","--global","user.email"])||"").trim()}catch{}return G(await Y({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function fn(t,e){$.step(`connecting account ${e}`);let r;try{r=await As(t,e)}catch(s){throw s instanceof er&&F(`${e} is not authorized on this HUB yet.
555
+ `),$.success(`.codepipe/ added to ${mc(e)}`)}function xf(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=mf(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function mn(){let t="";try{t=(await fn().raw(["config","--global","user.email"])||"").trim()}catch{}return G(await Y({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function gn(t,e){$.step(`connecting account ${e}`);let r;try{r=await Ns(t,e)}catch(s){throw s instanceof tr&&F(`${e} is not authorized on this HUB yet.
556
556
  Sign up at ${t} (registration form on the login screen),
557
557
  wait for the operator to approve it by email, then re-run
558
- \`codepipe init\` with the same email.`),s}r.accountCreated&&$.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&$.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&($f(r.authorizeUrl),$.message(`a browser tab was opened to confirm this CLI:
558
+ \`codepipe init\` with the same email.`),s}r.accountCreated&&$.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&$.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(xf(r.authorizeUrl),$.message(`a browser tab was opened to confirm this CLI:
559
559
  ${r.authorizeUrl}
560
560
  `+(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
561
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&$.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),$.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await _s(t,r.requestId)}catch(a){$.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await lo(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&$.message(`connected as ${a} (the account confirmed in the browser).`),$.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&F("the HUB rejected this account"),s.status==="expired"&&F("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,$.message(`email confirmed. waiting for the operator to approve your account\u2026
562
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await lo(5e3);continue}await lo(2e3)}F("bootstrap timed out")}async function yc(t,e,r){let n=ct(t,ye);if(_t(ct(n,".git"))){$.message(`${n} already cloned \u2014 skipping`);return}_t(n)&&F(`${n} exists but is not a git repo \u2014 remove it and re-run`),cc(n,{recursive:!0}),$.step(`cloning Context Repo \u2192 ${n}`);try{await pn().clone(e,n,["--branch",r]),$.success(`cloned ${e}`)}catch(o){F(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function wc(t,e){if(e.length===0)return;$.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await lr(t,r,{log:{info:o=>$.message(o),warn:o=>$.warn(o)}});for(let o of n)$.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function kc(t){let e=ct(t,ye,".gitignore"),r="";if(_t(e)&&(r=lc(e,"utf-8")),ac.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
561
+ otherwise use the emailed link the page offers.`))),r.approvalRequired&&$.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),$.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await Us(t,r.requestId)}catch(a){$.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await uo(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&$.message(`connected as ${a} (the account confirmed in the browser).`),$.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&F("the HUB rejected this account"),s.status==="expired"&&F("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,$.message(`email confirmed. waiting for the operator to approve your account\u2026
562
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await uo(5e3);continue}await uo(2e3)}F("bootstrap timed out")}async function bc(t,e,r){let n=ct(t,we);if(_t(ct(n,".git"))){$.message(`${n} already cloned \u2014 skipping`);return}_t(n)&&F(`${n} exists but is not a git repo \u2014 remove it and re-run`),pc(n,{recursive:!0}),$.step(`cloning Context Repo \u2192 ${n}`);try{await fn().clone(e,n,["--branch",r]),$.success(`cloned ${e}`)}catch(o){F(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function $c(t,e){if(e.length===0)return;$.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await ur(t,r,{log:{info:o=>$.message(o),warn:o=>$.warn(o)}});for(let o of n)$.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function xc(t){let e=ct(t,we,".gitignore"),r="";if(_t(e)&&(r=dc(e,"utf-8")),uc.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
563
563
  `)||r.length===0?"":`
564
- `,i=ac.join(`
564
+ `,i=uc.join(`
565
565
  `)+`
566
- `;uc(e,r+o+(r?`
567
- `:"")+i),$.message(`appended runtime entries to ${pc(e)}`)}async function xf(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;$.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await un(s.host,t,s.owner,e),i?.();let c=G(await Y({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=G(await Y({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;le(await Ot({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=G(await Y({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||je(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=je(a);$.message(`${c.host}: ${c.owner}/${c.repoName}`),await un(c.host,t,c.owner,e),i?.();let l=G(await Y({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=G(await Y({message:"default branch (optional)",placeholder:"main"})).trim(),f=G(await Y({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),o.push(p),n.onProgress?.(o)}return o}async function bc(t,e,r,n){$.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 o=le(await lt({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"}));o==="attach"&&$.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=G(await Y({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Ce(t),validate:u=>{let f=(u??"").trim();if(!f)return"required";if(!je(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=je(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Sf(),l=G(await Y({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=G(await Y({message:"Context Repo name",placeholder:Ce(t),initialValue:Ce(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function $c(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??gt()}}async function vf(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await un(c.host,n,c.owner,o),i?.();let u=fc();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await Ka(c,$c(n),{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=le(await lt({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"&&F("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await bc(e,r,n,o),s(a)}}async function Sf(){return le(await lt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function ur(t,e){let r=fc();r.start(`verifying ${t}\u2026`);try{let n=await e();return r.stop(`${t} OK \u2014 ${n}`),!0}catch(n){return r.stop(`${t} failed \u2014 ${n instanceof Error?n.message:String(n)}`,1),!1}}function xc(t){Vt(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Jt(t.gitlab?.token??process.env.GITLAB_TOKEN),zt(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function un(t,e,r,n){if(!e[t])if(t==="github"){let o=await Cf(r);o?e.github=o:$.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let o=await Tf(r,n);o?e.bitbucket=o:$.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 o=await Rf();o?e.gitlab=o:$.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Cf(t){for(;;){let e=G(await Nt({message:`GitHub PAT \u2014 blank to skip
566
+ `;fc(e,r+o+(r?`
567
+ `:"")+i),$.message(`appended runtime entries to ${mc(e)}`)}async function vf(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;$.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await dn(s.host,t,s.owner,e),i?.();let c=G(await Y({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=G(await Y({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;le(await Ot({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=G(await Y({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||Ee(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=Ee(a);$.message(`${c.host}: ${c.owner}/${c.repoName}`),await dn(c.host,t,c.owner,e),i?.();let l=G(await Y({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=G(await Y({message:"default branch (optional)",placeholder:"main"})).trim(),f=G(await Y({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),o.push(p),n.onProgress?.(o)}return o}async function vc(t,e,r,n){$.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 o=le(await lt({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"}));o==="attach"&&$.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=G(await Y({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Ce(t),validate:u=>{let f=(u??"").trim();if(!f)return"required";if(!Ee(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=Ee(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Cf(),l=G(await Y({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=G(await Y({message:"Context Repo name",placeholder:Ce(t),initialValue:Ce(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function Sc(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??gt()}}async function Sf(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await dn(c.host,n,c.owner,o),i?.();let u=hc();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await qa(c,Sc(n),{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=le(await lt({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"&&F("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await vc(e,r,n,o),s(a)}}async function Cf(){return le(await lt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function pr(t,e){let r=hc();r.start(`verifying ${t}\u2026`);try{let n=await e();return r.stop(`${t} OK \u2014 ${n}`),!0}catch(n){return r.stop(`${t} failed \u2014 ${n instanceof Error?n.message:String(n)}`,1),!1}}function Cc(t){Jt(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),zt(t.gitlab?.token??process.env.GITLAB_TOKEN),Xt(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function dn(t,e,r,n){if(!e[t])if(t==="github"){let o=await Tf(r);o?e.github=o:$.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let o=await Rf(r,n);o?e.bitbucket=o:$.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 o=await If();o?e.gitlab=o:$.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Tf(t){for(;;){let e=G(await Nt({message:`GitHub PAT \u2014 blank to skip
568
568
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
569
569
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
570
570
  if org: approve token in org Settings \u2192 Personal access tokens.
571
571
  (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
572
- set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await ur("GitHub",()=>De(e,t?{owner:t}:void 0)))return{token:e};$.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Tf(t,e){for($.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
572
+ set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await pr("GitHub",()=>De(e,t?{owner:t}:void 0)))return{token:e};$.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Rf(t,e){for($.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
573
573
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
574
574
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
575
575
  read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
576
576
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
577
- The token is shown ONCE \u2014 copy it right away.`);;){let r=G(await Y({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:o=>!o||!o.trim()||o.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let n=G(await Nt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!n){$.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await ur("Bitbucket",()=>Be(r,n,t)))return{email:r,apiToken:n};$.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Rf(){for(;;){let t=G(await Nt({message:`GitLab PAT \u2014 blank to skip
578
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await ur("GitLab",()=>Me(t))){let e=await Ti(t);return e&&$.warn(e),{token:t}}$.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function If(t){if(le(await Ot({message:`Issue a separate context-write token (scoped to the Context Repo only)?
577
+ The token is shown ONCE \u2014 copy it right away.`);;){let r=G(await Y({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:o=>!o||!o.trim()||o.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let n=G(await Nt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!n){$.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await pr("Bitbucket",()=>Be(r,n,t)))return{email:r,apiToken:n};$.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function If(){for(;;){let t=G(await Nt({message:`GitLab PAT \u2014 blank to skip
578
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await pr("GitLab",()=>Me(t))){let e=await Ri(t);return e&&$.warn(e),{token:t}}$.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Pf(t){if(le(await Ot({message:`Issue a separate context-write token (scoped to the Context Repo only)?
579
579
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
580
580
  credential. A scoped token hardens setups where the SANDBOX runs outside
581
581
  your trusted network.`,initialValue:!1})))for(t.host==="github"?$.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
582
582
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
583
583
  required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):$.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
584
- (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=G(await Nt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await ur("contextWrite",()=>Pf(r,t)))return{token:r};$.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Pf(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=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(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.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(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function jf(t){if(Sn()?.claude?.oauthToken&&!t)return $.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`)."),"";$.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?`
585
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=G(await Nt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||$.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):($.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 vc(){for(;;){let t=G(await Y({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=G(await Nt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await ur("YouTrack",()=>Fe({baseUrl:t,token:e}))){let r=await Yi({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}$.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Ef}from"node:fs";function q(t){throw new Error(t)}function X(t,e){return(typeof t!="string"||t.trim().length===0)&&q(`config: '${e}' must be a non-empty string`),t.trim()}function pr(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 Af(t){(!t||typeof t!="object")&&q("config: expected a JSON object");let e=t,r=X(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||q("config: 'hubUrl' must start with http(s)://");let n=X(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&q("config: 'project' is required");let i=o,s=X(i.id,"project.id");Qe.test(s)||q("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=X(i.name,"project.name"),c=X(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&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((R,k)=>{(!R||typeof R!="object")&&q(`config: project.repos[${k}] must be an object`);let b=R,_=X(b.host,`project.repos[${k}].host`);_!=="github"&&_!=="bitbucket"&&_!=="gitlab"&&q(`config: project.repos[${k}].host must be 'github', 'bitbucket' or 'gitlab'`);let O={name:X(b.name,`project.repos[${k}].name`),host:_,owner:X(b.owner,`project.repos[${k}].owner`),repoName:X(b.repoName,`project.repos[${k}].repoName`)},I=pr(b.defaultBranch,`project.repos[${k}].defaultBranch`);I&&(O.defaultBranch=I);let h=pr(b.mountAs,`project.repos[${k}].mountAs`);return h&&(O.mountAs=h),O}),f=i.contextRepo;(!f||typeof f!="object")&&q("config: 'project.contextRepo' is required");let p=f,g=pr(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:X(p.owner,"project.contextRepo.owner"),name:pr(p.name,"project.contextRepo.name")??Ce(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:d}},S=pr(i.youtrackProjectKey,"project.youtrackProjectKey");S&&(y.project.youtrackProjectKey=S),i.index!==void 0&&(typeof i.index!="boolean"&&q("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&q("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let C=e.secrets;if(C!==void 0){(typeof C!="object"||C===null)&&q("config: 'secrets' must be an object");let R=C,k={};if(R.github){let b=R.github;k.github={token:X(b.token,"secrets.github.token")}}if(R.bitbucket){let b=R.bitbucket;k.bitbucket={email:X(b.email,"secrets.bitbucket.email"),apiToken:X(b.apiToken,"secrets.bitbucket.apiToken")}}if(R.gitlab){let b=R.gitlab;k.gitlab={token:X(b.token,"secrets.gitlab.token")}}if(R.youtrack){let b=R.youtrack;k.youtrack={url:X(b.url,"secrets.youtrack.url").replace(/\/$/,""),token:X(b.token,"secrets.youtrack.token")}}if(R.contextWrite){let b=R.contextWrite;k.contextWrite={token:X(b.token,"secrets.contextWrite.token")}}y.secrets=k}return y}async function _f(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Of(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await De(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(o=>o.host==="bitbucket")?.owner,n=await Be(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await Me(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Fe({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Sc(t){let e=!t.configPath||t.configPath==="-"?await _f():Ef(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 n=Af(r),{hubUrl:o,cliToken:i,project:s}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await Of(n));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=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Et(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??gt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.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 ${o}\u2026`);let u;try{u=await St(o,i,a)}catch(p){if(p instanceof N&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await Q(o,i,s.id);else if(p instanceof N)q(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let f={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(W(f),rt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${nt(s.id)}`),ot(s.id,ke(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await Yr(o,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 Cc,intro as Tc,isCancel as Rc,log as go,outro as Nf,password as Ic}from"@clack/prompts";async function Uf(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Pc(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Uf(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Tc("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),go.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Ic({message:"Claude OAuth token"});Rc(i)&&(Cc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),ni({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Ir()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ne(t.profile);if(!e){Tc(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),go.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Ic({message:"Claude OAuth token"});Rc(i)&&(Cc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=B(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},W(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(go.success("Claude OAuth token saved."),Nf("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Lf,confirm as Df,intro as Bf,isCancel as jc,log as te,outro as Mf,select as Ec,text as Ve}from"@clack/prompts";function Ac(t){Lf(t),process.exit(1)}function Ut(t){return jc(t)&&Ac("aborted"),t}function dr(t){return jc(t)&&Ac("aborted"),typeof t=="string"?t:""}async function Gf(t,e){let r=Ut(await Ec({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=dr(await Ve({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=dr(await Ve({message:"Context Repo name",placeholder:Ce(t),initialValue:Ce(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function _c(t={profile:void 0}){let e=Ne(t.profile);Bf(`codepipe project add \u2192 ${e.hubUrl}`);let r=Ut(await Ve({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>Qe.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Ut(await Ve({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),o=Ut(await Ec({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=Ut(await Ve({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Ut(await Df({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=dr(await Ve({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:C=>!C||!C.trim()||je(C)?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=je(p);te.message(`${g.host}: ${g.owner}/${g.repoName}`);let d=dr(await Ve({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:C=>C.trim().length>0?void 0:"required"})).trim(),y=dr(await Ve({message:"default branch (optional)",placeholder:"main"})).trim(),S={name:d,host:g.host,owner:g.owner,repoName:g.repoName};y&&(S.defaultBranch=y),a.push(S)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Gf(r,a),u=B(e.projectId);te.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Et(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??gt(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>te.message(p),warn:p=>te.warn(p)}})}catch(p){te.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=f,te.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await St(e.hubUrl,e.cliToken,c);te.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),ot(r,ke(c,s,u?.youtrack?.url),{info:g=>te.message(g),warn:g=>te.warn(g)}),p.contextRepo&&(te.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),te.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&te.error(` error: ${p.provisioningError}`),Mf("done")}catch(p){p instanceof N?(te.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&te.message(JSON.stringify(p.payload,null,2))):te.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{spawn as Ff}from"node:child_process";import{existsSync as Oc}from"node:fs";import{homedir as Hf,hostname as Kf}from"node:os";import{join as mn}from"node:path";async function Wf(t,e,r){let n=ee(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Pe(e)} points at a different HUB (${n.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let o;try{o=await js(t.hubUrl.replace(/\/$/,""),n.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(o==="unsupported")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(o==="ok")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${n.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${Pe(e)} still holds its token.
586
- Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${n.sandboxId} \u2014 replacing the registration`),ri(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function Yf(t,e,r){let n=ee(e)!==null;if(!await Wf(t,e,r))return;console.log(n?"[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 o;try{({secret:o}=await Wr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof N&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof N&&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 N?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 st({hub:t.hubUrl,token:o,name:r.name??`${Kf()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function qf(t,e){let r=ee(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=be(r.sealPublicKey);if(!B(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Rr(t,r.sandboxId,n);if(o==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${n}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${o==="pinned"?"auto-pinned":"already pinned"} for ${t} (${n})`)}async function Vf(t,e){let r=process.cwd(),n=mn(r,ye);if(Sr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Oc(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await Q(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 mo(r);if(!Mo(r,i?.parsed??null,o.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=B(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await zr({cfg:t,secrets:s,contextDir:n,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=mn(Hf(),".codepipe",e?mn("profiles",e,"context-config"):"context-config");if(Ar(c.contextDir,l,a),!Oc(mn(c.contextDir,"project.yaml"))){kt(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Yt(c.contextDir,ke(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 ${n}`)}async function Nc(t){let{cfg:e,profile:r}=Tr(t.profile);await Vf(e,r),await Yf(e,r,t),qf(e.projectId,r);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(g,d)=>{let y=S=>C=>{for(let R of C.toString("utf-8").split(`
587
- `))R.length>0&&S.write(`${d} ${R}
588
- `)};g.stdout?.on("data",y(process.stdout)),g.stderr?.on("data",y(process.stderr))},i=(g,d)=>{let y=Ff(process.execPath,[n,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return o(y,g),y};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=g=>{if(!l){l=!0,console.log(`
589
- [up] ${g} \u2014 stopping both roles`);for(let{child:d}of c)d.exitCode===null&&d.kill(g);setTimeout(()=>{for(let{name:d,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let f=c.map(({name:g,child:d})=>new Promise(y=>{d.on("exit",(S,C)=>y({name:g,code:S??(C?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 qc,mkdirSync as Zf,readFileSync as em,writeFileSync as tm}from"node:fs";import{homedir as rm}from"node:os";import{dirname as nm,join as Vc}from"node:path";import*as Dt from"node:readline";import{existsSync as wo,readFileSync as Jf,writeFileSync as zf}from"node:fs";import{join as mr}from"node:path";import{simpleGit as yo}from"simple-git";var Uc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Xf="apply-queue.json";function Lc(t){return mr(t,Xf)}function Lt(t){let e=Lc(t);if(!wo(e))return{};try{return JSON.parse(Jf(e,"utf-8"))}catch{return{}}}function Dc(t,e){zf(Lc(t),JSON.stringify(e,null,2)+`
590
- `)}async function Bc(t,e,r,n,o){let i;try{i=await Us(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(C=>C.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let d=mr(t.root,g.mountAs);if(!wo(mr(d,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await yo(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=yo(p.dir),d=await Qf(g),y=p.claimRepo;try{await g.fetch()}catch(R){return await ho(a,o),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${fr(R)}`}}let S=`origin/${y.baseRef}`,C;try{C=await Br(g,{contextRepoCloneUrl:y.contextRepoCloneUrl,deliveryRef:y.deliveryRef,deliverySha:y.deliverySha,baseSha:y.baseSha,commitMessage:y.commitMessage})}catch(R){return await ho(a,o),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${fr(R)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:d,branch:y.branchName,baseSha:S,deliveryCommit:C,startPoint:S})}let c=[];for(let p of a)try{if(n==="apply"){await p.git.checkout(["-B",p.branch,p.startPoint]),await p.git.raw([...Uc,"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([...Uc,"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 ho(a,o),{ok:!1,message:`apply failed in ${p.mountAs}: ${fr(g)} (rolled back all repos)`}}let l=Lt(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Dc(t.contextDir,l);let u=c.map(p=>p.mountAs).join(", "),f=n==="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:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
584
+ (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=G(await Nt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await pr("contextWrite",()=>Ef(r,t)))return{token:r};$.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Ef(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=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(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.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(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function jf(t){if(Tn()?.claude?.oauthToken&&!t)return $.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`)."),"";$.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?`
585
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=G(await Nt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||$.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):($.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 Tc(){for(;;){let t=G(await Y({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=G(await Nt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await pr("YouTrack",()=>Fe({baseUrl:t,token:e}))){let r=await Ji({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}$.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Af}from"node:fs";function q(t){throw new Error(t)}function X(t,e){return(typeof t!="string"||t.trim().length===0)&&q(`config: '${e}' must be a non-empty string`),t.trim()}function dr(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 _f(t){(!t||typeof t!="object")&&q("config: expected a JSON object");let e=t,r=X(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||q("config: 'hubUrl' must start with http(s)://");let n=X(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&q("config: 'project' is required");let i=o,s=X(i.id,"project.id");Qe.test(s)||q("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=X(i.name,"project.name"),c=X(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&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((R,k)=>{(!R||typeof R!="object")&&q(`config: project.repos[${k}] must be an object`);let b=R,_=X(b.host,`project.repos[${k}].host`);_!=="github"&&_!=="bitbucket"&&_!=="gitlab"&&q(`config: project.repos[${k}].host must be 'github', 'bitbucket' or 'gitlab'`);let O={name:X(b.name,`project.repos[${k}].name`),host:_,owner:X(b.owner,`project.repos[${k}].owner`),repoName:X(b.repoName,`project.repos[${k}].repoName`)},I=dr(b.defaultBranch,`project.repos[${k}].defaultBranch`);I&&(O.defaultBranch=I);let y=dr(b.mountAs,`project.repos[${k}].mountAs`);return y&&(O.mountAs=y),O}),f=i.contextRepo;(!f||typeof f!="object")&&q("config: 'project.contextRepo' is required");let p=f,g=dr(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:X(p.owner,"project.contextRepo.owner"),name:dr(p.name,"project.contextRepo.name")??Ce(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:d}},C=dr(i.youtrackProjectKey,"project.youtrackProjectKey");C&&(h.project.youtrackProjectKey=C),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 S=e.secrets;if(S!==void 0){(typeof S!="object"||S===null)&&q("config: 'secrets' must be an object");let R=S,k={};if(R.github){let b=R.github;k.github={token:X(b.token,"secrets.github.token")}}if(R.bitbucket){let b=R.bitbucket;k.bitbucket={email:X(b.email,"secrets.bitbucket.email"),apiToken:X(b.apiToken,"secrets.bitbucket.apiToken")}}if(R.gitlab){let b=R.gitlab;k.gitlab={token:X(b.token,"secrets.gitlab.token")}}if(R.youtrack){let b=R.youtrack;k.youtrack={url:X(b.url,"secrets.youtrack.url").replace(/\/$/,""),token:X(b.token,"secrets.youtrack.token")}}if(R.contextWrite){let b=R.contextWrite;k.contextWrite={token:X(b.token,"secrets.contextWrite.token")}}h.secrets=k}return h}async function Of(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Nf(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await De(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(o=>o.host==="bitbucket")?.owner,n=await Be(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await Me(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Fe({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Rc(t){let e=!t.configPath||t.configPath==="-"?await Of():Af(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 n=_f(r),{hubUrl:o,cliToken:i,project:s}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await Nf(n));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=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await jt(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??gt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.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 ${o}\u2026`);let u;try{u=await St(o,i,a)}catch(p){if(p instanceof N&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await Q(o,i,s.id);else if(p instanceof N)q(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let f={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(W(f),rt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${nt(s.id)}`),ot(s.id,be(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await Vr(o,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 Ic,intro as Pc,isCancel as Ec,log as ho,outro as Uf,password as jc}from"@clack/prompts";async function Lf(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Ac(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Lf(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Pc("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),ho.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await jc({message:"Claude OAuth token"});Ec(i)&&(Ic("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),oi({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Pr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ne(t.profile);if(!e){Pc(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),ho.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await jc({message:"Claude OAuth token"});Ec(i)&&(Ic("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=B(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},W(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(ho.success("Claude OAuth token saved."),Uf("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Df,confirm as Bf,intro as Mf,isCancel as _c,log as te,outro as Gf,select as Oc,text as Ve}from"@clack/prompts";function Nc(t){Df(t),process.exit(1)}function Ut(t){return _c(t)&&Nc("aborted"),t}function fr(t){return _c(t)&&Nc("aborted"),typeof t=="string"?t:""}async function Ff(t,e){let r=Ut(await Oc({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=fr(await Ve({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=fr(await Ve({message:"Context Repo name",placeholder:Ce(t),initialValue:Ce(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Uc(t={profile:void 0}){let e=Ne(t.profile);Mf(`codepipe project add \u2192 ${e.hubUrl}`);let r=Ut(await Ve({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>Qe.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Ut(await Ve({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),o=Ut(await Oc({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=Ut(await Ve({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Ut(await Bf({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=fr(await Ve({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:S=>!S||!S.trim()||Ee(S)?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=Ee(p);te.message(`${g.host}: ${g.owner}/${g.repoName}`);let d=fr(await Ve({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:S=>S.trim().length>0?void 0:"required"})).trim(),h=fr(await Ve({message:"default branch (optional)",placeholder:"main"})).trim(),C={name:d,host:g.host,owner:g.owner,repoName:g.repoName};h&&(C.defaultBranch=h),a.push(C)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Ff(r,a),u=B(e.projectId);te.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await jt(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??gt(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>te.message(p),warn:p=>te.warn(p)}})}catch(p){te.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=f,te.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await St(e.hubUrl,e.cliToken,c);te.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),ot(r,be(c,s,u?.youtrack?.url),{info:g=>te.message(g),warn:g=>te.warn(g)}),p.contextRepo&&(te.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),te.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&te.error(` error: ${p.provisioningError}`),Gf("done")}catch(p){p instanceof N?(te.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&te.message(JSON.stringify(p.payload,null,2))):te.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{spawn as Hf}from"node:child_process";import{existsSync as Lc}from"node:fs";import{homedir as Kf,hostname as Wf}from"node:os";import{join as hn}from"node:path";async function Yf(t,e,r){let n=ee(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Pe(e)} points at a different HUB (${n.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let o;try{o=await _s(t.hubUrl.replace(/\/$/,""),n.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(o==="unsupported")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(o==="ok")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${n.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${Pe(e)} still holds its token.
586
+ Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${n.sandboxId} \u2014 replacing the registration`),ni(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function qf(t,e,r){let n=ee(e)!==null;if(!await Yf(t,e,r))return;console.log(n?"[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 o;try{({secret:o}=await qr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof N&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof N&&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 N?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 st({hub:t.hubUrl,token:o,name:r.name??`${Wf()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function Vf(t,e){let r=ee(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=$e(r.sealPublicKey);if(!B(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Ir(t,r.sandboxId,n);if(o==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${n}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${o==="pinned"?"auto-pinned":"already pinned"} for ${t} (${n})`)}async function Jf(t,e){let r=process.cwd(),n=hn(r,we);if(Cr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Lc(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await Q(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 go(r);if(!Go(r,i?.parsed??null,o.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=B(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Qr({cfg:t,secrets:s,contextDir:n,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=hn(Kf(),".codepipe",e?hn("profiles",e,"context-config"):"context-config");if(_r(c.contextDir,l,a),!Lc(hn(c.contextDir,"project.yaml"))){kt(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};qt(c.contextDir,be(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 ${n}`)}async function Dc(t){let{cfg:e,profile:r}=Rr(t.profile);await Jf(e,r),await qf(e,r,t),Vf(e.projectId,r);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(g,d)=>{let h=C=>S=>{for(let R of S.toString("utf-8").split(`
587
+ `))R.length>0&&C.write(`${d} ${R}
588
+ `)};g.stdout?.on("data",h(process.stdout)),g.stderr?.on("data",h(process.stderr))},i=(g,d)=>{let h=Hf(process.execPath,[n,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return o(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(`
589
+ [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",(C,S)=>h({name:g,code:C??(S?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 zc,mkdirSync as em,readFileSync as tm,writeFileSync as rm}from"node:fs";import{homedir as nm}from"node:os";import{dirname as om,join as Xc}from"node:path";import*as Dt from"node:readline";import{existsSync as ko,readFileSync as zf,writeFileSync as Xf}from"node:fs";import{join as gr}from"node:path";import{simpleGit as wo}from"simple-git";var Bc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Qf="apply-queue.json";function Mc(t){return gr(t,Qf)}function Lt(t){let e=Mc(t);if(!ko(e))return{};try{return JSON.parse(zf(e,"utf-8"))}catch{return{}}}function Gc(t,e){Xf(Mc(t),JSON.stringify(e,null,2)+`
590
+ `)}async function Fc(t,e,r,n,o){let i;try{i=await Bs(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(S=>S.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let d=gr(t.root,g.mountAs);if(!ko(gr(d,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await wo(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=wo(p.dir),d=await Zf(g),h=p.claimRepo;try{await g.fetch()}catch(R){return await yo(a,o),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${mr(R)}`}}let C=`origin/${h.baseRef}`,S;try{S=await Gr(g,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(R){return await yo(a,o),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${mr(R)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:d,branch:h.branchName,baseSha:C,deliveryCommit:S,startPoint:C})}let c=[];for(let p of a)try{if(n==="apply"){await p.git.checkout(["-B",p.branch,p.startPoint]),await p.git.raw([...Bc,"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([...Bc,"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 yo(a,o),{ok:!1,message:`apply failed in ${p.mountAs}: ${mr(g)} (rolled back all repos)`}}let l=Lt(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Gc(t.contextDir,l);let u=c.map(p=>p.mountAs).join(", "),f=n==="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:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
591
591
  ${f}
592
- or: /abort ${r} --reason "..."`}}function ko(t,e){let r=Lt(t);r[e]&&(delete r[e],Dc(t,r))}async function ho(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(n){e.warn(`rollback failed in ${r.mountAs}: ${fr(n)} \u2014 check manually`)}}async function Mc(t,e,r){let o=Lt(t.contextDir)[e];if(o){for(let i of o.repos){let s=mr(t.root,i.mountAs);if(!wo(mr(s,".git")))continue;let a=yo(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}: ${fr(u)} \u2014 check manually`)}}ko(t.contextDir,e)}}async function Qf(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function fr(t){return t instanceof Error?t.message.trim():String(t)}var gn=Vc(rm(),".codepipe","history"),Gc=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Jc=500,Fc=40;async function zc(){let t=tt();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=B(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)),Wt(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=Lt(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
592
+ or: /abort ${r} --reason "..."`}}function bo(t,e){let r=Lt(t);r[e]&&(delete r[e],Gc(t,r))}async function yo(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(n){e.warn(`rollback failed in ${r.mountAs}: ${mr(n)} \u2014 check manually`)}}async function Hc(t,e,r){let o=Lt(t.contextDir)[e];if(o){for(let i of o.repos){let s=gr(t.root,i.mountAs);if(!ko(gr(s,".git")))continue;let a=wo(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}: ${mr(u)} \u2014 check manually`)}}bo(t.contextDir,e)}}async function Zf(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function mr(t){return t instanceof Error?t.message.trim():String(t)}var yn=Xc(nm(),".codepipe","history"),Kc=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Qc=500,Wc=40;async function Zc(){let t=tt();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=B(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)),Yt(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=Lt(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
593
593
  \u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
594
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=Dt.createInterface({input:process.stdin,output:process.stdout,completer:om,history:Sm(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};bs(s=>ut(i,s)),i.daemon=Jr({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>ut(i,s),warn:s=>ut(i,s)},onEvent:s=>wm(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),$o(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await im(i,a)){Yc(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,$o(i),o.prompt()}),o.on("close",()=>{Yc(i)})}function om(t){let e=Gc.filter(r=>r.startsWith(t));return[e.length?e:Gc,t]}async function im(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return sm(),!1;case"/status":return await am(t),!1;case"/tasks":return await cm(t,n),!1;case"/task":return await lm(t,n),!1;case"/sync":return await um(t),!1;case"/logs":return km(t,n),!1;case"/monitor":return bm(t),!1;case"/apply":return await Hc(t,n,"apply"),!1;case"/unstash":return await Hc(t,n,"unstash"),!1;case"/applied":return await pm(t,n),!1;case"/abort":return await dm(t,n),!1;case"/approve":return await Kc(t,n,"approve"),!1;case"/merge":return await Kc(t,n,"merge"),!1;case"/login":return mm(t,n),!1;case"/secret":return gm(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function sm(){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(`
595
- `))}async function am(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 n=qc(Vc(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function cm(t,e){let r=$m(e,"--phase");try{let n=await Os(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){hr(n)}}async function lm(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Ns(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${n.task.phase} \u2014 ${n.task.title}`),n.artifacts.length>0){console.log(" artifacts:");for(let o of n.artifacts)console.log(` ${o.path}`)}}catch(n){hr(n)}}async function um(t){let e=await lr(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 Hc(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Bc(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function pm(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=Lt(t.ws.contextDir)[r],i=xm(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=o?.repos.length===1?fm(t,o.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 Ls(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);ko(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){hr(c)}}async function Kc(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Bs(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){hr(o)}}async function dm(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=vm(e,"--reason")||"local apply aborted";await Mc(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await Ds(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){hr(o)}}function fm(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function mm(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},W(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 gm(t,e){let[r,n,...o]=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(`
596
- `)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}hm(t.secrets,n,i),W(t.secrets),Wt(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}ym(t.secrets,n),W(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function hm(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 ym(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 wm(t,e){switch(e.kind){case"connected":t.connection="connecting",ut(t,"[hub] connected");break;case"registered":t.connection="registered",ut(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",gr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",ut(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",gr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":gr(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?ut(t,`[hub] action ${e.actionType} done`):gr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function ut(t,e){t.logBuffer.push(e),t.logBuffer.length>Jc&&t.logBuffer.shift(),t.follow&&gr(t,e)}function km(t,e){let r=e[0];if(r==="follow"||r==="on"){bo(t,!0);return}if(r==="off"){bo(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Jc,Number(r)||Fc)):Fc,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of o)console.log(` ${i}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function bm(t){bo(t,!t.follow)}function bo(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function gr(t,e){Dt.cursorTo(process.stdout,0),Dt.clearLine(process.stdout,0),process.stdout.write(e+`
597
- `),t.unread+=1,$o(t),t.rl.prompt(!0)}function $o(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Wc=!1;function Yc(t){Wc||(Wc=!0,Cm(t.rl),t.daemon.stop(),console.log(`
598
- bye.`),setTimeout(()=>process.exit(0),150))}function $m(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function xm(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function vm(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function hr(t){t instanceof N?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Sm(){if(!qc(gn))return[];try{return em(gn,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Cm(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{Zf(nm(gn),{recursive:!0}),tm(gn,r.slice().reverse().join(`
594
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=Dt.createInterface({input:process.stdin,output:process.stdout,completer:im,history:Cm(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};vs(s=>ut(i,s)),i.daemon=Xr({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>ut(i,s),warn:s=>ut(i,s)},onEvent:s=>km(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),xo(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await sm(i,a)){Jc(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,xo(i),o.prompt()}),o.on("close",()=>{Jc(i)})}function im(t){let e=Kc.filter(r=>r.startsWith(t));return[e.length?e:Kc,t]}async function sm(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return am(),!1;case"/status":return await cm(t),!1;case"/tasks":return await lm(t,n),!1;case"/task":return await um(t,n),!1;case"/sync":return await pm(t),!1;case"/logs":return bm(t,n),!1;case"/monitor":return $m(t),!1;case"/apply":return await Yc(t,n,"apply"),!1;case"/unstash":return await Yc(t,n,"unstash"),!1;case"/applied":return await dm(t,n),!1;case"/abort":return await fm(t,n),!1;case"/approve":return await qc(t,n,"approve"),!1;case"/merge":return await qc(t,n,"merge"),!1;case"/login":return gm(t,n),!1;case"/secret":return hm(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function am(){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(`
595
+ `))}async function cm(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 n=zc(Xc(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function lm(t,e){let r=xm(e,"--phase");try{let n=await Ls(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){yr(n)}}async function um(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Ds(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${n.task.phase} \u2014 ${n.task.title}`),n.artifacts.length>0){console.log(" artifacts:");for(let o of n.artifacts)console.log(` ${o.path}`)}}catch(n){yr(n)}}async function pm(t){let e=await ur(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 Yc(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Fc(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function dm(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=Lt(t.ws.contextDir)[r],i=vm(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=o?.repos.length===1?mm(t,o.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 Ms(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);bo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){yr(c)}}async function qc(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Fs(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){yr(o)}}async function fm(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=Sm(e,"--reason")||"local apply aborted";await Hc(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await Gs(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){yr(o)}}function mm(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function gm(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},W(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 hm(t,e){let[r,n,...o]=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(`
596
+ `)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}ym(t.secrets,n,i),W(t.secrets),Yt(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}wm(t.secrets,n),W(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function ym(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 wm(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 km(t,e){switch(e.kind){case"connected":t.connection="connecting",ut(t,"[hub] connected");break;case"registered":t.connection="registered",ut(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",hr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",ut(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",hr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":hr(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?ut(t,`[hub] action ${e.actionType} done`):hr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function ut(t,e){t.logBuffer.push(e),t.logBuffer.length>Qc&&t.logBuffer.shift(),t.follow&&hr(t,e)}function bm(t,e){let r=e[0];if(r==="follow"||r==="on"){$o(t,!0);return}if(r==="off"){$o(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Qc,Number(r)||Wc)):Wc,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of o)console.log(` ${i}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function $m(t){$o(t,!t.follow)}function $o(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function hr(t,e){Dt.cursorTo(process.stdout,0),Dt.clearLine(process.stdout,0),process.stdout.write(e+`
597
+ `),t.unread+=1,xo(t),t.rl.prompt(!0)}function xo(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Vc=!1;function Jc(t){Vc||(Vc=!0,Tm(t.rl),t.daemon.stop(),console.log(`
598
+ bye.`),setTimeout(()=>process.exit(0),150))}function xm(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function vm(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function Sm(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function yr(t){t instanceof N?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Cm(){if(!zc(yn))return[];try{return tm(yn,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Tm(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{em(om(yn),{recursive:!0}),rm(yn,r.slice().reverse().join(`
599
599
  `)+`
600
- `)}catch{}}import{hostname as Tm}from"node:os";import{cancel as Rm,confirm as Xc,intro as Im,isCancel as el,log as Bt,multiselect as Pm,outro as Qc,password as jm,select as xo,text as vo}from"@clack/prompts";function yr(t){Rm(t),process.exit(1)}function Mt(t){return el(t)&&yr("aborted"),t}function hn(t){return el(t)&&yr("aborted"),typeof t=="string"?t:""}function So(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Zc(t,e){try{let{secret:r}=await Wr(t,e);return r}catch(r){throw r instanceof N&&r.status===404&&yr("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 Em(t,e){if(Mt(await xo({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 o=await Es(t,e);if(o.length>0)return Mt(await Pm({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));Bt.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Bt.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return hn(await vo({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:o=>o.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function Co(t){Im("codepipe worker \u2014 set up this machine as a runner");let e=ee(t.profile);e&&(Bt.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Mt(await Xc({message:"re-register this worker?",initialValue:!1}))||yr("keeping the existing registration"));let r=Te(t.profile)??Te(),n=hn(await vo({message:"HUB URL",placeholder:ge,initialValue:L("HUB_URL")??r?.hubUrl??ge,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Mt(await xo({message:"how to authorize the registration?",options:[...o?[{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:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await Zc(n,a),Bt.success("account-issued registration token minted");else if(i==="login"){let p=await dn();a=(await fn(n,p)).cliToken,s=await Zc(n,a),Bt.success("account-issued registration token minted")}else s=hn(await jm({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||yr("a registration token is required");let c=await Em(n,a),l=hn(await vo({message:"worker name",initialValue:Tm(),validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=Mt(await xo({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 st({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Bt.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Mt(await Xc({message:"start the claim-loop now?",initialValue:!0}))){Qc("registered. start later with `codepipe worker`.");return}Qc("starting the claim-loop\u2026"),await cr(t.profile?{profile:t.profile}:{})}function _m(){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 re=_m();Wo(re);Vo();var ue=new Am;ue.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ce).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await zc()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Sc({configPath:t.config,skipVerify:t.skipVerify===!0}):await mc({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","CLI token (matches HUB_CLI_TOKEN on HUB)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await oi({...t,profile:re})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await gc({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ue.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await ia({profile:re})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await sc({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Pc({profile:re,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Ha({profile:re})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await Nc({profile:re,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var tl=ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");tl.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")??Te(re)?.hubUrl??ge,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&So()){await Co({profile:re});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 n=L("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??L("WORKER_NAME"),i=t.llm??L("WORKER_LLM");await st({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...re?{profile:re}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});tl.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ee(re)&&So()){await Co({profile:re});return}await cr(re?{profile:re}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Om=ue.command("project").description("Manage CodePipe projects");Om.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await _c({profile:re})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.parseAsync();
600
+ `)}catch{}}import{hostname as Rm}from"node:os";import{cancel as Im,confirm as el,intro as Pm,isCancel as nl,log as Bt,multiselect as Em,outro as tl,password as jm,select as vo,text as So}from"@clack/prompts";function wr(t){Im(t),process.exit(1)}function Mt(t){return nl(t)&&wr("aborted"),t}function wn(t){return nl(t)&&wr("aborted"),typeof t=="string"?t:""}function Co(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function rl(t,e){try{let{secret:r}=await qr(t,e);return r}catch(r){throw r instanceof N&&r.status===404&&wr("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 Am(t,e){if(Mt(await vo({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 o=await Os(t,e);if(o.length>0)return Mt(await Em({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));Bt.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Bt.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return wn(await So({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:o=>o.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function To(t){Pm("codepipe worker \u2014 set up this machine as a runner");let e=ee(t.profile);e&&(Bt.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Mt(await el({message:"re-register this worker?",initialValue:!1}))||wr("keeping the existing registration"));let r=Te(t.profile)??Te(),n=wn(await So({message:"HUB URL",placeholder:ge,initialValue:L("HUB_URL")??r?.hubUrl??ge,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Mt(await vo({message:"how to authorize the registration?",options:[...o?[{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:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await rl(n,a),Bt.success("account-issued registration token minted");else if(i==="login"){let p=await mn();a=(await gn(n,p)).cliToken,s=await rl(n,a),Bt.success("account-issued registration token minted")}else s=wn(await jm({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||wr("a registration token is required");let c=await Am(n,a),l=wn(await So({message:"worker name",initialValue:Rm(),validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=Mt(await vo({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 st({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Bt.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Mt(await el({message:"start the claim-loop now?",initialValue:!0}))){tl("registered. start later with `codepipe worker`.");return}tl("starting the claim-loop\u2026"),await lr(t.profile?{profile:t.profile}:{})}function Om(){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 re=Om();Yo(re);Jo();var ue=new _m;ue.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ce).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await Zc()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Rc({configPath:t.config,skipVerify:t.skipVerify===!0}):await yc({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","CLI token (matches HUB_CLI_TOKEN on HUB)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await ii({...t,profile:re})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await wc({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ue.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await ca({profile:re})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await lc({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Ac({profile:re,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Ya({profile:re})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await Dc({profile:re,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var ol=ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");ol.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")??Te(re)?.hubUrl??ge,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Co()){await To({profile:re});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 n=L("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??L("WORKER_NAME"),i=t.llm??L("WORKER_LLM");await st({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...re?{profile:re}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ol.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ee(re)&&Co()){await To({profile:re});return}await lr(re?{profile:re}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Nm=ue.command("project").description("Manage CodePipe projects");Nm.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Uc({profile:re})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.parseAsync();