@code-partner/codepipe 0.3.0 → 0.3.1

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 +114 -113
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,35 +1,35 @@
1
1
  #!/usr/bin/env node
2
- var fe="0.3.0",Te="https://hub.codepipe.dev";var Ie=4,uu=4;function Br(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=uu&&t<=Ie}var je=".codepipe-context.yaml",pr=".devpipe-context.yaml",ii=[{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",je]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[je]}];function Gr(t=2){return`# CodePipe Context Repo format version.
2
+ var me="0.3.1",Te="https://hub.codepipe.dev";var Ie=4,mu=4;function Lr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=mu&&t<=Ie}var je=".codepipe-context.yaml",lr=".devpipe-context.yaml",ai=[{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",je]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[je]}];function Dr(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 si(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 ai(t,e=ii){let r=[];for(let o of e)if(!(o.version<=t))for(let n of o.addedPaths)r.includes(n)||r.push(n);return r}function ci(t,e=ii){return e.filter(r=>r.version>t)}var li=["estimate","analyze","implement","resolve-conflict","rework","draft","build","index","analysis","chat"];function pt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var qe="opus",Mr="sonnet",pu="haiku",Ho=[qe,Mr,pu],ui={analyze:qe,implement:qe,"resolve-conflict":qe,rework:qe,estimate:Mr,build:Mr,draft:Mr,index:qe,analysis:qe,chat:qe};var du=[{id:"llm",label:"LLM",fields:[],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Ho],help:"Overrides the recommended defaults for every role not listed below."},...li.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Ho],help:`recommended: ${ui[t]}`}))]}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on, a task taken from Develop waits in AWAITING_APPROVAL for a manual Approve before analysis starts. Off \u21D2 intake auto-starts the pipeline."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]}];function pi(t=du){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...pi(r.groups));return e}function fu(t,e){let r=JSON.stringify(e);return pi().find(o=>o.file===t&&JSON.stringify(o.path)===r)}function di(t){let e=fu(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,o=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||o&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":return typeof r!="string"?{ok:!1,error:`${e.id} must be a string`}:{ok:!0,field:e,value:r.trim()};case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}}}var dt=/^[a-z][a-z0-9-]{1,30}$/,mu="-codepipe-ctx";function Ge(t){return`${t}${mu}`}var gu=[{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 Fr(t){for(let e of gu){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var dr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function Rt(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let o=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return o?o[1]??null:null}var ft="x-bitbucket-api-token-auth";function Hr(t){switch(t){case dr.gitlab:return"oauth2";case dr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var fi=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as bh}from"commander";import{homedir as wi}from"node:os";import{mkdirSync as Cu,readFileSync as Ru,writeFileSync as Tu,existsSync as Wo}from"node:fs";import{dirname as ki,join as qr,resolve as Iu}from"node:path";import{fileURLToPath as ju}from"node:url";import{existsSync as Kr,readFileSync as gi,readdirSync as yu,writeFileSync as wu}from"node:fs";import{dirname as bu,join as Ye}from"node:path";import{parse as ku}from"yaml";import{existsSync as mi,renameSync as hu}from"node:fs";function mt(t,e,r=o=>console.error(o)){if(mi(e)||!mi(t))return!1;try{return hu(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(o){return r(`failed to migrate ${t} \u2192 ${e}: ${o instanceof Error?o.message:String(o)} \u2014 continuing with the legacy path untouched`),!1}}var Pe=".codepipe",Ko=".devpipe";function $u(t=process.cwd()){let e=t;for(;;){if(Kr(Ye(e,Pe,"project.yaml")))return e;if(Kr(Ye(e,Ko,"project.yaml")))return mt(Ye(e,Ko),Ye(e,Pe))&&xu(e),e;let r=bu(e);if(r===e)return null;e=r}}function vu(t){let e=Ye(t,Pe);return Kr(e)?e:Ye(t,Ko)}function xu(t){let e=Ye(t,".gitignore");if(!Kr(e))return;let r=gi(e,"utf-8"),o=r.split(/\r?\n/).map(n=>{let i=n.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?n.replace(".devpipe",".codepipe"):n}).join(`
6
- `);o!==r&&wu(e,o)}function me(t=process.cwd()){let e=$u(t);if(!e)return null;let r=vu(e),o=Su(gi(Ye(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function hi(t,e,r){return yu(t).filter(n=>n!==".DS_Store").length===0?!0:e?r.some(n=>n.host===e.host&&n.owner===e.owner&&n.repoName===e.repoName):!1}function Wr(t,e=process.cwd()){try{let r=me(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Su(t){let e=ku(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),o=String(e.name??r),n=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of n){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,f=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:o,repos:i}}function yi(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 bi=Iu(ki(ju(import.meta.url)),"..");function $i(t){let e=qr(bi,".env");if(Wo(e)&&process.loadEnvFile(e),t){let r=qr(bi,"profiles",t,".env");Wo(r)&&process.loadEnvFile(r)}}function Tt(t){let e=L("CONFIG");return e||(t?qr(wi(),".codepipe","profiles",t,"config.json"):qr(wi(),".codepipe","config.json"))}function $e(t){let e=Tt(t);if(!Wo(e))return null;let r=Ru(e,"utf-8");return JSON.parse(r)}function Me(t,e){let r=Tt(e);Cu(ki(r),{recursive:!0}),Tu(r,JSON.stringify(t,null,2)+`
7
- `,{mode:384})}function Yr(t){if(t)return{cfg:ge(t),profile:t};let e;try{e=me()?.spec.projectId||void 0}catch{}if(e){let r=$e(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:ge(void 0),profile:void 0}}function ge(t){let e=$e(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Tt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as vi}from"node:os";import{join as xi}from"node:path";function Si(){mt(xi(vi(),".devpipe"),xi(vi(),".codepipe"))}import{homedir as Ci}from"node:os";import{existsSync as Ri,mkdirSync as Ti,readFileSync as Ii,writeFileSync as ji}from"node:fs";import{dirname as Pi,join as Ei}from"node:path";function Vr(t,e,r){let o=U(t);if(!o)return"mismatch";let n=o.sandboxPins??{},i=n[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(n[e]=r,o.sandboxPins=n,V(o),"pinned")}function Ai(t,e){let r=U(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],V(r),!0):!1}function Ee(t){return Ei(Ci(),".codepipe","secrets",`${t}.json`)}function U(t){let e=Ee(t);return Ri(e)?JSON.parse(Ii(e,"utf-8")):null}function V(t){let e=Ee(t.projectId);Ti(Pi(e),{recursive:!0}),ji(e,JSON.stringify(t,null,2)+`
8
- `,{mode:384})}function Jr(){return Ei(Ci(),".codepipe","shared.json")}function qo(){let t=Jr();return Ri(t)?JSON.parse(Ii(t,"utf-8")):null}function _i(t){let e=Jr();Ti(Pi(e),{recursive:!0}),ji(e,JSON.stringify(t,null,2)+`
9
- `,{mode:384})}function It(t){let e=U(t)?.claude?.oauthToken;return e||qo()?.claude?.oauthToken}function fr(t){let e=(r,o)=>{o&&!process.env[r]&&(process.env[r]=o)};e("GH_TOKEN",t.github?.token),e("BITBUCKET_EMAIL",t.bitbucket?.email),e("BITBUCKET_API_TOKEN",t.bitbucket?.apiToken),e("GITLAB_TOKEN",t.gitlab?.token),e("YOUTRACK_URL",t.youtrack?.url),e("YOUTRACK_TOKEN",t.youtrack?.token)}function jt(){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=$e(e);r&&!t.force&&(console.error(`already configured at ${Tt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");Me({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...U(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};V(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${Tt(e)}`)}import{homedir as vn}from"node:os";import{join as Sr}from"node:path";import{appendFileSync as Pu,existsSync as Ni,mkdirSync as Eu,renameSync as Ui,statSync as Au,unlinkSync as _u}from"node:fs";import{Writable as Ou}from"node:stream";import{join as Nu}from"node:path";var Li={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Pt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Eu(e.dir,{recursive:!0}),this.currentPath=Nu(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 ci(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 li(t,e=ai){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 ui(t,e=ai){return e.filter(r=>r.version>t)}var pi=["estimate","analyze","implement","resolve-conflict","rework","draft","build","index","analysis","chat"];function pt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var qe="opus",Br="sonnet",gu="haiku",Hn=[qe,Br,gu],di={analyze:qe,implement:qe,"resolve-conflict":qe,rework:qe,estimate:Br,build:Br,draft:Br,index:qe,analysis:qe,chat:qe};var hu=[{id:"llm",label:"LLM",fields:[],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Hn],help:"Overrides the recommended defaults for every role not listed below."},...pi.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Hn],help:`recommended: ${di[t]}`}))]}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on, a task taken from Develop waits in AWAITING_APPROVAL for a manual Approve before analysis starts. Off \u21D2 intake auto-starts the pipeline."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]}];function fi(t=hu){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...fi(r.groups));return e}function yu(t,e){let r=JSON.stringify(e);return fi().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function mi(t){let e=yu(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":return typeof r!="string"?{ok:!1,error:`${e.id} must be a string`}:{ok:!0,field:e,value:r.trim()};case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}}}var dt=/^[a-z][a-z0-9-]{1,30}$/,wu="-codepipe-ctx";function Ge(t){return`${t}${wu}`}var bu=[{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 Gr(t){for(let e of bu){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var ur={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function Ct(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 ft="x-bitbucket-api-token-auth";function Mr(t){switch(t){case ur.gitlab:return"oauth2";case ur.bitbucket:return"x-token-auth";default:return"x-access-token"}}var gi=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Ah}from"commander";import{homedir as ki}from"node:os";import{mkdirSync as ju,readFileSync as Pu,writeFileSync as Eu,existsSync as Wn}from"node:fs";import{dirname as vi,join as Kr,resolve as Au}from"node:path";import{fileURLToPath as _u}from"node:url";import{existsSync as Fr,readFileSync as yi,readdirSync as $u,writeFileSync as vu}from"node:fs";import{dirname as xu,join as Ye}from"node:path";import{parse as Su}from"yaml";import{existsSync as hi,renameSync as ku}from"node:fs";function mt(t,e,r=n=>console.error(n)){if(hi(e)||!hi(t))return!1;try{return ku(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 Pe=".codepipe",Kn=".devpipe";function Cu(t=process.cwd()){let e=t;for(;;){if(Fr(Ye(e,Pe,"project.yaml")))return e;if(Fr(Ye(e,Kn,"project.yaml")))return mt(Ye(e,Kn),Ye(e,Pe))&&Tu(e),e;let r=xu(e);if(r===e)return null;e=r}}function Ru(t){let e=Ye(t,Pe);return Fr(e)?e:Ye(t,Kn)}function Tu(t){let e=Ye(t,".gitignore");if(!Fr(e))return;let r=yi(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&&vu(e,n)}function ge(t=process.cwd()){let e=Cu(t);if(!e)return null;let r=Ru(e),n=Iu(yi(Ye(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function wi(t,e,r){return $u(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 Hr(t,e=process.cwd()){try{let r=ge(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Iu(t){let e=Su(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 bi(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 $i=Au(vi(_u(import.meta.url)),"..");function xi(t){let e=Kr($i,".env");if(Wn(e)&&process.loadEnvFile(e),t){let r=Kr($i,"profiles",t,".env");Wn(r)&&process.loadEnvFile(r)}}function Rt(t){let e=L("CONFIG");return e||(t?Kr(ki(),".codepipe","profiles",t,"config.json"):Kr(ki(),".codepipe","config.json"))}function $e(t){let e=Rt(t);if(!Wn(e))return null;let r=Pu(e,"utf-8");return JSON.parse(r)}function Me(t,e){let r=Rt(e);ju(vi(r),{recursive:!0}),Eu(r,JSON.stringify(t,null,2)+`
7
+ `,{mode:384})}function Wr(t){if(t)return{cfg:he(t),profile:t};let e;try{e=ge()?.spec.projectId||void 0}catch{}if(e){let r=$e(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:he(void 0),profile:void 0}}function he(t){let e=$e(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 ${Rt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as Si}from"node:os";import{join as Ci}from"node:path";function Ri(){mt(Ci(Si(),".devpipe"),Ci(Si(),".codepipe"))}import{homedir as Ti}from"node:os";import{existsSync as Ii,mkdirSync as ji,readFileSync as Pi,writeFileSync as Ei}from"node:fs";import{dirname as Ai,join as _i}from"node:path";function qr(t,e,r){let n=U(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,V(n),"pinned")}function Oi(t,e){let r=U(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],V(r),!0):!1}function Ee(t){return _i(Ti(),".codepipe","secrets",`${t}.json`)}function U(t){let e=Ee(t);return Ii(e)?JSON.parse(Pi(e,"utf-8")):null}function V(t){let e=Ee(t.projectId);ji(Ai(e),{recursive:!0}),Ei(e,JSON.stringify(t,null,2)+`
8
+ `,{mode:384})}function Yr(){return _i(Ti(),".codepipe","shared.json")}function qn(){let t=Yr();return Ii(t)?JSON.parse(Pi(t,"utf-8")):null}function Ni(t){let e=Yr();ji(Ai(e),{recursive:!0}),Ei(e,JSON.stringify(t,null,2)+`
9
+ `,{mode:384})}function Tt(t){let e=U(t)?.claude?.oauthToken;return e||qn()?.claude?.oauthToken}function pr(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 It(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Ui(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=$e(e);r&&!t.force&&(console.error(`already configured at ${Rt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Me({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...U(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};V(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Rt(e)}`)}import{homedir as So}from"node:os";import{join as vr}from"node:path";import{appendFileSync as Ou,existsSync as Li,mkdirSync as Nu,renameSync as Di,statSync as Uu,unlinkSync as Lu}from"node:fs";import{Writable as Du}from"node:stream";import{join as Bu}from"node:path";var Bi={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},jt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Nu(e.dir,{recursive:!0}),this.currentPath=Bu(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
- `;Pu(this.currentPath,r,"utf-8")}asWritable(){return new Ou({write:(e,r,o)=>{try{let n=typeof e=="string"?e:e.toString("utf-8");for(let i of n.split(/\r?\n/))i&&this.writeLine(i);o()}catch(n){o(n)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!Ni(this.currentPath)||Au(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;Ni(o)&&(r>=this.cfg.maxFiles?_u(o):Ui(o,`${this.currentPath}.${r+1}`))}Ui(this.currentPath,`${this.currentPath}.1`)}}};function zr(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=Uu(process.env[`${t}_MAX_BYTES`]??String(Li.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Li.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function Uu(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),o=(e[2]??"").toLowerCase();return o==="g"?r*1024**3:o==="m"?r*1024**2:o==="k"?r*1024:r}function Xr(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(o,n)=>(...i)=>{o(...i);try{t.writeLine(Lu(n,i))}catch{}};return console.log=r(e.log,"INFO"),console.warn=r(e.warn,"WARN"),console.error=r(e.error,"ERROR"),()=>{console.log=e.log,console.warn=e.warn,console.error=e.error}}function Lu(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:Du(n)).join(" ");return`${r} ${t} ${o}`}function Du(t){try{return JSON.stringify(t)}catch{return String(t)}}import{existsSync as Ua,rmSync as Yd}from"node:fs";import{join as xr}from"node:path";import{simpleGit as Vd}from"simple-git";import"ws";import{createHash as Bu}from"node:crypto";import{existsSync as Gu,readFileSync as Mu}from"node:fs";import{homedir as Fu,hostname as Yo}from"node:os";import{join as Hu}from"node:path";function Di(t){return Bu("sha256").update(t).digest("hex").slice(0,12)}function Ku(){let t=L("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Hu(Fu(),".claude","credentials.json");if(!Gu(e))return;let r=JSON.parse(Mu(e,"utf-8")),o=[r.email,r.account?.email,r.user?.email];for(let n of o)if(typeof n=="string"&&n.includes("@"))return n.trim().toLowerCase()}catch{}}function Bi(t){let e=Ku(),r=L("ACCOUNT_ID")?.trim(),o=L("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=It(t);return n?{accountId:`acct-${Di(n)}`,label:o||Yo(),...e?{email:e}:{}}:{accountId:`acct-${Di(`host:${Yo()}`)}`,label:o||Yo(),...e?{email:e}:{}}}import{existsSync as Wu}from"node:fs";import{join as qu}from"node:path";import{simpleGit as Yu}from"simple-git";async function Gi(t,e){if(!Wu(qu(t,".git")))return{status:"skipped"};let r=Yu(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${Vu(n)}`}}let o=await r.status();if(!o.isClean())return{status:"warn",reason:"uncommitted changes \u2014 working copy left as-is"};if(o.current!==e)return{status:"warn",reason:`on '${o.current??"detached HEAD"}', not '${e}' \u2014 not fast-forwarded`};try{await r.merge(["--ff-only",`origin/${e}`])}catch{return{status:"warn",reason:`'${e}' can't fast-forward to origin (diverged) \u2014 not updated`}}return{status:"updated"}}function Vu(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Vo,readFileSync as Mi,readdirSync as Ju,watch as zu}from"node:fs";import{join as Jo}from"node:path";var Qr=class{constructor(e,r,o,n,i=6e4){this.contextDir=e;this.projectId=r;this.send=o;this.log=n;this.intervalMs=i}timer=null;watcher=null;debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){if(this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null,this.watcher)try{this.watcher.close()}catch{}this.watcher=null}installWatcher(){if(Vo(this.contextDir))try{this.watcher=zu(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=Jo(this.contextDir,e);if(!Vo(r))return null;try{return Mi(r,"utf-8")}catch{return null}}readPrompts(){let e=Jo(this.contextDir,"prompts"),r={};if(!Vo(e))return r;let o;try{o=Ju(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=Mi(Jo(e,n),"utf-8")}catch{}}return r}};import{existsSync as Vi,readFileSync as Ji,readdirSync as sp}from"node:fs";import{join as zi}from"node:path";import{simpleGit as ap}from"simple-git";import{existsSync as ep,mkdirSync as tp,writeFileSync as Ki}from"node:fs";import{dirname as rp,isAbsolute as op,join as qi,normalize as en}from"node:path";import{simpleGit as Yi}from"simple-git";import{existsSync as Ve,mkdirSync as Fi,readFileSync as zo,writeFileSync as Et}from"node:fs";import{homedir as Xu}from"node:os";import{join as Ae}from"node:path";import{simpleGit as Qu}from"simple-git";var At=["project.yaml","regimen.yaml"];function mr(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=Ae(t,n);Ve(s)||(Et(s,i),r.push(n))}return r}function gt(t,e,r){let o=Ae(Xu(),".codepipe","profiles",t,"context-config");return Fi(o,{recursive:!0}),Et(Ae(o,"project.yaml"),e.projectYaml),Et(Ae(o,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${o}`),o}function Zr(t,e,r){if(Ve(e))for(let o of At){let n=Ae(e,o),i=Ae(t,o);if(!(!Ve(n)||Ve(i)))try{Et(i,zo(n)),r.info(`[config] seeded local ${o} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${o}: ${s instanceof Error?s.message:String(s)}`)}}}var Zu=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function _t(t){let e=Ae(t,".gitignore"),r=Ve(e)?zo(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(At.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
11
+ `;Ou(this.currentPath,r,"utf-8")}asWritable(){return new Du({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||!Li(this.currentPath)||Uu(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Li(n)&&(r>=this.cfg.maxFiles?Lu(n):Di(n,`${this.currentPath}.${r+1}`))}Di(this.currentPath,`${this.currentPath}.1`)}}};function Vr(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Gu(process.env[`${t}_MAX_BYTES`]??String(Bi.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Bi.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Gu(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),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(Mu(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 Mu(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Fu(o)).join(" ");return`${r} ${t} ${n}`}function Fu(t){try{return JSON.stringify(t)}catch{return String(t)}}import{existsSync as Ga,rmSync as af}from"node:fs";import{join as $r}from"node:path";import{simpleGit as cf}from"simple-git";import"ws";import{createHash as Hu}from"node:crypto";import{existsSync as Ku,readFileSync as Wu}from"node:fs";import{homedir as qu,hostname as Yn}from"node:os";import{join as Yu}from"node:path";function Gi(t){return Hu("sha256").update(t).digest("hex").slice(0,12)}function Vu(){let t=L("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Yu(qu(),".claude","credentials.json");if(!Ku(e))return;let r=JSON.parse(Wu(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 Mi(t){let e=Vu(),r=L("ACCOUNT_ID")?.trim(),n=L("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Tt(t);return o?{accountId:`acct-${Gi(o)}`,label:n||Yn(),...e?{email:e}:{}}:{accountId:`acct-${Gi(`host:${Yn()}`)}`,label:n||Yn(),...e?{email:e}:{}}}import{existsSync as Ju}from"node:fs";import{join as zu}from"node:path";import{simpleGit as Xu}from"simple-git";async function Fi(t,e){if(!Ju(zu(t,".git")))return{status:"skipped"};let r=Xu(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Qu(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 Qu(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Vn,readFileSync as Hi,readdirSync as Zu,watch as ep}from"node:fs";import{join as Jn}from"node:path";var zr=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(Vn(this.contextDir))try{this.watcher=ep(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=Jn(this.contextDir,e);if(!Vn(r))return null;try{return Hi(r,"utf-8")}catch{return null}}readPrompts(){let e=Jn(this.contextDir,"prompts"),r={};if(!Vn(e))return r;let n;try{n=Zu(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Hi(Jn(e,o),"utf-8")}catch{}}return r}};import{existsSync as zi,readFileSync as Xi,readdirSync as up}from"node:fs";import{join as Qi}from"node:path";import{simpleGit as pp}from"simple-git";import{existsSync as op,mkdirSync as ip,writeFileSync as qi}from"node:fs";import{dirname as sp,isAbsolute as ap,join as Vi,normalize as eo}from"node:path";import{simpleGit as Ji}from"simple-git";import{existsSync as Ve,mkdirSync as Ki,readFileSync as zn,writeFileSync as Pt}from"node:fs";import{homedir as tp}from"node:os";import{join as Ae}from"node:path";import{simpleGit as rp}from"simple-git";var Et=["project.yaml","regimen.yaml"];function dr(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Ae(t,o);Ve(s)||(Pt(s,i),r.push(o))}return r}function gt(t,e,r){let n=Ae(tp(),".codepipe","profiles",t,"context-config");return Ki(n,{recursive:!0}),Pt(Ae(n,"project.yaml"),e.projectYaml),Pt(Ae(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Xr(t,e,r){if(Ve(e))for(let n of Et){let o=Ae(e,n),i=Ae(t,n);if(!(!Ve(o)||Ve(i)))try{Pt(i,zn(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 np=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function At(t){let e=Ae(t,".gitignore"),r=Ve(e)?zn(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Et.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
12
12
  `)?"":`
13
- `;return Et(e,r+i+Zu.join(`
13
+ `;return Pt(e,r+i+np.join(`
14
14
  `)+`
15
- `),!0}async function Hi(t,e){try{if(!Ve(Ae(t,".git")))return;let r=Qu(t),o=(await r.raw(["ls-files","--",...At])).split(`
16
- `).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;_t(t),await r.raw(["rm","--cached","--quiet","--",...o]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await Zo(t),e.info(`[config] migrated ${o.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function Xo(t){let e=new Map;for(let r of At){let o=Ae(t,r);Ve(o)&&e.set(r,zo(o))}return e}function Qo(t,e){Fi(t,{recursive:!0});for(let[r,o]of e){let n=Ae(t,r);Ve(n)||Et(n,o)}}var Wi=3,np=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function Ot(t,e,r){if(!ep(qi(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Je(t,i.path);tp(rp(s),{recursive:!0}),i.encoding==="base64"?Ki(s,Buffer.from(i.content,"base64")):Ki(s,i.content)}let o=Yi(t);await o.add(["-A","--","."]),await o.raw(["reset","-q","--",...At]).catch(()=>{}),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await Zo(t))}async function Zo(t){let e=Yi(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=Wi;o++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let n=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${n}`])}catch{let i=await ip(e);if(i.length>0&&i.every(s=>np.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 ${Wi} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function ip(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
- `).map(r=>r.trim()).filter(Boolean)}function Je(t,e){if(op(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=en(qi(t,e)),o=en(t+"/");if(r!==en(t)&&!r.startsWith(o))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var cp=/^(\d{4})-(.+)\.md$/,lp="0000-template.md";function up(t){let e=t.split(`
18
- `),r=e.find(i=>i.startsWith("# ")),o=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",n=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:o,status:n("Status"),date:n("Date")}}function pp(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
19
- `),a=s.findIndex(k=>k.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 k=g;k<s.length;k++){let y=(s[k]??"").trim();if(y===""){g=k+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!$)break;let v=($[1]??"").trim().toLowerCase(),N=($[2]??"").trim(),P=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);P&&(p=parseInt(P[1]??"",10)),v==="tasks"&&(f=N),l.has(v)||u.push(y),g=k+1}let d=f?f.includes(o)?f:`${f}, ${o}`:o,h=s.slice(g).join(`
20
- `).replace(/^\n+/,""),C=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${n}`,`- **Tasks:** ${d}`,...u,"",h].join(`
15
+ `),!0}async function Wi(t,e){try{if(!Ve(Ae(t,".git")))return;let r=rp(t),n=(await r.raw(["ls-files","--",...Et])).split(`
16
+ `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;At(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 Zn(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 Xn(t){let e=new Map;for(let r of Et){let n=Ae(t,r);Ve(n)&&e.set(r,zn(n))}return e}function Qn(t,e){Ki(t,{recursive:!0});for(let[r,n]of e){let o=Ae(t,r);Ve(o)||Pt(o,n)}}var Yi=3,cp=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function _t(t,e,r){if(!op(Vi(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Je(t,i.path);ip(sp(s),{recursive:!0}),i.encoding==="base64"?qi(s,Buffer.from(i.content,"base64")):qi(s,i.content)}let n=Ji(t);await n.add(["-A","--","."]),await n.raw(["reset","-q","--",...Et]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await Zn(t))}async function Zn(t){let e=Ji(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Yi;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 lp(e);if(i.length>0&&i.every(s=>cp.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 ${Yi} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function lp(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
+ `).map(r=>r.trim()).filter(Boolean)}function Je(t,e){if(ap(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=eo(Vi(t,e)),n=eo(t+"/");if(r!==eo(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var dp=/^(\d{4})-(.+)\.md$/,fp="0000-template.md";function mp(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 gp(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
19
+ `),a=s.findIndex(k=>k.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 k=g;k<s.length;k++){let y=(s[k]??"").trim();if(y===""){g=k+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!$)break;let v=($[1]??"").trim().toLowerCase(),N=($[2]??"").trim(),P=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);P&&(p=parseInt(P[1]??"",10)),v==="tasks"&&(f=N),l.has(v)||u.push(y),g=k+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
21
  `);return{content:C.endsWith(`
22
22
  `)?C:C+`
23
- `,supersedes:p}}function dp(t,e){let r=String(e).padStart(4,"0"),o=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return o===t?t.replace(/^(# .*)$/m,`$1
23
+ `,supersedes:p}}function hp(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
24
 
25
- - **Status:** superseded by ADR-${r}`):o}function fp(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((o,n)=>o.num-n.num)){let o=String(r.num).padStart(4,"0"),n=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${o} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${n}`)}return e.join(`
25
+ - **Status:** superseded by ADR-${r}`):n}function yp(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 Xi(t,e,r,o=new Date().toISOString().slice(0,10)){try{await ap(t).pull(void 0,void 0,["--rebase"])}catch{}let n=[],i=[];for(let d of r){let h=Je(t,`tasks/${e}/adr/DRAFT-${d}.md`);if(!Vi(h)){i.push(d);continue}n.push({slug:d,content:Ji(h,"utf-8")})}let s=zi(t,"adr"),a=new Map;if(Vi(s))for(let d of sp(s)){let h=cp.exec(d);!h||d===lp||a.set(d,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:Ji(zi(s,d),"utf-8")})}let c=Math.max(0,...[...a.values()].map(d=>d.num))+1,l=new Map,u=[],f=[];for(let d of n){if([...a.entries()].find(([,v])=>v.slug===d.slug&&v.content.includes(e))){f.push(d.slug);continue}let C=c++,k=`${String(C).padStart(4,"0")}-${d.slug}.md`,{content:y,supersedes:$}=pp(d.content,C,d.slug,e,o);if(l.set(k,y),a.set(k,{num:C,slug:d.slug,content:y}),u.push(`adr/${k}`),$!==null){let v=[...a.keys()].find(N=>N.startsWith(`${String($).padStart(4,"0")}-`));if(v&&v!==k){let N=dp(l.get(v)??a.get(v).content,C);l.set(v,N),a.set(v,{...a.get(v),content:N})}}}if(u.length===0)return{promoted:u,skipped:f,missing:i};let p=[...a.entries()].map(([d,h])=>({num:h.num,file:d,header:up(h.content)}));l.set("INDEX.md",fp(p));let g=[...l.entries()].map(([d,h])=>({path:`adr/${d}`,content:h}));return await Ot(t,g,`adr(${e}): promote ${n.map(d=>d.slug).join(", ")}`),{promoted:u,skipped:f,missing:i}}import{existsSync as Qi,readFileSync as gp}from"node:fs";import{join as Zi}from"node:path";function hp(t){for(let e of[je,pr]){let r=Zi(t,e);if(Qi(r))try{return si(gp(r,"utf-8"))}catch{return 0}}return 0}function yp(t,e,r,o=2){let n=e<o,i=n?ai(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function eo(t,e){return yp(e,hp(t),r=>Qi(Zi(t,r)))}import{existsSync as os,mkdirSync as Ap,mkdtempSync as _p,rmSync as ns,writeFileSync as is}from"node:fs";import{tmpdir as Op}from"node:os";import{dirname as Np,join as ro}from"node:path";import{simpleGit as sn}from"simple-git";var ht=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function es(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
28
- `+t.slice(t.length-e)}async function ze(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let i=(await o.json()).login??"ok",s=o.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(c.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function to(t,e,r){let o=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,n;try{n=await fetch(o,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(n.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!n.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${n.status} ${n.statusText}`);if((await n.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function Xe(t,e,r){let o=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",n;try{n=await fetch(o,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(n.ok)return t;if(n.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await wp(n);throw n.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):n.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):n.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${n.status} ${n.statusText}${i}`)}async function wp(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Qe(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(o){throw new Error(`cannot reach gitlab.com (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function rs(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let o=(await e.json()).scopes??[];return o.length>0&&!o.includes("api")?`GitLab token scopes [${o.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}var tn=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!o.ok)throw new Error(`bitbucket pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.links?.html?.href??"",number:n.id}}async findOpenPrByBranch(e,r){let o=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${o}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let s=(await n.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let o=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(n.status===404)throw new ht(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,o,n){let i=o==="squash"?"squash":o==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:n})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:o}})});if(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!n.ok)throw new Error(`bitbucket decline PR #${r}: ${n.status} ${await n.text()}`)}},rn=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!o.ok)throw new Error(`github pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.html_url,number:n.number}}async findOpenPrByBranch(e,r){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let i=(await o.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let o=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(n.status===404)throw new ht(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let f of u.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let f of l.filter(p=>p.conclusion&&i.includes(p.conclusion))){let p=await fetch(`${n}/actions/runs/${f.id}/jobs?per_page=50`,{headers:o});if(!p.ok)continue;let g=(await p.json()).jobs??[];for(let d of g.filter(h=>h.conclusion==="failure")){let h=await fetch(`${n}/actions/jobs/${d.id}/logs`,{headers:o});if(!h.ok)continue;let C=await h.text();u.push(`### CI job: ${d.name}
27
+ `}async function Zi(t,e,r,n=new Date().toISOString().slice(0,10)){try{await pp(t).pull(void 0,void 0,["--rebase"])}catch{}let o=[],i=[];for(let d of r){let h=Je(t,`tasks/${e}/adr/DRAFT-${d}.md`);if(!zi(h)){i.push(d);continue}o.push({slug:d,content:Xi(h,"utf-8")})}let s=Qi(t,"adr"),a=new Map;if(zi(s))for(let d of up(s)){let h=dp.exec(d);!h||d===fp||a.set(d,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:Xi(Qi(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(([,v])=>v.slug===d.slug&&v.content.includes(e))){f.push(d.slug);continue}let C=c++,k=`${String(C).padStart(4,"0")}-${d.slug}.md`,{content:y,supersedes:$}=gp(d.content,C,d.slug,e,n);if(l.set(k,y),a.set(k,{num:C,slug:d.slug,content:y}),u.push(`adr/${k}`),$!==null){let v=[...a.keys()].find(N=>N.startsWith(`${String($).padStart(4,"0")}-`));if(v&&v!==k){let N=hp(l.get(v)??a.get(v).content,C);l.set(v,N),a.set(v,{...a.get(v),content:N})}}}if(u.length===0)return{promoted:u,skipped:f,missing:i};let p=[...a.entries()].map(([d,h])=>({num:h.num,file:d,header:mp(h.content)}));l.set("INDEX.md",yp(p));let g=[...l.entries()].map(([d,h])=>({path:`adr/${d}`,content:h}));return await _t(t,g,`adr(${e}): promote ${o.map(d=>d.slug).join(", ")}`),{promoted:u,skipped:f,missing:i}}import{existsSync as es,readFileSync as bp}from"node:fs";import{join as ts}from"node:path";function kp(t){for(let e of[je,lr]){let r=ts(t,e);if(es(r))try{return ci(bp(r,"utf-8"))}catch{return 0}}return 0}function $p(t,e,r,n=2){let o=e<n,i=o?li(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Qr(t,e){return $p(e,kp(t),r=>es(ts(t,r)))}import{existsSync as is,mkdirSync as Up,mkdtempSync as Lp,rmSync as ss,writeFileSync as as}from"node:fs";import{tmpdir as Dp}from"node:os";import{dirname as Bp,join as en}from"node:path";import{simpleGit as io}from"simple-git";var ht=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function rs(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
28
+ `+t.slice(t.length-e)}async function ze(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},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 Zr(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 Xe(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 vp(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 vp(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Qe(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 os(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 to=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 ht(`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()}`)}},ro=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 ht(`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
- ${es(C,8e3)}`)}}return u.length===0?void 0:es(u.join(`
30
+ ${rs(C,8e3)}`)}}return u.length===0?void 0:rs(u.join(`
31
31
 
32
- `),16e3)}catch{return}}async mergePR(e,r,o,n){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:o})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(n){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!n.ok)throw new Error(`github close PR #${r}: ${n.status} ${await n.text()}`)}},on=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!o.ok)throw new Error(`gitlab mr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.web_url??"",number:n.iid}}async findOpenPrByBranch(e,r){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!o.ok)return null;let i=(await o.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let o=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,n=await fetch(o,{method:"GET",headers:this.headers()});if(n.status===404)throw new ht(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(n.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=bp(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,o,n){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:o==="squash",should_remove_source_branch:n,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!n.ok)throw new Error(`gitlab close MR !${r}: ${n.status} ${await n.text()}`)}};function bp(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 nn=class{name="mock";async createPullRequest(e,r){let o=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${o}`,number:o}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,o,n){throw new Error(ts(e,r,"merge"))}async closePR(e,r,o){throw new Error(ts(e,r,"close"))}};function ts(t,e,r){let o=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${o}`}function Fe(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new rn(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new tn(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new on(e)}return new nn}function Nt(t,e,r,o){return[{path:"README.md",content:jp(t,e)},{path:".gitignore",content:Sp()},{path:"CLAUDE.md",content:Rp(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Cp()},{path:"knowledge/README.md",content:Tp()},{path:"knowledge/build.yaml",content:Ip()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:xp()},{path:"adr/README.md",content:kp()},{path:"adr/0000-template.md",content:$p()},{path:"adr/INDEX.md",content:vp()},{path:je,content:Gr()}]}function kp(){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()}`)}},no=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 ht(`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=xp(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=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async closePR(e,r,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 xp(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 oo=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(ns(e,r,"merge"))}async closePR(e,r,n){throw new Error(ns(e,r,"close"))}};function ns(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 Fe(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new ro(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new to(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new no(e)}return new oo}function Ot(t,e,r,n){return[{path:"README.md",content:_p(t,e)},{path:".gitignore",content:Ip()},{path:"CLAUDE.md",content:Pp(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:jp()},{path:"knowledge/README.md",content:Ep()},{path:"knowledge/build.yaml",content:Ap()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Tp()},{path:"adr/README.md",content:Sp()},{path:"adr/0000-template.md",content:Cp()},{path:"adr/INDEX.md",content:Rp()},{path:je,content:Dr()}]}function Sp(){return`# ADR \u2014 architecture decision records
33
33
 
34
34
  Accepted architectural decisions of this project \u2014 its **framework**. The
35
35
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -57,7 +57,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
57
57
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
58
58
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
59
59
  open a PR to this repository.
60
- `}function $p(){return`# ADR-NNNN: <title>
60
+ `}function Cp(){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 vp(){return`# ADR index
82
+ `}function Rp(){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 xp(){return`# Audit
87
+ `}function Tp(){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 _e(t,e,r,o){return{projectYaml:Pp(t,r,o),regimenYaml:Ep(t.automationLevel,e)}}function Sp(){return`# codepipe project config is local to each member's workspace
96
+ `}function _e(t,e,r,n){return{projectYaml:Op(t,r,n),regimenYaml:Np(t.automationLevel,e)}}function Ip(){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 Cp(){return`# Index prompt
103
+ `}function jp(){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 Rp(t){return`# Project context for the CodePipe agent
160
+ `}function Pp(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 Tp(){return`# Knowledge
188
+ `}function Ep(){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 Ip(){return`# BUILD phase config. Discovered & maintained by the agent.
205
+ `}function Ap(){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 jp(t,e){return`# ${e.name}
221
+ `}function _p(t,e){return`# ${e.name}
222
222
 
223
223
  Context Repo for the **${t.name}** project (CodePipe).
224
224
 
@@ -244,11 +244,11 @@ 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 Pp(t,e,r){let o=e?`
247
+ `}function Op(t,e,r){let n=e?`
248
248
  tracker_url: ${e}`:`
249
- # tracker_url: https://your.youtrack.cloud`,n=r?`require_assignee: true
249
+ # tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
250
250
  assignee: ${r}`:`require_assignee: false
251
- # assignee: your.youtrack.login`,i=t.youtrackProjectKey?` project_key: ${t.youtrackProjectKey}${o}
251
+ # assignee: your.youtrack.login`,i=t.youtrackProjectKey?` project_key: ${t.youtrackProjectKey}${n}
252
252
  poll_interval_sec: 60
253
253
  # Name of the YT workflow field the board is driven by. Default: Stage
254
254
  # (custom field); YouTrack's standard configuration uses State.
@@ -271,7 +271,7 @@ Automation level: **${t.automationLevel}**.
271
271
  # behavior unchanged. When true, CodePipe only pulls tasks of the given
272
272
  # assignee (YT login) into the pipeline; without assignee \u2014 any task with a
273
273
  # non-empty assignee. assignee only takes effect when require_assignee=true.
274
- ${n}`:` # project_key: \u2026
274
+ ${o}`:` # project_key: \u2026
275
275
  # tracker_url: https://your.youtrack.cloud
276
276
  poll_interval_sec: 60`,s=t.repos.length===0?` [] # add repos here
277
277
  `:t.repos.map(a=>` - name: ${a.name}
@@ -310,7 +310,7 @@ branch:
310
310
 
311
311
  repos:
312
312
  ${s}
313
- `}function Ep(t,e){let r=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
313
+ `}function Np(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
 
@@ -320,11 +320,11 @@ youtrack:
320
320
  # These flags are set from a dedicated 'codepipe init' question and do
321
321
  # NOT depend on automation.level \u2014 the two are orthogonal axes (writes vs gates).
322
322
  writes:
323
- enabled: ${o}
324
- status_changes: ${o}
325
- pr_comment: ${o}
323
+ enabled: ${n}
324
+ status_changes: ${n}
325
+ pr_comment: ${n}
326
326
  # Mirror dashboard comments back into YouTrack. Off without enabled.
327
- dashboard_mirror: ${o}
327
+ dashboard_mirror: ${n}
328
328
  # YT column (Stage) for new drafts published from PLAN.
329
329
  # Backlog by default \u2192 the task shows up in the TODO section, not straight in WORK.
330
330
  draft_target_status: Backlog
@@ -423,32 +423,33 @@ llm:
423
423
  # # the previous task's branch (auto-merge without reworking the
424
424
  # # tail of the chain).
425
425
  # mode: parallel
426
- `}function Up(t){return`codepipe/context-migration-v${t}`}function Lp(t){let e=ci(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 \`${je}\` stamp (renamed from \`${pr}\``,"when the legacy file is present). Hand-edited files are never touched.","","## Format changes",""];for(let o of e){r.push(`- **v${o.version}** \u2014 ${o.summary}`);for(let n of o.addedPaths)r.push(` - \`${n}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
427
- `)}async function ss(t,e,r,o){let n=sn(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=eo(t,e);if(!i.outdated)return i;let s=Up(i.currentVersion),a=r?.branch??(await n.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await n.fetch().catch(()=>{}),(await n.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await Dp(t,e,r,i,s,a,o):o.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return o.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Fe(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return o.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let f=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Lp(i)});return o.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(l){return o.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function Dp(t,e,r,o,n,i,s){let a=sn(t),c=_p(ro(Op(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",n,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map(Nt(l,u).map(h=>[h.path,h.content])),p=0;for(let h of o.missingPaths){if(h===je)continue;let C=f.get(h);if(C==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let k=ro(c,h);os(k)||(Ap(Np(k),{recursive:!0}),is(k,C),p++)}is(ro(c,je),Gr(o.currentVersion)),p++;let g=ro(c,pr);os(g)&&(ns(g,{force:!0}),p++);let d=sn(c);await d.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await d.commit(`chore(context): migrate format v${o.templateVersion} -> v${o.currentVersion}`),await d.push(["-u","origin",n]),s.info(`[ctx] migration branch ${n} pushed (${p} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),ns(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{existsSync as Bp,readFileSync as Gp,writeFileSync as Mp}from"node:fs";import{homedir as Fp}from"node:os";import{join as as}from"node:path";import{parseDocument as Hp}from"yaml";function Kp(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function Wp(t,e){let r=Hp(t);return r.set("repos",e.map(Kp)),r.toString()}function qp(t,e){let r=[as(Fp(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(as(e,"project.yaml")),r}function gr(t,e,r){let o=[],n=[];for(let i of qp(t,r))if(Bp(i))try{let s=Gp(i,"utf-8"),a=Wp(s,e);a!==s&&(Mp(i,a),o.push(i))}catch(s){n.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:o,errors:n}}import{homedir as Yp}from"node:os";import{existsSync as Vp,mkdirSync as Jp}from"node:fs";import{join as an}from"node:path";import{simpleGit as us}from"simple-git";var cs=t=>console.log(t);function ls(t){cs=t}function hr(t,e="info"){cs(t,e)}function ve(t,e,r){let o=r??an(Yp(),".codepipe","repos");return an(o,t,e)}async function oo(t,e,r={}){let o=ve(t,e.name,r.baseDir),n=r.cloneUrlOverride??cn(e);if(!Vp(an(o,".git"))){Jp(o,{recursive:!0});let a=us();hr(`[git] clone ${n} \u2192 ${o}`);try{await a.clone(n,o)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${n}
428
- ${l.trim()}`)}}let i=us(o);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${o}
429
- ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function yr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var ps=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function no(t,e){let{contextRepoCloneUrl:r,deliveryRef:o,deliverySha:n,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${o}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();n&&a!==n&&hr(`[git] delivery ${o} resolved ${a.slice(0,10)} (expected ${n.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await yr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await yr(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...ps,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function ds(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await yr(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await yr(t,n)){let s=(await t.revparse([n])).trim();return await t.raw(["update-ref",o,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",o,i]).catch(()=>{}),i}async function fs(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:f}=r,p=await ds(t,i,()=>no(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let g=`origin/${c}`;if(await yr(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([...ps,"cherry-pick",p])}catch(k){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=k instanceof Error?k.message:String(k);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
430
- ${y.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([o,"--delete",n]).catch(()=>{}),{commit:h}}async function ms(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await ds(t,i,()=>no(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function gs(t,e,r){let{branchName:o,baseBranch:n,mergeMethod:i,deleteBranch:s}=r,a=`origin/${o}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${o}'`)):i==="rebase"?(await t.checkout(["-B",o,a]),await t.rebase([n]),await t.checkout(n),await t.merge(["--ff-only",o])):await t.merge(["--no-ff",a,"-m",`Merge branch '${o}'`]),await t.push(["origin",n]),s&&await t.push(["origin","--delete",o]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function cn(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{createCipheriv as zp,createDecipheriv as Xp,createHash as Qp,createPrivateKey as Zp,createPublicKey as ln,diffieHellman as hs,generateKeyPairSync as ys,hkdfSync as ws,randomBytes as ed}from"node:crypto";var bs=Buffer.from("devpipe-sealedbox-v1","utf-8");function io(){let{publicKey:t,privateKey:e}=ys("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function he(t){let e=Buffer.from(t,"base64");return(Qp("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function He(t,e){let r=ln({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=ys("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=hs({privateKey:n,publicKey:r}),c=Buffer.from(ws("sha256",a,Buffer.concat([i,s]),bs,32)),l=ed(12),u=zp("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 so(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let o=Zp({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=ln({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=ln(o).export({type:"spki",format:"der"}),a=hs({privateKey:o,publicKey:n}),c=Buffer.from(ws("sha256",a,Buffer.concat([i,s]),bs,32)),l=Xp("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 td(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let o=e??t.claude?.oauthToken;return o&&(r.claudeOauthToken=o),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function ks(t,e,r,o){let n=td(e,r);t.sandboxes.length>0&&!n.claudeOauthToken&&o.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!n.contextWrite&&(n.github||n.gitlab||n.bitbucket)&&o.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(n),s=[];for(let a of t.sandboxes){let c=Vr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){o.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&o.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=He(a.publicKey,i)}catch(u){o.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}import{X509Certificate as xs}from"node:crypto";import{readFileSync as rd}from"node:fs";import Ze from"node:tls";var Ss=typeof Ze.getCACertificates=="function"&&typeof Ze.setDefaultCACertificates=="function",$s=!1,vs=new Map,Cs=t=>console.warn(t);function od(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Rs(t=Cs){if($s)return;$s=!0;let e=L("EXTRA_CA_FILE");if(!(!e||!Ss))try{let r=od(rd(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Ze.setDefaultCACertificates([...Ze.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 Ts(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 nd(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
431
- `)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function id(t,e,r){return new Promise((o,n)=>{let i=Ze.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 xs(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function un(t,e,r){return new Promise(o=>{let n=Ze.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{n.end(),o(!0)});n.on("error",()=>o(!1)),n.setTimeout(r,()=>{n.destroy(),o(!1)})})}async function sd(t){try{let e=await fetch(t);return e.ok?new xs(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Is(t,e=443,r=Cs){let o=`${t}:${e}`,n=vs.get(o);if(n)return n;let i=ad(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return vs.set(o,i),i}async function ad(t,e,r){if(!Ss)return!1;let o=8e3;if(await un(t,e,o))return!0;let n=await id(t,e,o),i=Ze.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=nd(n);if(!c)break;let l=await sd(c);if(!l)break;if(s.push(l.toString()),Ze.setDefaultCACertificates([...i,...s]),await un(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;n=l}return un(t,e,o)}function Oe(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ye(t,e,r){Rs();let o={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(o["Content-Type"]="application/json");let n=t.baseUrl+e,i={...r,headers:{...o,...r?.headers??{}}};try{return await fetch(n,i)}catch(s){if(Ts(s)&&await Is(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var js=t=>new Promise(e=>setTimeout(e,t));function cd(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function ld(){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 pn(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=ld(),a=null;for(let c=1;c<=n;c++){let l=null;try{l=await ye(t,r,o)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<n&&cd(l.status,u)){await js(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<n){await js(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function et(t){let e;try{e=await ye(t,"/api/users/me?fields=login,fullName")}catch(o){throw new Error(`cannot reach ${t.baseUrl} (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function As(t){try{let e=await ye(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var wr="Stage",Ps=new Map;async function ud(t,e,r,o){let n=`${e.split("-")[0]}:${o}:${r}`,i=Ps.get(n);if(i)return i;let s=await ye(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===o);if(!c)throw new Error(`yt: issue ${e} has no ${o} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${o} bundle for ${e}`);return Ps.set(n,l.id),l.id}async function _s(t,e,r,o=wr){let n=await ud(t,e,r,o);await pn(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:o,$type:"StateIssueCustomField",value:{id:n,$type:"StateBundleElement"}}]})})}async function Os(t,e,r){return await(await pn(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Ns(t,e,r){let o={};r.summary!==void 0&&(o.summary=r.summary),r.description!==void 0&&(o.description=r.description),await pn(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(o)})}var Es=new Map;async function Us(t,e){let r=Es.get(e);if(r)return r;let o=await ye(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!o.ok)throw new Error(`yt resolveProjectId: ${o.status} ${await o.text()}`);let i=(await o.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Es.set(e,i.id),i.id}async function Ls(t,e,r,o,n,i=wr){let s=await Us(t,e),a=await ye(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:o,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:n,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Ds(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await ye(t,"/api/commands",{method:"POST",body:JSON.stringify({query:n,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${n} on ${e}): ${i.status} ${await i.text()}`)}var Bs="attachments(id,name,url,size,mimeType)",pd="links(direction,linkType(name),issues(idReadable))",Gs=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Bs},${pd}`,dd=`id,text,created,author(login),${Bs}`;function Ms(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 Fs(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,o=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!o.ok)throw new Error(`yt downloadAttachment ${e}: ${o.status}`);return Buffer.from(await o.arrayBuffer())}async function Hs(t,e){let r=e.stageField??wr,o=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");o.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);o.push(`updated: ${c} .. *`)}e.assignee?o.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&o.push("has: Assignee");let n=o.join(" "),i=`/api/issues?query=${encodeURIComponent(n)}&fields=${Gs}&$top=200`,s=await ye(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Ws(c,r))}async function ao(t,e,r=wr){let o=`/api/issues/${encodeURIComponent(e)}?fields=${Gs}`,n=await ye(t,o);if(n.status===404)return null;if(!n.ok)throw new Error(`yt getIssue ${e}: ${n.status} ${await n.text()}`);return Ws(await n.json(),r)}async function Ks(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${dd}&$top=500`,n=await ye(t,o);if(!n.ok)throw new Error(`yt listComments ${e}: ${n.status} ${await n.text()}`);return(await n.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Ms(s.attachments);return c&&(a.attachments=c),a})}function fd(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let o=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(o)for(let n of r.issues??[])n.idReadable&&e.push({type:o,targetKey:n.idReadable})}return e.length>0?e:void 0}function Ws(t,e=wr){let r=t.customFields??[],o=r.find(l=>l.name===e),n=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:o?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),n?.value?.login&&(s.assignee=n.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Ms(t.attachments);a&&(s.attachments=a);let c=fd(t.links);return c&&(s.links=c),s}async function qs(t,e){let r=await md(t,e);return r.length>0?r:gd(t,e)}async function md(t,e){let r=await Us(t,e),o=await ye(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!o.ok)return[];let n=await o.json(),i=[];for(let s of n)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:Ys(s.bundle)});return i}async function gd(t,e){let r=`project: ${e}`,o=await ye(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!o.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${o.status} ${await o.text()}`);let n=await o.json(),i=[];for(let s of n[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:Ys(s.projectCustomField?.bundle)});return i}function Ys(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function xe(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Vs(t,e){let r=U(t),o=[],n=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await et({baseUrl:r.youtrack.url,token:r.youtrack.token});o.push({name:"youtrack",ok:!0}),n.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"youtrack",ok:!1,detail:xe(c)}),n.push({kind:"youtrack",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),n.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await ze(r.github.token);o.push({name:"github",ok:!0}),n.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"github",ok:!1,detail:xe(c)}),n.push({kind:"github",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else n.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Xe(r.bitbucket.email,r.bitbucket.apiToken);o.push({name:"bitbucket",ok:!0}),n.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"bitbucket",ok:!1,detail:xe(c)}),n.push({kind:"bitbucket",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else n.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Qe(r.gitlab.token);o.push({name:"gitlab",ok:!0}),n.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"gitlab",ok:!1,detail:xe(c)}),n.push({kind:"gitlab",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else n.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await to(c,u.owner,u.repoName),o.push({name:`repo:${u.name}`,ok:!0})}catch(f){o.push({name:`repo:${u.name}`,ok:!1,detail:xe(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await to(c,l.owner,l.name),o.push({name:"context-repo",ok:!0})}catch(u){o.push({name:"context-repo",ok:!1,detail:xe(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await to(r.contextWrite.token,c.owner,c.name),n.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){n.push({kind:"contextWrite",present:!0,ok:!1,detail:xe(l),checkedAt:i()})}else n.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else n.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=It(t);if(!a)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),n.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await dn(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";o.push({name:"claude",ok:!1,detail:l}),n.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:o.every(c=>c.ok),checks:o,creds:n,checkedAt:Date.now()}}async function dn(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function br(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@github.com:"),n(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function kr(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@gitlab.com:"),n(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function $r(t,e=process.env){if(!t)return!1;let r=`https://${ft}:${encodeURIComponent(t)}@bitbucket.org/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@bitbucket.org:"),n(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function fn(t,e,r,o){let n=Number.parseInt(o.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<n;s++){let a=o[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(o[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function Js(t,e=process.env){return fn(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>br(t,e),e)}function zs(t,e=process.env){return fn(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>kr(t,e),e)}function Xs(t,e=process.env){return fn(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${ft}:${encodeURIComponent(t)}@bitbucket.org/`,()=>$r(t,e),e)}function Qs(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=io();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},V(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:he(e.sealKey.publicKey)}}async function Zs(t,e,r,o){let n;try{n=JSON.parse(so(o,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=U(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await ze(n.token);return i.github={token:n.token},Ut(i,()=>{process.env.GH_TOKEN=n.token,Js(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Qe(n.token);return i.gitlab={token:n.token},Ut(i,()=>{process.env.GITLAB_TOKEN=n.token,zs(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!n.email||!n.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Xe(n.email,n.apiToken);return i.bitbucket={email:n.email,apiToken:n.apiToken},Ut(i,()=>{process.env.BITBUCKET_EMAIL=n.email,process.env.BITBUCKET_API_TOKEN=n.apiToken,Xs(n.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=n.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await et({baseUrl:s,token:n.token});return i.youtrack={url:s,token:n.token},Ut(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=n.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await dn(n.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:n.token},Ut(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return n.token?(i.contextWrite={token:n.token},Ut(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 Ut(t,e){V(t),e()}import{existsSync as hd,readFileSync as yd,statSync as ea}from"node:fs";var ta=2*1024*1024;function wd(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function ra(t,e){let r=Je(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!hd(r)||!ea(r).isFile())throw new Error(`file not found: ${e}`);let{size:o}=ea(r);if(o>ta)throw new Error(`file too large: ${e} is ${o} bytes (limit ${ta})`);let n=yd(r);return wd(n)?{content:n.toString("utf-8"),encoding:"utf8",sizeBytes:n.length}:{content:n.toString("base64"),encoding:"base64",sizeBytes:n.length}}import{existsSync as bd,readFileSync as kd,writeFileSync as $d}from"node:fs";import{join as vd}from"node:path";import{parseDocument as xd}from"yaml";async function oa(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let n of e){let i=di(n);if(!i.ok)throw new Error(i.error);let s=r.get(n.file)??[];s.push({path:i.field.path,value:i.value}),r.set(n.file,s)}let o=[];for(let[n,i]of r){let s=vd(t,n);if(!bd(s))throw new Error(`${n} not found in context repo (${t})`);let a=xd(kd(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);$d(s,a.toString()),o.push(n)}return{files:o}}import{existsSync as mn,readFileSync as gn,writeFileSync as Sd}from"node:fs";import{join as co}from"node:path";import{parseDocument as hn}from"yaml";async function na(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=co(t,"project.yaml");if(!mn(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=hn(gn(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=co(t,"regimen.yaml");if(!mn(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=hn(gn(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)Sd(co(t,i.path),i.content);return{files:r.map(i=>i.path)}}function lo(t){if(!t)return"Stage";try{let e=co(t,"project.yaml");if(!mn(e))return"Stage";let o=hn(gn(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof o=="string"&&o.trim().length>0?o.trim():"Stage"}catch{return"Stage"}}import{existsSync as ia,readFileSync as Cd,readdirSync as Rd}from"node:fs";function Td(t,e,r){let o=[];for(let n of r){let i=n.issue.key,s=Ed(t,i,n.attachments);o.push({path:`tasks/${i}/task.md`,content:Id(n.issue,e,s)}),o.push({path:`tasks/${i}/comments.jsonl`,content:Pd(jd(t,i,n.comments))});for(let a of n.attachments)o.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return o}async function uo(t,e,r){if(r.length===0)return;let o=Td(t,e,r),n=r.map(i=>i.issue.key);await Ot(t,o,`sync(${n.join(", ")}): task data`)}function Id(t,e,r){let o=new Date(t.updatedAt).toISOString(),n=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${o}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){n.push("## Attachments","");for(let i of r)n.push(`- [${i}](attachments/${encodeURI(i)})`);n.push("")}return n.join(`
432
- `)}function jd(t,e,r){let o=new Map,n=Je(t,`tasks/${e}/comments.jsonl`);if(ia(n))for(let i of Cd(n,"utf-8").split(`
433
- `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&o.set(a.id,a)}catch{}}for(let i of r){let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Fr(i.body);a&&(s.parsedCommand=a),o.set(i.id,s)}return[...o.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Pd(t){return t.map(e=>JSON.stringify(e)).join(`
426
+ `}function Gp(t){return`codepipe/context-migration-v${t}`}function Mp(t){let e=ui(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 \`${je}\` stamp (renamed from \`${lr}\``,"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(`
427
+ `)}async function cs(t,e,r,n){let o=io(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Qr(t,e);if(!i.outdated)return i;let s=Gp(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 Fp(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=Fe(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:Mp(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 Fp(t,e,r,n,o,i,s){let a=io(t),c=Lp(en(Dp(),"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(Ot(l,u).map(h=>[h.path,h.content])),p=0;for(let h of n.missingPaths){if(h===je)continue;let C=f.get(h);if(C==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let k=en(c,h);is(k)||(Up(Bp(k),{recursive:!0}),as(k,C),p++)}as(en(c,je),Dr(n.currentVersion)),p++;let g=en(c,lr);is(g)&&(ss(g,{force:!0}),p++);let d=io(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(()=>{}),ss(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as Hp,readFileSync as Kp,writeFileSync as Wp}from"node:fs";import{homedir as qp}from"node:os";import{join as ls}from"node:path";import{parseDocument as Yp}from"yaml";function Vp(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function Jp(t,e){let r=Yp(t);return r.set("repos",e.map(Vp)),r.toString()}function zp(t,e){let r=[ls(qp(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(ls(e,"project.yaml")),r}function fr(t,e,r){let n=[],o=[];for(let i of zp(t,r))if(Hp(i))try{let s=Kp(i,"utf-8"),a=Jp(s,e);a!==s&&(Wp(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}import{homedir as Xp}from"node:os";import{existsSync as Qp,mkdirSync as Zp}from"node:fs";import{join as so}from"node:path";import{simpleGit as ds}from"simple-git";var us=t=>console.log(t);function ps(t){us=t}function mr(t,e="info"){us(t,e)}function ve(t,e,r){let n=r??so(Xp(),".codepipe","repos");return so(n,t,e)}async function tn(t,e,r={}){let n=ve(t,e.name,r.baseDir),o=r.cloneUrlOverride??ao(e);if(!Qp(so(n,".git"))){Zp(n,{recursive:!0});let a=ds();mr(`[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}
428
+ ${l.trim()}`)}}let i=ds(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
429
+ ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function gr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var fs=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function rn(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&&mr(`[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 gr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await gr(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...fs,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function ms(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await gr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await gr(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 gs(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 ms(t,i,()=>rn(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 gr(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([...fs,"cherry-pick",p])}catch(k){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=k instanceof Error?k.message:String(k);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
430
+ ${y.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 hs(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await ms(t,i,()=>rn(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 ys(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 ao(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{createCipheriv as ed,createDecipheriv as td,createHash as rd,createPrivateKey as nd,createPublicKey as co,diffieHellman as ws,generateKeyPairSync as bs,hkdfSync as ks,randomBytes as od}from"node:crypto";var $s=Buffer.from("devpipe-sealedbox-v1","utf-8");function nn(){let{publicKey:t,privateKey:e}=bs("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ae(t){let e=Buffer.from(t,"base64");return(rd("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function He(t,e){let r=co({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=bs("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=ws({privateKey:o,publicKey:r}),c=Buffer.from(ks("sha256",a,Buffer.concat([i,s]),$s,32)),l=od(12),u=ed("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 on(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=nd({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=co({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=co(n).export({type:"spki",format:"der"}),a=ws({privateKey:n,publicKey:o}),c=Buffer.from(ks("sha256",a,Buffer.concat([i,s]),$s,32)),l=td("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 id(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 vs(t,e,r,n){let o=id(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=qr(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=He(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 Cs}from"node:crypto";import{readFileSync as sd}from"node:fs";import Ze from"node:tls";var Rs=typeof Ze.getCACertificates=="function"&&typeof Ze.setDefaultCACertificates=="function",xs=!1,Ss=new Map,Ts=t=>console.warn(t);function ad(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Is(t=Ts){if(xs)return;xs=!0;let e=L("EXTRA_CA_FILE");if(!(!e||!Rs))try{let r=ad(sd(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Ze.setDefaultCACertificates([...Ze.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 js(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 cd(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
431
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function ld(t,e,r){return new Promise((n,o)=>{let i=Ze.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 Cs(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function lo(t,e,r){return new Promise(n=>{let o=Ze.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 ud(t){try{let e=await fetch(t);return e.ok?new Cs(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ps(t,e=443,r=Ts){let n=`${t}:${e}`,o=Ss.get(n);if(o)return o;let i=pd(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Ss.set(n,i),i}async function pd(t,e,r){if(!Rs)return!1;let n=8e3;if(await lo(t,e,n))return!0;let o=await ld(t,e,n),i=Ze.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=cd(o);if(!c)break;let l=await ud(c);if(!l)break;if(s.push(l.toString()),Ze.setDefaultCACertificates([...i,...s]),await lo(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 lo(t,e,n)}function Oe(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ye(t,e,r){Is();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(js(s)&&await Ps(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var Es=t=>new Promise(e=>setTimeout(e,t));function dd(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function fd(){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 uo(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=fd(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await ye(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&&dd(l.status,u)){await Es(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Es(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function et(t){let e;try{e=await ye(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 Os(t){try{let e=await ye(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var hr="Stage",As=new Map;async function md(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=As.get(o);if(i)return i;let s=await ye(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 As.set(o,l.id),l.id}async function Ns(t,e,r,n=hr){let o=await md(t,e,r,n);await uo(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 Us(t,e,r){return await(await uo(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Ls(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await uo(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}var _s=new Map;async function Ds(t,e){let r=_s.get(e);if(r)return r;let n=await ye(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 _s.set(e,i.id),i.id}async function Bs(t,e,r,n,o,i=hr){let s=await Ds(t,e),a=await ye(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 Gs(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await ye(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 Ms="attachments(id,name,url,size,mimeType)",gd="links(direction,linkType(name),issues(idReadable))",Fs=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ms},${gd}`,hd=`id,text,created,author(login),${Ms}`;function Hs(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 Ks(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 Ws(t,e){let r=e.stageField??hr,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=${Fs}&$top=200`,s=await ye(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Ys(c,r))}async function sn(t,e,r=hr){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Fs}`,o=await ye(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Ys(await o.json(),r)}async function qs(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${hd}&$top=500`,o=await ye(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=Hs(s.attachments);return c&&(a.attachments=c),a})}function yd(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 Ys(t,e=hr){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=Hs(t.attachments);a&&(s.attachments=a);let c=yd(t.links);return c&&(s.links=c),s}async function Vs(t,e){let r=await wd(t,e);return r.length>0?r:bd(t,e)}async function wd(t,e){let r=await Ds(t,e),n=await ye(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),i=[];for(let s of o)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:Js(s.bundle)});return i}async function bd(t,e){let r=`project: ${e}`,n=await ye(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);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[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:Js(s.projectCustomField?.bundle)});return i}function Js(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function xe(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function zs(t,e){let r=U(t),n=[],o=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await et({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:xe(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:xe(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 ze(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:xe(c)}),o.push({kind:"github",present:!0,ok:!1,detail:xe(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 Xe(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:xe(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Qe(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:xe(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:xe(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 Zr(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(f){n.push({name:`repo:${u.name}`,ok:!1,detail:xe(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Zr(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){n.push({name:"context-repo",ok:!1,detail:xe(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Zr(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:xe(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=Tt(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 po(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 po(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 yr(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 wr(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 br(t,e=process.env){if(!t)return!1;let r=`https://${ft}:${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 fo(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 Xs(t,e=process.env){return fo(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>yr(t,e),e)}function Qs(t,e=process.env){return fo(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>wr(t,e),e)}function Zs(t,e=process.env){return fo(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${ft}:${encodeURIComponent(t)}@bitbucket.org/`,()=>br(t,e),e)}function ea(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=nn();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},V(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ae(e.sealKey.publicKey)}}async function ta(t,e,r,n){let o;try{o=JSON.parse(on(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=U(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 ze(o.token);return i.github={token:o.token},Nt(i,()=>{process.env.GH_TOKEN=o.token,Xs(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Qe(o.token);return i.gitlab={token:o.token},Nt(i,()=>{process.env.GITLAB_TOKEN=o.token,Qs(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 Xe(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Nt(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Zs(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 et({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Nt(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 po(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Nt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Nt(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function Nt(t,e){V(t),e()}import{existsSync as kd,readFileSync as $d,statSync as ra}from"node:fs";var na=2*1024*1024;function vd(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function oa(t,e){let r=Je(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!kd(r)||!ra(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=ra(r);if(n>na)throw new Error(`file too large: ${e} is ${n} bytes (limit ${na})`);let o=$d(r);return vd(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{existsSync as xd,readFileSync as Sd,writeFileSync as Cd}from"node:fs";import{join as Rd}from"node:path";import{parseDocument as Td}from"yaml";async function ia(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=mi(o);if(!i.ok)throw new Error(i.error);let s=r.get(o.file)??[];s.push({path:i.field.path,value:i.value}),r.set(o.file,s)}let n=[];for(let[o,i]of r){let s=Rd(t,o);if(!xd(s))throw new Error(`${o} not found in context repo (${t})`);let a=Td(Sd(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);Cd(s,a.toString()),n.push(o)}return{files:n}}import{existsSync as mo,readFileSync as go,writeFileSync as Id}from"node:fs";import{join as an}from"node:path";import{parseDocument as ho}from"yaml";async function sa(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=an(t,"project.yaml");if(!mo(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=ho(go(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=an(t,"regimen.yaml");if(!mo(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=ho(go(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)Id(an(t,i.path),i.content);return{files:r.map(i=>i.path)}}function cn(t){if(!t)return"Stage";try{let e=an(t,"project.yaml");if(!mo(e))return"Stage";let n=ho(go(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}import{existsSync as aa,readFileSync as jd,readdirSync as Pd}from"node:fs";function Ed(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Nd(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Ad(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Od(_d(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 ln(t,e,r){if(r.length===0)return;let n=Ed(t,e,r),o=r.map(i=>i.issue.key);await _t(t,n,`sync(${o.join(", ")}): task data`)}function Ad(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(`
432
+ `)}function _d(t,e,r){let n=new Map,o=Je(t,`tasks/${e}/comments.jsonl`);if(aa(o))for(let i of jd(o,"utf-8").split(`
433
+ `)){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=Gr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Od(t){return t.map(e=>JSON.stringify(e)).join(`
434
434
  `)+(t.length>0?`
435
- `:"")}function Ed(t,e,r){let o=[],n=Je(t,`tasks/${e}/attachments`);if(ia(n))for(let i of Rd(n))o.push(i);for(let i of r)o.includes(i.name)||o.push(i.name);return o}var po=new Map;async function yn(t,e){let o=(po.get(t)??Promise.resolve()).catch(()=>{}).then(e);po.set(t,o);try{return await o}finally{po.get(t)===o&&po.delete(t)}}async function sa(t){let{action:e,repo:r}=t,o="repoName"in e?e.repoName:"-",n="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;hr(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return yn(`${i}/${r.name}`,async()=>{let s=await oo(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c}=await fs(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return te({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return yn(`${i}/${r.name}`,async()=>{let s=await oo(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await ms(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return te({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return q("no repo spec");let i=Fe(r),s=await i.createPullRequest(r,e);return te({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return q("no repo spec");let i=Fe(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return te({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return q("no repo spec");let i=Fe(r);return await i.closePR(r,e.prNumber,e.comment),te({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return yn(`${i}/${r.name}`,async()=>{let s=await oo(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{mergedSha:c}=await gs(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return te({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return te({stub:!0});case"tracker_status":{let i=Oe();return i?t.trackerIssueId?(await _s(i,t.trackerIssueId,e.newStatus,lo(t.contextDir)),te({issueId:t.trackerIssueId,newStatus:e.newStatus})):q("no tracker_issue_id provided"):q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return q("no tracker_issue_id provided");let s=await Os(i,t.trackerIssueId,e.body);return te({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return q("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Ls(i,e.projectKey,e.title,e.body,e.targetStatus,lo(t.contextDir));return te({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Ds(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return q(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return te({applied:s})}case"set_project_setting":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await oa(t.contextDir,e.edits);return te({files:i.files})}case"tracker_edit":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.contextDir)return q("no context repo clone on this CLI");let s=lo(t.contextDir);await Ns(i,e.issueKey,{...e.title!==void 0?{summary:e.title}:{},...e.body!==void 0?{description:e.body}:{}});let a=await ao(i,e.issueKey,s);return a&&await uo(t.contextDir,e.projectId,[{issue:a,comments:[],attachments:[]}]),te({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await na(t.contextDir,e);return te({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),te({reported:!0})):q("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return q("no context repo clone on this CLI");let i=await t.refreshContextStatus();return te({outdated:i.outdated,templateVersion:i.templateVersion})}case"read_context_file":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=ra(t.contextDir,e.path);return te({path:e.path,...i})}default:return q(`unsupported action type: ${e.type}`)}}catch(i){return q(i instanceof Error?i.message:String(i))}}function te(t){return{status:"done",result:t}}function q(t){return{status:"failed",error:t}}import{existsSync as xa,readFileSync as Sa}from"node:fs";import{join as Ca}from"node:path";import{homedir as Ad}from"node:os";import{existsSync as _d,mkdirSync as Od,readFileSync as Nd,writeFileSync as Ud}from"node:fs";import{dirname as Ld,join as Dd}from"node:path";function wn(){return L("FARM_PINS")??Dd(Ad(),".codepipe","farm-pins.json")}function aa(){let t=wn();if(!_d(t))return{};try{return JSON.parse(Nd(t,"utf-8"))}catch{return{}}}function Bd(t){let e=wn();Od(Ld(e),{recursive:!0}),Ud(e,JSON.stringify(t,null,2)+`
436
- `,{mode:384})}function Gd(t){return aa()[t]}function yt(t,e){let r=aa();r[t]=e,Bd(r)}function Lt(t,e){let r=he(e),o=Gd(t);if(o&&o!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${o}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${wn()}.`);return r}import Md from"ws";function fo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Md(r)}var A=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function tt(t,e,r){return Se(t,e,"/projects",r)}async function ca(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function mo(t,e,r,o){return Se(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function la(t,e,r,o){return Se(t,e,`/farms/${encodeURIComponent(r)}/gh-runners`,o)}async function ua(t,e,r,o){return Se(t,e,`/farms/${encodeURIComponent(r)}/gh-runners/teardown`,o)}async function pa(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new A(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function go(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function da(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var vr=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function fa(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let o;try{o=(await r.json()).error}catch{}if(o==="registration_required")throw new vr(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function ma(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new A(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function ga(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function ha(t,e,r,o){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(o)}`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new A(n.status,null,`GET cli-task HTTP ${n.status}`);return await n.json()}async function ya(t,e,r,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function wa(t,e,r,o,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function ba(t,e,r,o,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function ka(t,e,r,o,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function ho(t,e,r,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function bn(t,e,r,o){await Se(t,e,`/projects/${encodeURIComponent(r)}/init-status`,o)}async function $a(t,e,r,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/repos`,o)}async function va(t,e,r,o){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(o)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}async function M(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function Se(t,e,r,o){let n=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}async function Ra(t,e,r,o){let n=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return n(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=he(e.farmPublicKey);if(i!==e.fingerprint)return n("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Lt(e.farmId,e.farmPublicKey);let s=U(t.projectId);if(!s)return n("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await M(t.hubUrl,t.cliToken,t.projectId),c;if(r){let p=Ca(r,"project.yaml"),g=Ca(r,"regimen.yaml");xa(p)&&xa(g)?c={projectYaml:Sa(p,"utf-8"),regimenYaml:Sa(g,"utf-8")}:o.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=He(e.farmPublicKey,JSON.stringify(l));yt(e.farmId,i),o.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await mo(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:n(f.error??"farm provisioning failed")}catch(i){return n(i instanceof Error?i.message:String(i))}}var Ia=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Ta(t,e,r,o){let n=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${o}`,{method:"POST",headers:Ia(t)});if(!n.ok)throw new Error(`github ${o} for ${e}/${r}: HTTP ${n.status}`);let i=await n.json();if(!i.token)throw new Error(`github ${o} for ${e}/${r}: no token in response`);return i.token}var Fd={async repoHasAdmin(t,e,r){let o=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Ia(t)});if(!o.ok)throw new Error(`github GET /repos/${e}/${r}: HTTP ${o.status}`);return(await o.json()).permissions?.admin===!0},mintRegistrationToken:(t,e,r)=>Ta(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Ta(t,e,r,"remove-token")},ja={api:Fd,fetchProject:M,provisionOnFarm:la,teardownOnFarm:ua};async function Pa(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(he(e.farmPublicKey)!==e.fingerprint)throw new Error("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Lt(e.farmId,e.farmPublicKey);let i=U(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).filter(c=>c.host==="github");if(a.length===0)throw new Error("the project has no GitHub repositories \u2014 nothing to connect a runner to");return{githubToken:i,repos:a}}async function Ea(t,e,r,o=ja){let n=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await Pa(t,e,o),a=[];for(let p of s)await o.api.repoHasAdmin(i,p.owner,p.repoName)||a.push(`${p.owner}/${p.repoName}`);if(a.length>0)return n(`the GitHub token lacks admin access on ${a.join(", ")} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on every repository`);let c=[];for(let p of s)c.push({owner:p.owner,repo:p.repoName,regToken:await o.api.mintRegistrationToken(i,p.owner,p.repoName)});let l={projectId:t.projectId,runners:c},u=He(e.farmPublicKey,JSON.stringify(l));yt(e.farmId,e.fingerprint),r.info(`[ghr] ${c.length} registration token(s) sealed for farm ${e.farmName} \u2014 handing off`);let f=await o.provisionOnFarm(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:f.ok,...f.runners?{runners:f.runners}:{},...f.error?{error:f.error}:{}}}catch(i){return n(i instanceof Error?i.message:String(i))}}async function Aa(t,e,r,o=ja){let n=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await Pa(t,e,o),a=[];for(let f of s)try{a.push({owner:f.owner,repo:f.repoName,removeToken:await o.api.mintRemoveToken(i,f.owner,f.repoName)})}catch(p){r.warn(`[ghr] remove-token for ${f.owner}/${f.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the farm will force-remove`),a.push({owner:f.owner,repo:f.repoName})}let c={projectId:t.projectId,runners:a},l=He(e.farmPublicKey,JSON.stringify(c));yt(e.farmId,e.fingerprint),r.info(`[ghr] removal bundle sealed for farm ${e.farmName} \u2014 handing off`);let u=await o.teardownOnFarm(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:l});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return n(i instanceof Error?i.message:String(i))}}var yo=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let o=[];for(let s of r.prs){let a=Fe(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);o.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof ht){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let n=o.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===n)return;for(let s=0;s<o.length;s++){let a=o[s];if(a.ci!=="failed")continue;let c=Fe(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:o}),this.lastSig.set(e,n);let i=Hd(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function Hd(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var wo=class t{constructor(e,r,o,n={contextDir:null}){this.intervalMs=e;this.send=r;this.log=o;this.options=n}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let e=Oe();if(!e){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn("[yt-sync] YOUTRACK_URL/YOUTRACK_TOKEN missing \u2014 poller idle. set them in cli/.env to enable YT read-sync."));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,e)}finally{this.running=!1}}async pollOnce(e,r){let o=Date.now(),n;try{let $=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await Hs(r,{projectKey:e.projectKey,columns:$,...e.stageField?{stageField:e.stageField}:{},...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch($){this.log.warn(`[yt-sync] listIssues failed: ${$ instanceof Error?$.message:String($)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let $ of n){if(s.add($.id),a.has($.status))continue;let v=await Oa(r,$.id,e.sinceMs,this.log);v&&i.set($.id,v)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let v=await Oa(r,$,e.sinceMs,this.log);if(v&&v.length>0&&i.set($,v),e.requireAssignee||v&&v.length>0){let N=await qd(r,$,e.stageField,this.log);if(N)c.push(N);else if(v&&v.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=n.filter($=>!a.has($.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($=>({issue:$,comments:i.get($.id)??[],attachments:u.get($.id)??[]}));try{await uo(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let $ of f)this.shippedAttachments.add($)}catch($){let v=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${v}`);return}let g=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[$,v]of i){let N=v.filter(x=>!g(x.id));if(N.length===0)continue;d.push({issueId:$,comments:N.map(Kd)});let P=N.flatMap(x=>{let m=Fr(x.body);return m?[{commentId:x.id,author:x.author,name:m.name,args:m.args,createdAt:x.createdAt}]:[]});P.length>0&&h.push({issueId:$,commands:P})}let C={type:"youtrack_observation",projectId:e.projectId,issues:n.map(_a),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(_a)}:{},observedAtMs:o};this.send(C);let k=d.reduce(($,v)=>$+v.comments.length,0),y=h.reduce(($,v)=>$+v.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${n.length} comments=${k} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,o){let n=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let f=`${s.id}:${u.id}`;if(this.shippedAttachments.has(f))continue;let p;try{p=await Fs(o,u.url)}catch(d){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${d instanceof Error?d.message:String(d)}`);continue}let g=Wd(u.name);l.has(g)&&(g=`${u.id}-${g}`),l.add(g),c.push({name:g,contentBase64:p.toString("base64")}),i.push(f)}c.length>0&&n.set(s.id,c)}return{attachmentsByIssue:n,attachmentKeys:i}}};function _a(t){let{description:e,...r}=t;return r}function Kd(t){let{body:e,...r}=t;return r}function Wd(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 qd(t,e,r,o){try{return await ao(t,e,r)}catch(n){return o.warn(`[yt-sync] getIssue ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}async function Oa(t,e,r,o){try{return await Ks(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var kn="npm i -g @code-partner/codepipe@latest";function bo(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${fe} (protocol ${Ie})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&Hi(n.contextDir,r);let i=Na("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Na("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=fo(t.hubUrl,t.cliToken),h=null,C=new yo(i,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r),k=new wo(s,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r,{contextDir:n?.contextDir??null,isSelfComment:m=>f.has(m)}),y=null,$=async()=>{try{let m;try{let S=await M(t.hubUrl,t.cliToken,t.projectId);m={repos:S.repos,contextRepo:S.contextRepo}}catch(S){r.warn(`[readiness] could not fetch project summary for push checks: ${S instanceof Error?S.message:String(S)}`)}let T=await Vs(t.projectId,m);if(d.readyState!==d.OPEN)return;let b={type:"cli_readiness",projectId:t.projectId,ready:T.ready,checks:T.checks,creds:T.creds,checkedAt:T.checkedAt};if(d.send(JSON.stringify(b)),T.ready)r.info("[readiness] ready");else{let S=T.checks.filter(j=>!j.ok).map(j=>`${j.name}(${j.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${S.join(", ")}`)}}catch(m){r.warn(`[readiness] check failed: ${m instanceof Error?m.message:String(m)}`)}},v=()=>{$(),y=setInterval(()=>void $(),a),typeof y.unref=="function"&&y.unref()},N=()=>{y&&(clearInterval(y),y=null)},P=n?.contextDir?new Qr(n.contextDir,t.projectId,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r):null,x=async()=>{let m=n?.contextDir;if(!m)throw new Error("no context repo clone on this CLI");let T;try{T=(await M(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let b=await ss(m,t.projectId,T,r);return d.readyState===d.OPEN&&d.send(JSON.stringify(b)),b};return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let m=Bi(t.projectId),T=L("ORIGIN")==="farm"?"farm":"local",b=L("FARM_ID"),S=t.accountEmail??m.email,j;try{let I=Qs(t.projectId);I&&(j=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let w={type:"register",projectId:t.projectId,platformVersion:fe,protocolVersion:Ie,accountId:m.accountId,accountLabel:m.label,origin:T,inFlightActionIds:[...u],...S?{accountEmail:S}:{},...T==="farm"&&b?{farmId:b}:{},...j?{sealPublicKey:j}:{}};d.send(JSON.stringify(w))}),d.on("message",async m=>{let T=m.toString("utf-8");if(T==="pong"||T==="ping")return;let b;try{b=JSON.parse(T)}catch{return}if(!b||typeof b!="object")return;let S=b.type;if(S==="registered"){let w=b;if(w.ok){if(r.info(`[ws] registered for project ${w.projectId}`),o({kind:"registered",projectId:w.projectId??t.projectId}),C.start(),P?.start(),v(),$n(t,n,r),n?.contextDir)try{let I=eo(n.contextDir,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),l||(l=!0,x().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}}else r.warn(`[ws] register rejected: ${w.reason??"unknown"}`),o({kind:"register_rejected",reason:w.reason??"unknown"}),c=!0,d.close();return}if(S==="hello"){let w=b;h=Br(w.protocolVersion);let I=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${I}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${fe}, protocol ${Ie}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${kn}`),o({kind:"incompatible",hubVersion:typeof w.platformVersion=="string"?w.platformVersion:null,hubProtocol:typeof w.protocolVersion=="number"?w.protocolVersion:null,updateCommand:kn}));return}if(S==="tracking_targets"){C.setTargets(b.targets);return}if(S==="youtrack_sync_request"){k.setRequest(b);return}if(S==="youtrack_force_sync"){k.forceSync();return}if(S==="sync_local"){await Xd(b,n,d,r);return}if(S==="provision_repo"){let w=b;r.info(`[repo] provision_repo: ${w.repo.name} (${w.repo.host}:${w.repo.owner}/${w.repo.repoName})`),await Jd(t,n,w.repo,r),await $n(t,n,r);return}if(S==="remove_repo"){let w=b;r.info(`[repo] remove_repo: ${w.repoName}${w.purge?" (purge)":""}`),await $n(t,n,r),w.purge&&zd(t,n,w.repoName,r);return}if(S==="context_write"){await Qd(b,n,d,r);return}if(S==="adr_promote"){await Zd(b,n,d,r);return}if(S==="cred_update"){let w=b,I=U(t.projectId),B=I?.sealKey?await Zs(t.projectId,w.kind,w.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},K={type:"cred_update_result",updateId:w.updateId,projectId:t.projectId,ok:B.ok,...B.detail?{detail:B.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(K)),B.ok?(r.info(`[cred] ${w.kind} replaced${B.detail?` \u2014 ${B.detail}`:""}`),$()):r.warn(`[cred] ${w.kind} replacement rejected: ${B.detail??"unknown"}`);return}if(S==="move_to_farm"){let w=b;r.info(`[farm-move] request to move ${t.projectId} onto farm ${w.farmName} (${w.farmId})`);let I=await Ra(t,w,n?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if(S==="gh_runner_setup"){let w=b;r.info(`[ghr] runner setup for ${t.projectId} on farm ${w.farmName} (${w.farmId})`);let I=await Ea(t,w,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${w.farmName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if(S==="gh_runner_teardown"){let w=b;r.info(`[ghr] runner teardown for ${t.projectId} on farm ${w.farmName} (${w.farmId})`);let I=await Aa(t,w,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${w.farmName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if(S==="tracker_fields_request"){let w=b,I={type:"tracker_fields_result",requestId:w.requestId,projectId:t.projectId,ok:!1},B=Oe();if(!B)I.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{I.fields=await qs(B,w.projectKey),I.ok=!0}catch(K){I.error=K instanceof Error?K.message:String(K)}d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(S==="sandbox_keys"){let w=U(t.projectId);if(!w){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=It(t.projectId),B=ks(b,w,I,r);for(let K of B)d.readyState===d.OPEN&&d.send(JSON.stringify(K));return}if(S!=="dispatch_action")return;let j=b;if(h===!1){let w=`refused: HUB protocol incompatible with CLI v${fe} (protocol ${Ie})`;d.send(JSON.stringify({type:"action_result",actionId:j.actionId,status:"failed",error:w})),r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 REFUSED: ${w}`),r.warn(`[exec] update the CLI to clear this: ${kn}`),o({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:!1,error:w});return}u.add(j.actionId);try{let w=await sa({action:j.action,repo:j.repo,trackerIssueId:j.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:P?()=>P.reportNow():void 0,refreshContextStatus:n?.contextDir?x:void 0}).catch(K=>({status:"failed",error:K instanceof Error?K.message:String(K)}));j.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:j.actionId,...w}));let I=w.status!=="failed",B=!I&&"error"in w?w.error:void 0;I?r.info(`[exec] ${j.actionId} (${j.action.type}) \u2192 done`):r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 FAILED: ${B??"?"}`),o({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:I,...B?{error:B}:{}})}finally{u.delete(j.actionId)}}),d.on("close",(m,T)=>{let b=T?.toString("utf-8")??"";if(r.info(`[ws] closed code=${m}${b?` reason=${b}`:""}`),C.stop(),k.stop(),P?.stop(),N(),b==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),o({kind:"replaced"});return}o({kind:"disconnected",code:m}),!c&&setTimeout(()=>{p=g()},2e3)}),d.on("error",m=>r.warn(`[ws] error: ${m.message}`)),d}return{stop(){c=!0,p.close()}}}async function $n(t,e,r){try{let o=await M(t.hubUrl,t.cliToken,t.projectId),{updated:n,errors:i}=gr(t.projectId,o.repos,e?.contextDir);for(let s of n)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(o){r.warn(`[repo] repo-set reconcile skipped: ${o instanceof Error?o.message:String(o)}`)}}async function Jd(t,e,r,o){let n=r.mountAs??r.name;if(n==="."){o.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?xr(e.root,n):ve(t.projectId,r.name);if(Ua(xr(i,".git"))){o.info(`[repo] ${r.name} already present at ${i}`);return}try{await Vd().clone(cn(r),i),o.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){o.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function zd(t,e,r,o){let n=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?xr(e.root,n):ve(t.projectId,r);if(e&&i===e.root){o.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Ua(xr(i,".git"))){o.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Yd(i,{recursive:!0,force:!0}),o.info(`[repo] purged local clone ${i}`)}catch(s){o.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function Xd(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(l=>l.name===n.repoName),s=xr(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await Gi(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?o.info(`[sync] ${n.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${n.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${n.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:n.repoName,reason:c.reason??"sync skipped"})))}}async function Qd(t,e,r,o){let n=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{await Ot(e.contextDir,t.files,t.message),o.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[ctx] context_write ${t.id} failed: ${s}`),n("failed",s)}}async function Zd(t,e,r,o){let n=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{let i=await Xi(e.contextDir,t.taskKey,t.slugs);if(o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let s=`draft file(s) missing in clone: ${i.missing.map(a=>`tasks/${t.taskKey}/adr/DRAFT-${a}.md`).join(", ")}`;o.warn(`[adr] adr_promote ${t.id}: ${s}`),n("failed",s);return}n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[adr] adr_promote ${t.id} failed: ${s}`),n("failed",s)}}function Na(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Ha,mkdirSync as Ka}from"node:fs";import{dirname as Wa}from"node:path";import{simpleGit as Dt}from"simple-git";import{execFileSync as ef}from"node:child_process";import{mkdtempSync as tf,mkdirSync as rf,readFileSync as La,rmSync as of,writeFileSync as nf}from"node:fs";import{tmpdir as sf}from"node:os";import{dirname as af,join as Da}from"node:path";function Ba(t="codepipe-context"){let e=tf(Da(sf(),"codepipe-ssh-")),r=Da(e,"id_ed25519");try{return ef("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:La(r,"utf-8"),publicKey:La(`${r}.pub`,"utf-8").trim()}}finally{of(e,{recursive:!0,force:!0})}}async function Ga(t,e,r,o="codepipe-context"){let n=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:o,key:r,read_only:!1})});if(n.ok)return;let i=await n.text();if(!(n.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${n.status} ${i}`)}function Ma(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 Fa(t,e){rf(af(t),{recursive:!0});let r=e.endsWith(`
435
+ `:"")}function Nd(t,e,r){let n=[],o=Je(t,`tasks/${e}/attachments`);if(aa(o))for(let i of Pd(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var un=new Map;async function yo(t,e){let n=(un.get(t)??Promise.resolve()).catch(()=>{}).then(e);un.set(t,n);try{return await n}finally{un.get(t)===n&&un.delete(t)}}async function ca(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;mr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return yo(`${i}/${r.name}`,async()=>{let s=await tn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c}=await gs(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return te({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return yo(`${i}/${r.name}`,async()=>{let s=await tn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await hs(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return te({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return q("no repo spec");let i=Fe(r),s=await i.createPullRequest(r,e);return te({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return q("no repo spec");let i=Fe(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return te({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return q("no repo spec");let i=Fe(r);return await i.closePR(r,e.prNumber,e.comment),te({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return yo(`${i}/${r.name}`,async()=>{let s=await tn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{mergedSha:c}=await ys(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return te({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return te({stub:!0});case"tracker_status":{let i=Oe();return i?t.trackerIssueId?(await Ns(i,t.trackerIssueId,e.newStatus,cn(t.contextDir)),te({issueId:t.trackerIssueId,newStatus:e.newStatus})):q("no tracker_issue_id provided"):q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return q("no tracker_issue_id provided");let s=await Us(i,t.trackerIssueId,e.body);return te({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return q("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Bs(i,e.projectKey,e.title,e.body,e.targetStatus,cn(t.contextDir));return te({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Gs(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return q(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return te({applied:s})}case"set_project_setting":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await ia(t.contextDir,e.edits);return te({files:i.files})}case"tracker_edit":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.contextDir)return q("no context repo clone on this CLI");let s=cn(t.contextDir);await Ls(i,e.issueKey,{...e.title!==void 0?{summary:e.title}:{},...e.body!==void 0?{description:e.body}:{}});let a=await sn(i,e.issueKey,s);return a&&await ln(t.contextDir,e.projectId,[{issue:a,comments:[],attachments:[]}]),te({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await sa(t.contextDir,e);return te({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),te({reported:!0})):q("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return q("no context repo clone on this CLI");let i=await t.refreshContextStatus();return te({outdated:i.outdated,templateVersion:i.templateVersion})}case"read_context_file":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=oa(t.contextDir,e.path);return te({path:e.path,...i})}default:return q(`unsupported action type: ${e.type}`)}}catch(i){return q(i instanceof Error?i.message:String(i))}}function te(t){return{status:"done",result:t}}function q(t){return{status:"failed",error:t}}import{existsSync as Ca,readFileSync as Ra}from"node:fs";import{join as Ta}from"node:path";import{homedir as Ud}from"node:os";import{existsSync as Ld,mkdirSync as Dd,readFileSync as Bd,writeFileSync as Gd}from"node:fs";import{dirname as Md,join as Fd}from"node:path";function wo(){return L("FARM_PINS")??Fd(Ud(),".codepipe","farm-pins.json")}function la(){let t=wo();if(!Ld(t))return{};try{return JSON.parse(Bd(t,"utf-8"))}catch{return{}}}function Hd(t){let e=wo();Dd(Md(e),{recursive:!0}),Gd(e,JSON.stringify(t,null,2)+`
436
+ `,{mode:384})}function Kd(t){return la()[t]}function pn(t,e){let r=la();r[t]=e,Hd(r)}function dn(t,e){let r=ae(e),n=Kd(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 ${wo()}.`);return r}import Wd from"ws";function fn(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Wd(r)}var A=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};async function tt(t,e,r){return Se(t,e,"/projects",r)}async function ua(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function mn(t,e,r,n){return Se(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function pa(t,e,r,n){return Se(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function da(t,e,r,n){return Se(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function fa(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new A(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function gn(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function ma(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var kr=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function ga(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 kr(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function ha(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new A(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function ya(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new A(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function wa(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 A(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function ba(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function ka(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function $a(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function va(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function hn(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function bo(t,e,r,n){await Se(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function xa(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Sa(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),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 A(o.status,s,a)}return s}async function M(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new A(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function Se(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 A(o.status,s,a)}return s}async function Ia(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=ae(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");dn(e.farmId,e.farmPublicKey);let s=U(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await M(t.hubUrl,t.cliToken,t.projectId),c;if(r){let p=Ta(r,"project.yaml"),g=Ta(r,"regimen.yaml");Ca(p)&&Ca(g)?c={projectYaml:Ra(p,"utf-8"),regimenYaml:Ra(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=He(e.farmPublicKey,JSON.stringify(l));pn(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await mn(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))}}import{homedir as qd}from"node:os";import{existsSync as Yd,mkdirSync as Vd,readFileSync as Jd,writeFileSync as zd}from"node:fs";import{dirname as Xd,join as Qd}from"node:path";function ko(){return L("RUNNER_PINS")??Qd(qd(),".codepipe","runner-pins.json")}function ja(){let t=ko();if(!Yd(t))return{};try{return JSON.parse(Jd(t,"utf-8"))}catch{return{}}}function Zd(t){let e=ko();Vd(Xd(e),{recursive:!0}),zd(e,JSON.stringify(t,null,2)+`
437
+ `,{mode:384})}function ef(t){return ja()[t]}function $o(t,e){let r=ja();r[t]=e,Zd(r)}function Pa(t,e){let r=ae(e),n=ef(t);if(n&&n!==r)throw new Error(`runner host ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the runner host was re-registered intentionally, remove its entry from ${ko()}.`);return r}var Aa=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Ea(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Aa(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var tf={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Aa(t)});if(!n.ok)throw new Error(`github GET /repos/${e}/${r}: HTTP ${n.status}`);return(await n.json()).permissions?.admin===!0},mintRegistrationToken:(t,e,r)=>Ea(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Ea(t,e,r,"remove-token")},_a={api:tf,fetchProject:M,provisionOnRunner:pa,teardownOnRunner:da};async function Oa(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(ae(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Pa(e.runnerId,e.runnerPublicKey);let i=U(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).filter(c=>c.host==="github");if(a.length===0)throw new Error("the project has no GitHub repositories \u2014 nothing to connect a runner to");return{githubToken:i,repos:a}}async function Na(t,e,r,n=_a){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await Oa(t,e,n),a=[];for(let p of s)await n.api.repoHasAdmin(i,p.owner,p.repoName)||a.push(`${p.owner}/${p.repoName}`);if(a.length>0)return o(`the GitHub token lacks admin access on ${a.join(", ")} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on every repository`);let c=[];for(let p of s)c.push({owner:p.owner,repo:p.repoName,regToken:await n.api.mintRegistrationToken(i,p.owner,p.repoName)});let l={projectId:t.projectId,runners:c},u=He(e.runnerPublicKey,JSON.stringify(l));$o(e.runnerId,e.fingerprint),r.info(`[ghr] ${c.length} registration token(s) sealed for runner host ${e.runnerName} \u2014 handing off`);let f=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:u});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:f.ok,...f.runners?{runners:f.runners}:{},...f.error?{error:f.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function Ua(t,e,r,n=_a){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await Oa(t,e,n),a=[];for(let f of s)try{a.push({owner:f.owner,repo:f.repoName,removeToken:await n.api.mintRemoveToken(i,f.owner,f.repoName)})}catch(p){r.warn(`[ghr] remove-token for ${f.owner}/${f.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`),a.push({owner:f.owner,repo:f.repoName})}let c={projectId:t.projectId,runners:a},l=He(e.runnerPublicKey,JSON.stringify(c));$o(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var yn=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=Fe(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 ht){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=Fe(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=rf(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function rf(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var wn=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 forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let e=Oe();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 $=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await Ws(r,{projectKey:e.projectKey,columns:$,...e.stageField?{stageField:e.stageField}:{},...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch($){this.log.warn(`[yt-sync] listIssues failed: ${$ instanceof Error?$.message:String($)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let $ of o){if(s.add($.id),a.has($.status))continue;let v=await Da(r,$.id,e.sinceMs,this.log);v&&i.set($.id,v)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let v=await Da(r,$,e.sinceMs,this.log);if(v&&v.length>0&&i.set($,v),e.requireAssignee||v&&v.length>0){let N=await sf(r,$,e.stageField,this.log);if(N)c.push(N);else if(v&&v.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter($=>!a.has($.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($=>({issue:$,comments:i.get($.id)??[],attachments:u.get($.id)??[]}));try{await ln(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let $ of f)this.shippedAttachments.add($)}catch($){let v=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${v}`);return}let g=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[$,v]of i){let N=v.filter(x=>!g(x.id));if(N.length===0)continue;d.push({issueId:$,comments:N.map(nf)});let P=N.flatMap(x=>{let m=Gr(x.body);return m?[{commentId:x.id,author:x.author,name:m.name,args:m.args,createdAt:x.createdAt}]:[]});P.length>0&&h.push({issueId:$,commands:P})}let C={type:"youtrack_observation",projectId:e.projectId,issues:o.map(La),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(La)}:{},observedAtMs:n};this.send(C);let k=d.reduce(($,v)=>$+v.comments.length,0),y=h.reduce(($,v)=>$+v.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${k} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,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 Ks(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=of(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 La(t){let{description:e,...r}=t;return r}function nf(t){let{body:e,...r}=t;return r}function of(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 sf(t,e,r,n){try{return await sn(t,e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Da(t,e,r,n){try{return await qs(t,e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var vo="npm i -g @code-partner/codepipe@latest";function bn(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${me} (protocol ${Ie})`);let n=d=>e.onEvent?.(d),o=e.workspace;o?.contextDir&&Wi(o.contextDir,r);let i=Ba("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Ba("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=fn(t.hubUrl,t.cliToken),h=null,C=new yn(i,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r),k=new wn(s,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r,{contextDir:o?.contextDir??null,isSelfComment:m=>f.has(m)}),y=null,$=async()=>{try{let m;try{let S=await M(t.hubUrl,t.cliToken,t.projectId);m={repos:S.repos,contextRepo:S.contextRepo}}catch(S){r.warn(`[readiness] could not fetch project summary for push checks: ${S instanceof Error?S.message:String(S)}`)}let T=await zs(t.projectId,m);if(d.readyState!==d.OPEN)return;let b={type:"cli_readiness",projectId:t.projectId,ready:T.ready,checks:T.checks,creds:T.creds,checkedAt:T.checkedAt};if(d.send(JSON.stringify(b)),T.ready)r.info("[readiness] ready");else{let S=T.checks.filter(j=>!j.ok).map(j=>`${j.name}(${j.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${S.join(", ")}`)}}catch(m){r.warn(`[readiness] check failed: ${m instanceof Error?m.message:String(m)}`)}},v=()=>{$(),y=setInterval(()=>void $(),a),typeof y.unref=="function"&&y.unref()},N=()=>{y&&(clearInterval(y),y=null)},P=o?.contextDir?new zr(o.contextDir,t.projectId,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r):null,x=async()=>{let m=o?.contextDir;if(!m)throw new Error("no context repo clone on this CLI");let T;try{T=(await M(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let b=await cs(m,t.projectId,T,r);return d.readyState===d.OPEN&&d.send(JSON.stringify(b)),b};return d.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let m=Mi(t.projectId),T=L("ORIGIN")==="farm"?"farm":"local",b=L("FARM_ID"),S=t.accountEmail??m.email,j;try{let I=ea(t.projectId);I&&(j=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let w={type:"register",projectId:t.projectId,platformVersion:me,protocolVersion:Ie,accountId:m.accountId,accountLabel:m.label,origin:T,inFlightActionIds:[...u],...S?{accountEmail:S}:{},...T==="farm"&&b?{farmId:b}:{},...j?{sealPublicKey:j}:{}};d.send(JSON.stringify(w))}),d.on("message",async m=>{let T=m.toString("utf-8");if(T==="pong"||T==="ping")return;let b;try{b=JSON.parse(T)}catch{return}if(!b||typeof b!="object")return;let S=b.type;if(S==="registered"){let w=b;if(w.ok){if(r.info(`[ws] registered for project ${w.projectId}`),n({kind:"registered",projectId:w.projectId??t.projectId}),C.start(),P?.start(),v(),xo(t,o,r),o?.contextDir)try{let I=Qr(o.contextDir,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),l||(l=!0,x().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}}else r.warn(`[ws] register rejected: ${w.reason??"unknown"}`),n({kind:"register_rejected",reason:w.reason??"unknown"}),c=!0,d.close();return}if(S==="hello"){let w=b;h=Lr(w.protocolVersion);let I=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${I}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${me}, protocol ${Ie}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${vo}`),n({kind:"incompatible",hubVersion:typeof w.platformVersion=="string"?w.platformVersion:null,hubProtocol:typeof w.protocolVersion=="number"?w.protocolVersion:null,updateCommand:vo}));return}if(S==="tracking_targets"){C.setTargets(b.targets);return}if(S==="youtrack_sync_request"){k.setRequest(b);return}if(S==="youtrack_force_sync"){k.forceSync();return}if(S==="sync_local"){await pf(b,o,d,r);return}if(S==="provision_repo"){let w=b;r.info(`[repo] provision_repo: ${w.repo.name} (${w.repo.host}:${w.repo.owner}/${w.repo.repoName})`),await lf(t,o,w.repo,r),await xo(t,o,r);return}if(S==="remove_repo"){let w=b;r.info(`[repo] remove_repo: ${w.repoName}${w.purge?" (purge)":""}`),await xo(t,o,r),w.purge&&uf(t,o,w.repoName,r);return}if(S==="context_write"){await df(b,o,d,r);return}if(S==="adr_promote"){await ff(b,o,d,r);return}if(S==="cred_update"){let w=b,I=U(t.projectId),B=I?.sealKey?await ta(t.projectId,w.kind,w.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},K={type:"cred_update_result",updateId:w.updateId,projectId:t.projectId,ok:B.ok,...B.detail?{detail:B.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(K)),B.ok?(r.info(`[cred] ${w.kind} replaced${B.detail?` \u2014 ${B.detail}`:""}`),$()):r.warn(`[cred] ${w.kind} replacement rejected: ${B.detail??"unknown"}`);return}if(S==="move_to_farm"){let w=b;r.info(`[farm-move] request to move ${t.projectId} onto farm ${w.farmName} (${w.farmId})`);let I=await Ia(t,w,o?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if(S==="gh_runner_setup"){let w=b;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${w.runnerName} (${w.runnerId})`);let I=await Na(t,w,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${w.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if(S==="gh_runner_teardown"){let w=b;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${w.runnerName} (${w.runnerId})`);let I=await Ua(t,w,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${w.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if(S==="tracker_fields_request"){let w=b,I={type:"tracker_fields_result",requestId:w.requestId,projectId:t.projectId,ok:!1},B=Oe();if(!B)I.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{I.fields=await Vs(B,w.projectKey),I.ok=!0}catch(K){I.error=K instanceof Error?K.message:String(K)}d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(S==="sandbox_keys"){let w=U(t.projectId);if(!w){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=Tt(t.projectId),B=vs(b,w,I,r);for(let K of B)d.readyState===d.OPEN&&d.send(JSON.stringify(K));return}if(S!=="dispatch_action")return;let j=b;if(h===!1){let w=`refused: HUB protocol incompatible with CLI v${me} (protocol ${Ie})`;d.send(JSON.stringify({type:"action_result",actionId:j.actionId,status:"failed",error:w})),r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 REFUSED: ${w}`),r.warn(`[exec] update the CLI to clear this: ${vo}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:!1,error:w});return}u.add(j.actionId);try{let w=await ca({action:j.action,repo:j.repo,trackerIssueId:j.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:P?()=>P.reportNow():void 0,refreshContextStatus:o?.contextDir?x:void 0}).catch(K=>({status:"failed",error:K instanceof Error?K.message:String(K)}));j.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:j.actionId,...w}));let I=w.status!=="failed",B=!I&&"error"in w?w.error:void 0;I?r.info(`[exec] ${j.actionId} (${j.action.type}) \u2192 done`):r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 FAILED: ${B??"?"}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:I,...B?{error:B}:{}})}finally{u.delete(j.actionId)}}),d.on("close",(m,T)=>{let b=T?.toString("utf-8")??"";if(r.info(`[ws] closed code=${m}${b?` reason=${b}`:""}`),C.stop(),k.stop(),P?.stop(),N(),b==="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:m}),!c&&setTimeout(()=>{p=g()},2e3)}),d.on("error",m=>r.warn(`[ws] error: ${m.message}`)),d}return{stop(){c=!0,p.close()}}}async function xo(t,e,r){try{let n=await M(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=fr(t.projectId,n.repos,e?.contextDir);for(let s of o)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function lf(t,e,r,n){let o=r.mountAs??r.name;if(o==="."){n.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?$r(e.root,o):ve(t.projectId,r.name);if(Ga($r(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await cf().clone(ao(r),i),n.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function uf(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?$r(e.root,o):ve(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Ga($r(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{af(i,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${i}`)}catch(s){n.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function pf(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=$r(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Fi(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 df(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 _t(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 ff(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 Zi(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 Ba(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Ya,mkdirSync as Va}from"node:fs";import{dirname as Ja}from"node:path";import{simpleGit as Ut}from"simple-git";import{execFileSync as mf}from"node:child_process";import{mkdtempSync as gf,mkdirSync as hf,readFileSync as Ma,rmSync as yf,writeFileSync as wf}from"node:fs";import{tmpdir as bf}from"node:os";import{dirname as kf,join as Fa}from"node:path";function Ha(t="codepipe-context"){let e=gf(Fa(bf(),"codepipe-ssh-")),r=Fa(e,"id_ed25519");try{return mf("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Ma(r,"utf-8"),publicKey:Ma(`${r}.pub`,"utf-8").trim()}}finally{yf(e,{recursive:!0,force:!0})}}async function Ka(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 Wa(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 qa(t,e){hf(kf(t),{recursive:!0});let r=e.endsWith(`
437
438
  `)?e:e+`
438
- `;return nf(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function cf(t,e,r="x-access-token"){let o=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,n=t.match(/^git@([^:]+):(.+)$/);if(n)return`https://${o}@${n[1]}/${n[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${o}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${o}@${s[1]}`:t}function lf(t,e){return e?.contextWrite?.token?{user:Hr(t),secret:e.contextWrite.token}:t===dr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===dr.bitbucket?e?.bitbucket?.apiToken?{user:ft,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function ko(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await M(e.hubUrl,e.cliToken,e.projectId)}catch(c){return n.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return n.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=lf(Rt(s.cloneUrl),r);if(a){let c=await uf({ctx:s,contextDir:o,cred:a,log:n});if(c)return c;n.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await pf({ctx:s,contextDir:o,privateKey:r.contextSsh.privateKey,log:n});if(c)return c;n.warn("[ctx] SSH deploy-key clone failed")}return n.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function uf(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=cf(e.cloneUrl,o.secret,o.user),s=e.branch,a=encodeURIComponent(o.secret),c=l=>l.split(o.secret).join("***").split(a).join("***");try{if(Ha(`${r}/.git`)){let l=Dt(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Xo(r);await l.reset(["--hard",`origin/${s}`]),Qo(r,u),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Ka(Wa(r),{recursive:!0}),await Dt().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await qa(r)}catch(l){return n.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function pf(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=Fa(i,o),a=Ma(e.cloneUrl),c=e.branch;try{if(Ha(`${r}/.git`)){let l=Dt(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=Xo(r);await l.reset(["--hard",`origin/${c}`]),Qo(r,u),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Ka(Wa(r),{recursive:!0}),await Dt().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Dt(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await qa(r),{root:r,contextDir:r,repos:[]}}catch(l){return n.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function qa(t){let e=Dt(t);await e.raw(["config","user.email"]).then(o=>o.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}async function Ya(t={profile:void 0}){let{cfg:e,profile:r}=Yr(t.profile),o=U(e.projectId);o&&fr(o),br(o?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),kr(o?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),$r(o?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let n=Sr(vn(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=zr("CLI_LOG",i,n);if(s.enabled){let p=new Pt(s);Xr(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=Wr(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=Sr(vn(),".codepipe",r?Sr("profiles",r,"context"):"context");if(await bn(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await ko({cfg:e,secrets:o,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),a||await bn(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=Sr(vn(),".codepipe",r?Sr("profiles",r,"context-config"):"context-config");Zr(a.contextDir,g,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=bo(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(`
439
- [${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 bf}from"node:os";import{spawnSync as df}from"node:child_process";function ff(){try{return df("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Va(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:ff(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Bt}from"node:os";import{mkdirSync as mf,readFileSync as Ja,writeFileSync as gf,existsSync as xn}from"node:fs";import{dirname as hf,join as rt}from"node:path";xn(".env")&&process.loadEnvFile(".env");function yf(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Ce(t){let e=L("SANDBOX_CONFIG");if(e)return e;let r=rt(Bt(),".codepipe","worker");return t?rt(r,"profiles",t,"config.json"):rt(r,"config.json")}function za(){return rt(Bt(),".devpipe-sandbox","config.json")}function $o(){mt(rt(Bt(),".devpipe"),rt(Bt(),".codepipe")),L("SANDBOX_CONFIG")||mt(rt(Bt(),".devpipe-sandbox"),rt(Bt(),".codepipe-sandbox"))}function ie(t){let e=Ce(t),r=null;return xn(e)?r=JSON.parse(Ja(e,"utf-8")):!t&&!L("SANDBOX_CONFIG")&&xn(za())&&(r=JSON.parse(Ja(za(),"utf-8"))),r?(r.planningLane=yf(),r):null}function Xa(t,e){let r=Ce(e);mf(hf(r),{recursive:!0}),gf(r,JSON.stringify(t,null,2)+`
440
- `,{mode:384})}import wf from"ws";var Gt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(o.signal=e);let n=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(n,o)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(o.signal=r);let n=await fetch(`${this.hubUrl}/jobs/heartbeat`,o);if(n.status===410)return"claim_lost";if(!n.ok)throw new Error(`heartbeat failed: ${n.status} ${await n.text()}`);return"ok"}async releaseJob(e,r,o){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};o&&(n.signal=o);let i=await fetch(`${this.hubUrl}/jobs/release`,n);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new wf(e)}};async function wt(t){$o();let e=ie(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Ce(t.profile)}.`),process.exit(1));let r=t.name??bf(),o=Va({projects:t.projects??[],llm:t.llm??null}),n=new Gt(t.hub.replace(/\/$/,"")),i=io(),s=he(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});Xa({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 ${Ce(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 um,readFileSync as En,readdirSync as pm,writeFileSync as dm}from"node:fs";import{dirname as fm,join as Ir,resolve as mm}from"node:path";import{spawn as Cf}from"node:child_process";import{existsSync as Rf}from"node:fs";import{spawn as kf}from"node:child_process";var Qa=16e3,Za=5e3,ec=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),$f="\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B \u0434\u0438\u0430\u043B\u043E\u0433. \u0422\u0435\u043F\u0435\u0440\u044C, \u043E\u043F\u0438\u0440\u0430\u044F\u0441\u044C \u043D\u0430 \u0432\u0441\u0451, \u0447\u0442\u043E \u043C\u044B \u043E\u0431\u0441\u0443\u0434\u0438\u043B\u0438, \u043D\u0430\u043F\u0438\u0448\u0438 \u0444\u0430\u0439\u043B DRAFT.md \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u043F\u043E \u043E\u043F\u0438\u0441\u0430\u043D\u043D\u043E\u043C\u0443 \u043A\u043E\u043D\u0442\u0440\u0430\u043A\u0442\u0443 (\u0441\u0442\u0440\u043E\u043A\u0430 1 \u2014 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u226480 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C, \u0441\u0442\u0440\u043E\u043A\u0430 2 \u043F\u0443\u0441\u0442\u0430\u044F, \u0434\u0430\u043B\u044C\u0448\u0435 \u0442\u0435\u043B\u043E \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C \u0432 Markdown) \u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0438 \u0440\u0430\u0431\u043E\u0442\u0443. \u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043F\u0438\u0448\u0438.";function Sn(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function vf(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}function xf(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function bt(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Cn(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
441
- `}async function tc(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Ke;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let o=e.onActivity,n=c=>{if(o)try{o(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),u=c.type;if(u==="assistant"){let f=c.message;for(let p of f?.content??[]){let g=p.type;if(g==="text"){let d=String(p.text??"").trim();d&&n({ts:l,kind:"text",author:"agent",text:Sn(d,Qa)})}else if(g==="tool_use"){let d=String(p.name??""),h=p.input?.file_path??p.input?.path,C=vf(h,e.workspaceDir);n({ts:l,kind:"tool",author:"agent",tool:d,...C?{file:C}:{}})}}return}if(u==="user"){let f=c.message;for(let p of f?.content??[])if(p.type==="tool_result"){let g=p.is_error===!0,d=g?Sn(xf(p.content),200):"";n({ts:l,kind:"tool_result",author:"agent",isError:g,...d?{text:d}:{}})}return}if(u==="result"){s=c;let f=String(c.subtype??"").trim();n({ts:l,kind:"result",author:"agent",...f?{text:f}:{}});return}if(u==="system"){let f=String(c.subtype??"").trim();f&&n({ts:l,kind:"system",author:"agent",text:f})}};return n({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let u=kf(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let f=!1,p=!1,g=null,d=()=>{f=!0,u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),Za)};e.signal?.addEventListener("abort",d,{once:!0});let h=null,C=()=>{h&&clearTimeout(h),h=setTimeout(()=>{p=!0,console.warn(`[claude:chat] idle for ${ec}ms \u2014 ending session`),u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),Za)},ec)},k=()=>{g&&clearTimeout(g),h&&clearTimeout(h),e.signal?.removeEventListener("abort",d)},y=!0,$=P=>{if(!(!y||u.stdin.destroyed))try{u.stdin.write(P)}catch{}};$(Cn(e.prompt)),C(),(async()=>{try{for await(let P of e.interactive.inbox){if(f||!y)break;if(C(),P.kind==="user")n({ts:Date.now(),kind:"text",author:"user",text:Sn(P.text,Qa)}),$(Cn(P.text));else{$(Cn($f)),y=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let v="",N=P=>{let x;try{x=JSON.parse(P)}catch{return}a(x)};u.stdout.on("data",P=>{i.push(P),C(),v+=P;let x;for(;(x=v.indexOf(`
439
+ `;return wf(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function $f(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 vf(t,e){return e?.contextWrite?.token?{user:Mr(t),secret:e.contextWrite.token}:t===ur.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===ur.bitbucket?e?.bitbucket?.apiToken?{user:ft,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function kn(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await M(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=vf(Ct(s.cloneUrl),r);if(a){let c=await xf({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 Sf({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 xf(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=$f(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(Ya(`${r}/.git`)){let l=Ut(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Xn(r);await l.reset(["--hard",`origin/${s}`]),Qn(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Va(Ja(r),{recursive:!0}),await Ut().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await za(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 Sf(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=qa(i,n),a=Wa(e.cloneUrl),c=e.branch;try{if(Ya(`${r}/.git`)){let l=Ut(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=Xn(r);await l.reset(["--hard",`origin/${c}`]),Qn(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Va(Ja(r),{recursive:!0}),await Ut().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ut(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await za(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 za(t){let e=Ut(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 Xa(t={profile:void 0}){let{cfg:e,profile:r}=Wr(t.profile),n=U(e.projectId);n&&pr(n),yr(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),wr(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),br(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=vr(So(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Vr("CLI_LOG",i,o);if(s.enabled){let p=new jt(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=Hr(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=vr(So(),".codepipe",r?vr("profiles",r,"context"):"context");if(await bo(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await kn({cfg:e,secrets:n,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),a||await bo(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=vr(So(),".codepipe",r?vr("profiles",r,"context-config"):"context-config");Xr(a.contextDir,g,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=bn(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(`
440
+ [${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 Af}from"node:os";import{spawnSync as Cf}from"node:child_process";function Rf(){try{return Cf("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Qa(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Rf(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Lt}from"node:os";import{mkdirSync as Tf,readFileSync as Za,writeFileSync as If,existsSync as Co}from"node:fs";import{dirname as jf,join as rt}from"node:path";Co(".env")&&process.loadEnvFile(".env");function Pf(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Ce(t){let e=L("SANDBOX_CONFIG");if(e)return e;let r=rt(Lt(),".codepipe","worker");return t?rt(r,"profiles",t,"config.json"):rt(r,"config.json")}function ec(){return rt(Lt(),".devpipe-sandbox","config.json")}function $n(){mt(rt(Lt(),".devpipe"),rt(Lt(),".codepipe")),L("SANDBOX_CONFIG")||mt(rt(Lt(),".devpipe-sandbox"),rt(Lt(),".codepipe-sandbox"))}function ie(t){let e=Ce(t),r=null;return Co(e)?r=JSON.parse(Za(e,"utf-8")):!t&&!L("SANDBOX_CONFIG")&&Co(ec())&&(r=JSON.parse(Za(ec(),"utf-8"))),r?(r.planningLane=Pf(),r):null}function tc(t,e){let r=Ce(e);Tf(jf(r),{recursive:!0}),If(r,JSON.stringify(t,null,2)+`
441
+ `,{mode:384})}import Ef from"ws";var Dt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}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 Ef(e)}};async function yt(t){$n();let e=ie(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Ce(t.profile)}.`),process.exit(1));let r=t.name??Af(),n=Qa({projects:t.projects??[],llm:t.llm??null}),o=new Dt(t.hub.replace(/\/$/,"")),i=nn(),s=ae(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});tc({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 ${Ce(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 xm,readFileSync as _o,readdirSync as Sm,writeFileSync as Cm}from"node:fs";import{dirname as Rm,join as Rr,resolve as Tm}from"node:path";import{spawn as Df}from"node:child_process";import{existsSync as Bf}from"node:fs";import{spawn as _f}from"node:child_process";var rc=16e3,nc=5e3,oc=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Of="\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B \u0434\u0438\u0430\u043B\u043E\u0433. \u0422\u0435\u043F\u0435\u0440\u044C, \u043E\u043F\u0438\u0440\u0430\u044F\u0441\u044C \u043D\u0430 \u0432\u0441\u0451, \u0447\u0442\u043E \u043C\u044B \u043E\u0431\u0441\u0443\u0434\u0438\u043B\u0438, \u043D\u0430\u043F\u0438\u0448\u0438 \u0444\u0430\u0439\u043B DRAFT.md \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u043F\u043E \u043E\u043F\u0438\u0441\u0430\u043D\u043D\u043E\u043C\u0443 \u043A\u043E\u043D\u0442\u0440\u0430\u043A\u0442\u0443 (\u0441\u0442\u0440\u043E\u043A\u0430 1 \u2014 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u226480 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C, \u0441\u0442\u0440\u043E\u043A\u0430 2 \u043F\u0443\u0441\u0442\u0430\u044F, \u0434\u0430\u043B\u044C\u0448\u0435 \u0442\u0435\u043B\u043E \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C \u0432 Markdown) \u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0438 \u0440\u0430\u0431\u043E\u0442\u0443. \u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043F\u0438\u0448\u0438.";function Ro(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Nf(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}function Uf(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function wt(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function To(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
442
+ `}async function ic(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Ke;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let n=e.onActivity,o=c=>{if(n)try{n(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),u=c.type;if(u==="assistant"){let f=c.message;for(let p of f?.content??[]){let g=p.type;if(g==="text"){let d=String(p.text??"").trim();d&&o({ts:l,kind:"text",author:"agent",text:Ro(d,rc)})}else if(g==="tool_use"){let d=String(p.name??""),h=p.input?.file_path??p.input?.path,C=Nf(h,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:d,...C?{file:C}:{}})}}return}if(u==="user"){let f=c.message;for(let p of f?.content??[])if(p.type==="tool_result"){let g=p.is_error===!0,d=g?Ro(Uf(p.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:g,...d?{text:d}:{}})}return}if(u==="result"){s=c;let f=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...f?{text:f}:{}});return}if(u==="system"){let f=String(c.subtype??"").trim();f&&o({ts:l,kind:"system",author:"agent",text:f})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let u=_f(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let f=!1,p=!1,g=null,d=()=>{f=!0,u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),nc)};e.signal?.addEventListener("abort",d,{once:!0});let h=null,C=()=>{h&&clearTimeout(h),h=setTimeout(()=>{p=!0,console.warn(`[claude:chat] idle for ${oc}ms \u2014 ending session`),u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),nc)},oc)},k=()=>{g&&clearTimeout(g),h&&clearTimeout(h),e.signal?.removeEventListener("abort",d)},y=!0,$=P=>{if(!(!y||u.stdin.destroyed))try{u.stdin.write(P)}catch{}};$(To(e.prompt)),C(),(async()=>{try{for await(let P of e.interactive.inbox){if(f||!y)break;if(C(),P.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:Ro(P.text,rc)}),$(To(P.text));else{$(To(Of)),y=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let v="",N=P=>{let x;try{x=JSON.parse(P)}catch{return}a(x)};u.stdout.on("data",P=>{i.push(P),C(),v+=P;let x;for(;(x=v.indexOf(`
442
443
  `))!==-1;){let m=v.slice(0,x).trim();v=v.slice(x+1),m&&N(m)}}),u.stderr.on("data",P=>{i.push(P);for(let x of P.split(`
443
- `)){let m=x.trim();m&&console.warn(`[claude:chat:stderr] ${m}`)}}),u.on("error",P=>{k(),l(P)}),u.on("close",P=>{if(k(),f){l(new Ke);return}if(p){l(new Error("chat session ended: idle for too long without a reply"));return}v.trim()&&N(v.trim()),console.log(`[claude:chat] exit code=${P}`),c({artifactPaths:[],log:i.join(""),usage:Sf(s)})})})}function Sf(t){let e=pt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=bt(r.input_tokens),e.outputTokens=bt(r.output_tokens),e.cacheReadInputTokens=bt(r.cache_read_input_tokens),e.cacheCreationInputTokens=bt(r.cache_creation_input_tokens)),e.totalCostUsd=bt(t.total_cost_usd),e.numTurns=bt(t.num_turns),e.durationMs=bt(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Mt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Ke=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Tf=5e3,Cr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return tc(this.binary,e);if(e.signal?.aborted)throw new Ke;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let d of e.addDirs??[])r.push("--add-dir",d);let o=[],n=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=d=>{if(d){if(d.type==="result"){i=d;return}if(d.type==="rate_limit_event"){let h=Ef(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+=ae(C.input_tokens),s.output+=ae(C.output_tokens),s.cacheRead+=ae(C.cache_read_input_tokens),s.cacheCreate+=ae(C.cache_creation_input_tokens))}}},f=e.role,p=e.onActivity,g=d=>{if(p)for(let h of _f(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=Cf(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 k=!1,y=null,$=()=>{k=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),C.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),C.kill("SIGKILL")},Tf)};e.signal?.addEventListener("abort",$,{once:!0});let v=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",$)},N="";C.stdout.on("data",P=>{o.push(P),N+=P;let x;for(;(x=N.indexOf(`
444
- `))!==-1;){let m=N.slice(0,x).trim();if(N=N.slice(x+1),m){let T=rc(m);u(T),T&&g(T)}}}),C.stderr.on("data",P=>{o.push(P),n.push(P);for(let x of P.split(`
445
- `)){let m=x.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),C.on("error",P=>{v(),h(P)}),C.on("close",P=>{if(v(),k){h(new Ke);return}if(N.trim()){let m=rc(N.trim());u(m),m&&g(m)}let x=i?.is_error===!0;if(P!==0||x){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,T=typeof i?.subtype=="string"?i.subtype:void 0,b=typeof i?.result=="string"?i.result:void 0;h(new Mt(If(P,i,n.join("")),{code:P,apiErrorStatus:m,subtype:T,resultText:b,retryAfterMs:jf(i)}));return}console.log("[claude] exit code=0"),d({artifactPaths:[],log:o.join(""),usage:Af(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(o=>o.includes("/")&&Rf(o))}};function rc(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let o=e.subtype??"";return console.log(`[claude] system ${o}`),e}if(r==="assistant"){let o=e.message;for(let n of o?.content??[]){let i=n.type;if(i==="text"){let s=String(n.text??"").trim();s&&console.log(`[claude] text: ${ot(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=Pf(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let o=e.message;for(let n of o?.content??[])if(n.type==="tool_result")if(n.is_error===!0){let i=nc(n.content);console.log(`[claude] tool_result (error)${i?`: ${ot(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let o=e.subtype??"",n=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${o} turns=${n} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${ot(JSON.stringify(e),200)}`),e}function If(t,e,r){let o=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let n=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;n?o.push(ot(n,500)):typeof s=="string"&&s!=="success"&&o.push(s),typeof i=="number"&&o.push(`(api_status=${i})`)}return o.length===1&&r.trim()&&o.push(ot(r.trim().split(`
444
+ `)){let m=x.trim();m&&console.warn(`[claude:chat:stderr] ${m}`)}}),u.on("error",P=>{k(),l(P)}),u.on("close",P=>{if(k(),f){l(new Ke);return}if(p){l(new Error("chat session ended: idle for too long without a reply"));return}v.trim()&&N(v.trim()),console.log(`[claude:chat] exit code=${P}`),c({artifactPaths:[],log:i.join(""),usage:Lf(s)})})})}function Lf(t){let e=pt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=wt(r.input_tokens),e.outputTokens=wt(r.output_tokens),e.cacheReadInputTokens=wt(r.cache_read_input_tokens),e.cacheCreationInputTokens=wt(r.cache_creation_input_tokens)),e.totalCostUsd=wt(t.total_cost_usd),e.numTurns=wt(t.num_turns),e.durationMs=wt(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Bt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Ke=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Gf=5e3,xr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return ic(this.binary,e);if(e.signal?.aborted)throw new Ke;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=Kf(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+=ce(C.input_tokens),s.output+=ce(C.output_tokens),s.cacheRead+=ce(C.cache_read_input_tokens),s.cacheCreate+=ce(C.cache_creation_input_tokens))}}},f=e.role,p=e.onActivity,g=d=>{if(p)for(let h of qf(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=Df(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 k=!1,y=null,$=()=>{k=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),C.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),C.kill("SIGKILL")},Gf)};e.signal?.addEventListener("abort",$,{once:!0});let v=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",$)},N="";C.stdout.on("data",P=>{n.push(P),N+=P;let x;for(;(x=N.indexOf(`
445
+ `))!==-1;){let m=N.slice(0,x).trim();if(N=N.slice(x+1),m){let T=sc(m);u(T),T&&g(T)}}}),C.stderr.on("data",P=>{n.push(P),o.push(P);for(let x of P.split(`
446
+ `)){let m=x.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),C.on("error",P=>{v(),h(P)}),C.on("close",P=>{if(v(),k){h(new Ke);return}if(N.trim()){let m=sc(N.trim());u(m),m&&g(m)}let x=i?.is_error===!0;if(P!==0||x){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,T=typeof i?.subtype=="string"?i.subtype:void 0,b=typeof i?.result=="string"?i.result:void 0;h(new Bt(Mf(P,i,o.join("")),{code:P,apiErrorStatus:m,subtype:T,resultText:b,retryAfterMs:Ff(i)}));return}console.log("[claude] exit code=0"),d({artifactPaths:[],log:n.join(""),usage:Wf(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("/")&&Bf(n))}};function sc(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: ${nt(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=Hf(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=cc(o.content);console.log(`[claude] tool_result (error)${i?`: ${nt(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)} ${nt(JSON.stringify(e),200)}`),e}function Mf(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(nt(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(nt(r.trim().split(`
446
447
  `).slice(-5).join(`
447
- `),500)),o.join(" \u2014 ")}function jf(t){if(!t)return;let e=t.retry_after;if(typeof e=="number"&&e>0)return Math.round(e*1e3);let r=typeof t.result=="string"?t.result:"",o=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(r),n=o?Number(o[1]??o[2]):NaN;return Number.isFinite(n)&&n>0?n*1e3:void 0}function nc(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Pf(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=${ot(r,80)}`}return""}function ot(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function ae(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ef(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=ae(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:ae(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:o,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(n.surpassedThreshold=e.surpassedThreshold),n}function Af(t,e,r,o){let n=pt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=ae(i.input_tokens),n.outputTokens=ae(i.output_tokens),n.cacheReadInputTokens=ae(i.cache_read_input_tokens),n.cacheCreationInputTokens=ae(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=ae(t?.total_cost_usd),n.numTurns=t&&ae(t.num_turns)>0?ae(t.num_turns):r,n.durationMs=ae(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var oc=200;function _f(t,e){let r=Date.now(),o=t.type;if(o==="system"){let n=String(t.subtype??"").trim();return n?[{ts:r,kind:"system",text:n}]:[]}if(o==="assistant"){let n=t.message,i=[];for(let s of n?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:ot(c,oc)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,f=Of(u,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return i}if(o==="user"){let n=t.message,i=[];for(let s of n?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?ot(nc(s.content),oc):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(o==="result"){let n=String(t.subtype??"").trim(),i=typeof t.num_turns=="number"?t.num_turns:void 0,s=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...n?{text:n}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function Of(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 Nf,writeFileSync as Ft}from"node:fs";import{dirname as Uf,join as Ht}from"node:path";function ic(t,e,r){let o=Ht(t,e);Nf(Uf(o),{recursive:!0}),Ft(o,r)}var Rr=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},o=r.trackerIssueKey??"TASK",n=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=Lf(o,n,i);Ft(Ht(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Ft(Ht(e.workspaceDir,"SOLUTION.md"),Df(o,n,i,a)),s.push("SOLUTION.md"),Ft(Ht(e.workspaceDir,"QUESTIONS.md"),Bf(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;ic(e.workspaceDir,"changes/sample.patch",Gf(o,n,a)),s.push("changes/sample.patch"),ic(e.workspaceDir,"diff-summary.md",Mf(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Ft(Ht(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${o})
448
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:pt()}}async runInteractive(e){let r=e.onActivity,o=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),o("\u041F\u0440\u0438\u0432\u0435\u0442! \u041E\u043F\u0438\u0448\u0438\u0442\u0435 \u0437\u0430\u0434\u0430\u0447\u0443, \u043A\u043E\u0442\u043E\u0440\u0443\u044E \u0445\u043E\u0442\u0438\u0442\u0435 \u0441\u0444\u043E\u0440\u043C\u0443\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C.");let n="\u0427\u0435\u0440\u043D\u043E\u0432\u0438\u043A \u0438\u0437 \u0447\u0430\u0442\u0430";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Ke;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(n=i.text.trim().slice(0,80)),o(`\u041F\u043E\u043D\u044F\u043B: **${i.text.trim()}**. \u0427\u0442\u043E-\u043D\u0438\u0431\u0443\u0434\u044C \u0435\u0449\u0451 \u0443\u0442\u043E\u0447\u043D\u0438\u0442\u044C?`);else break}return Ft(Ht(e.workspaceDir,"DRAFT.md"),`${n}
448
+ `),500)),n.join(" \u2014 ")}function Ff(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 cc(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Hf(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=${nt(r,80)}`}return""}function nt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function ce(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Kf(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=ce(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:ce(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 Wf(t,e,r,n){let o=pt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=ce(i.input_tokens),o.outputTokens=ce(i.output_tokens),o.cacheReadInputTokens=ce(i.cache_read_input_tokens),o.cacheCreationInputTokens=ce(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=ce(t?.total_cost_usd),o.numTurns=t&&ce(t.num_turns)>0?ce(t.num_turns):r,o.durationMs=ce(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}var ac=200;function qf(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:nt(c,ac)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,f=Yf(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?nt(cc(s.content),ac):"";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 Yf(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 Vf,writeFileSync as Gt}from"node:fs";import{dirname as Jf,join as Mt}from"node:path";function lc(t,e,r){let n=Mt(t,e);Vf(Jf(n),{recursive:!0}),Gt(n,r)}var Sr=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=zf(n,o,i);Gt(Mt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Gt(Mt(e.workspaceDir,"SOLUTION.md"),Xf(n,o,i,a)),s.push("SOLUTION.md"),Gt(Mt(e.workspaceDir,"QUESTIONS.md"),Qf(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;lc(e.workspaceDir,"changes/sample.patch",Zf(n,o,a)),s.push("changes/sample.patch"),lc(e.workspaceDir,"diff-summary.md",em(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Gt(Mt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
449
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:pt()}}async runInteractive(e){let r=e.onActivity,n=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("\u041F\u0440\u0438\u0432\u0435\u0442! \u041E\u043F\u0438\u0448\u0438\u0442\u0435 \u0437\u0430\u0434\u0430\u0447\u0443, \u043A\u043E\u0442\u043E\u0440\u0443\u044E \u0445\u043E\u0442\u0438\u0442\u0435 \u0441\u0444\u043E\u0440\u043C\u0443\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C.");let o="\u0427\u0435\u0440\u043D\u043E\u0432\u0438\u043A \u0438\u0437 \u0447\u0430\u0442\u0430";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Ke;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`\u041F\u043E\u043D\u044F\u043B: **${i.text.trim()}**. \u0427\u0442\u043E-\u043D\u0438\u0431\u0443\u0434\u044C \u0435\u0449\u0451 \u0443\u0442\u043E\u0447\u043D\u0438\u0442\u044C?`);else break}return Gt(Mt(e.workspaceDir,"DRAFT.md"),`${o}
449
450
 
450
451
  \u0421\u0444\u043E\u0440\u043C\u0438\u0440\u043E\u0432\u0430\u043D\u043E \u0432 \u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u043E\u043C \u0447\u0430\u0442\u0435 (mock runner).
451
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:pt()}}};function Lf(t,e,r){return`# ${t} \u2014 Estimate
452
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:pt()}}};function zf(t,e,r){return`# ${t} \u2014 Estimate
452
453
 
453
454
  **Title:** ${e}
454
455
 
@@ -469,10 +470,10 @@ production-grade estimates.)
469
470
  ${r.split(`
470
471
  `).slice(0,8).join(`
471
472
  `).trim()||"(empty)"}
472
- `}function Df(t,e,r,o){let n=o?`
473
+ `}function Xf(t,e,r,n){let o=n?`
473
474
  ## Reviewer rework instruction
474
475
 
475
- > ${o.split(`
476
+ > ${n.split(`
476
477
  `).join(`
477
478
  > `)}
478
479
 
@@ -480,7 +481,7 @@ This pass addresses the points above.
480
481
  `:"";return`# ${t} \u2014 Solution
481
482
 
482
483
  **Title:** ${e}
483
- ${n}
484
+ ${o}
484
485
  ## Plan
485
486
  1. Locate the relevant module(s) in the project repo.
486
487
  2. Apply the minimum diff that satisfies the DoD in the YouTrack task.
@@ -498,21 +499,21 @@ TBD (mock runner does not yet inspect project code).
498
499
  ${r.split(`
499
500
  `).slice(0,8).join(`
500
501
  `).trim()||"(empty)"}
501
- `}function Bf(t){return`# ${t} \u2014 Open questions
502
+ `}function Qf(t){return`# ${t} \u2014 Open questions
502
503
 
503
504
  (none \u2014 mock runner did not surface ambiguities.)
504
- `}function Gf(t,e,r){let o=r?` (rework: ${r.split(`
505
+ `}function Zf(t,e,r){let n=r?` (rework: ${r.split(`
505
506
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
506
507
  index 0000000..1111111 100644
507
508
  --- a/CHANGELOG.md
508
509
  +++ b/CHANGELOG.md
509
510
  @@ -1,3 +1,6 @@
510
- +## ${t} \u2014 ${e}${o}
511
+ +## ${t} \u2014 ${e}${n}
511
512
  +
512
513
  +- mock-runner placeholder change for slice 5 testing.
513
514
  +
514
515
  # Changelog
515
- `}function Mf(t,e,r){return`# ${t} \u2014 Diff summary
516
+ `}function em(t,e,r){return`# ${t} \u2014 Diff summary
516
517
 
517
518
  **Title:** ${e}
518
519
  ${r?`
@@ -523,97 +524,97 @@ ${r?`
523
524
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
524
525
 
525
526
  (Mock-runner output. Replace with claude-headless for production patches.)
526
- `}function sc(t){switch(t){case"mock":return new Rr;case"claude-headless":return new Cr;default:return null}}function lc(t=process.env){return{maxAttempts:vo(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:vo(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:vo(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:vo(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var Ff=new Set([429,500,502,503,529]),ac=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,Hf=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,Kf=new Set(["error_max_turns"]);function Wf(t){if(t instanceof Mt){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return Hf.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&Kf.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:Ff.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:ac.test(s)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:o??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return ac.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var cc=/(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 uc(t){if(t instanceof Mt){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&cc.test(o)}let e=t instanceof Error?t.message:String(t);return cc.test(e)}function qf(t,e,r){if(typeof r=="number"&&r>0)return Math.min(r,e.maxDelayMs);let o=e.baseDelayMs*2**(t-1),n=Math.min(o,e.maxDelayMs);return Math.round(n/2+Math.random()*(n/2))}async function pc(t,e,r){let o=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),n=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=Wf(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=qf(s,r.policy,c.retryAfterMs);if(Date.now()+u>n)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await o(u)}}function vo(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as Yf,rmSync as Vf,writeFileSync as dc}from"node:fs";import{tmpdir as Jf}from"node:os";import{join as Rn}from"node:path";function xo(t){return`[url "https://${t}/"]
527
+ `}function uc(t){switch(t){case"mock":return new Sr;case"claude-headless":return new xr;default:return null}}function fc(t=process.env){return{maxAttempts:vn(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:vn(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:vn(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:vn(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var tm=new Set([429,500,502,503,529]),pc=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,rm=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,nm=new Set(["error_max_turns"]);function om(t){if(t instanceof Bt){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return rm.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&nm.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:tm.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:pc.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 pc.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var dc=/(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 mc(t){if(t instanceof Bt){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&dc.test(n)}let e=t instanceof Error?t.message:String(t);return dc.test(e)}function im(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 gc(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=om(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=im(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 vn(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as sm,rmSync as am,writeFileSync as hc}from"node:fs";import{tmpdir as cm}from"node:os";import{join as Io}from"node:path";function xn(t){return`[url "https://${t}/"]
527
528
  insteadOf = git@${t}:
528
529
  insteadOf = ssh://git@${t}/
529
- `}var zf=xo("github.com"),Xf=xo("bitbucket.org"),Qf=xo("gitlab.com");function fc(t,e){if(t.length===0)return null;let r=Yf(Rn(Jf(),"devpipe-gitcreds-")),o=Rn(r,"credentials"),n=Rn(r,"gitconfig");return dc(o,t.join(`
530
+ `}var lm=xn("github.com"),um=xn("bitbucket.org"),pm=xn("gitlab.com");function yc(t,e){if(t.length===0)return null;let r=sm(Io(cm(),"devpipe-gitcreds-")),n=Io(r,"credentials"),o=Io(r,"gitconfig");return hc(n,t.join(`
530
531
  `)+`
531
- `,{mode:384}),dc(n,`[credential]
532
- helper = store --file=${o}
533
- `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{Vf(r,{recursive:!0,force:!0})}catch{}}}}function Tn(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(zf)),t.bitbucket?.apiToken&&(e.push(`https://${ft}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Xf)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Qf)),fc(e,r)}function mc(t,e){if(t.contextWrite?.token){let r=Rt(e)??"github.com",o=Hr(r);return fc([`https://${o}:${t.contextWrite.token}@${r}`],[xo(r)])}return Tn(t)}import{spawn as hc}from"node:child_process";import{existsSync as So,mkdirSync as Co,readFileSync as Zf,rmSync as In,symlinkSync as em}from"node:fs";import{homedir as tm}from"node:os";import{dirname as Ro,join as kt}from"node:path";function yc(){return kt(tm(),".codepipe-sandbox","repos")}var Kt=new Map;function wc(t,e){let o=(Kt.get(t)??Promise.resolve()).then(e,e),n=o.then(()=>{Kt.get(t)===n&&Kt.delete(t)},()=>{Kt.get(t)===n&&Kt.delete(t)});return Kt.set(t,n),o}function gc(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 bc(t,e,r,o,n){if(So(kt(t,".git"))){let i=async s=>{await Y(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],n),await Y(t,["reset","--hard",`origin/${s}`],n),await Y(t,["clean","-fdx"],n)};try{return await i(r),r}catch(s){if(!o||o===r||!gc(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}So(t)&&In(t,{recursive:!0,force:!0}),Co(Ro(t),{recursive:!0});try{return await Y(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],n),r}catch(i){if(!o||o===r||!gc(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),So(t)&&In(t,{recursive:!0,force:!0}),Co(Ro(t),{recursive:!0}),await Y(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function kc(t){await Y(t.workspacePath,["reset","--hard",t.baseSha]),await Y(t.workspacePath,["clean","-fdx"])}var Wt="CodePipe Agent",qt="codepipe@codepartner.ee";async function $c(t,e){let r=t.workspacePath;await Y(r,["add","-A"]);let o=(await ne(r,["write-tree"])).trim(),n=(await ne(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:Wt,GIT_AUTHOR_EMAIL:qt,GIT_COMMITTER_NAME:Wt,GIT_COMMITTER_EMAIL:qt};return(await ne(r,["commit-tree",o,"-m",e],i)).trim()}async function vc(t,e,r,o,n){try{await Y(t.workspacePath,["push","--force",o,`${e}:refs/heads/${r}`],n)}catch(i){let s=i instanceof Error?i.message:String(i);throw Rt(o)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function xc(t,e){return ne(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Sc(t,e,r,o,n){await Y(t.workspacePath,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],n),await Y(t.workspacePath,["checkout","--force",r])}async function Cc(t,e,r,o,n,i){let s=t.workspacePath;await Y(s,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await ne(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=d=>ne(s,["rev-parse","-q","--verify",`${d}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(o)&&((await ne(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(h=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(h)}`)}),await c(o)||await Y(s,["fetch","origin",o],i).catch(()=>{}),!await c(o)))throw new Error(`moved-base apply: delivery base ${o.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:Wt,GIT_AUTHOR_EMAIL:qt,GIT_COMMITTER_NAME:Wt,GIT_COMMITTER_EMAIL:qt},u=(await ne(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),f=(await ne(s,["commit-tree",u,"-p",o,"-m","delivery"],l)).trim();await Y(s,["cherry-pick","--quit"],l).catch(()=>{});let p=null;try{await Y(s,["cherry-pick","--no-commit",f],l)}catch(d){p=d instanceof Error?d.message:String(d)}let g=(await ne(s,["diff","--name-only","--diff-filter=U"])).split(`
534
- `).map(d=>d.trim()).filter(d=>d.length>0);if(p&&g.length===0)throw await Y(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${p}`);return g}async function jn(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:Wt,GIT_AUTHOR_EMAIL:qt,GIT_COMMITTER_NAME:Wt,GIT_COMMITTER_EMAIL:qt};(await ne(o,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(o,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await Y(o,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await Y(o,["merge","--no-commit","--no-ff",`origin/${e}`],n)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await ne(o,["diff","--name-only","--diff-filter=U"])).split(`
535
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await ne(o,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function Y(t,e,r){return new Promise((o,n)=>{let i=hc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",n),i.on("close",a=>{if(a===0)return o();n(new Error(`git ${e[0]} failed (exit ${a}):
536
- ${s.join("").trim()||"(no stderr)"}`))})})}function ne(t,e,r){return new Promise((o,n)=>{let i=hc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",n),i.on("close",c=>{if(c===0)return o(s.join(""));n(new Error(`git ${e[0]} failed (exit ${c}):
537
- ${a.join("").trim()||"(no stderr)"}`))})})}function Rc(t,e){So(t)&&In(t,{recursive:!0,force:!0}),Co(Ro(t),{recursive:!0}),em(e,t,"dir")}async function Tc(t,e,r){await Y(t,["worktree","prune"]).catch(()=>{}),Co(Ro(r),{recursive:!0}),await Y(t,["worktree","add","--detach",r,`origin/${e}`])}async function Ic(t,e,r,o="worktree",n){return r.length===0?[]:wc(e,async()=>{let i=[];for(let s of r){let a=kt(yc(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await bc(a,s.cloneUrl,s.ref,s.defaultBranch,n)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await ne(a,["rev-parse","HEAD"])).trim(),u=kt(t,"code",s.name);o==="direct"?(Rc(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await Tc(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 jc(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=r;return wc(e,async()=>{let s=kt(yc(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await bc(s,i.cloneUrl,i.ref,void 0,n)}catch(l){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(l instanceof Error?l.message:String(l)))}let a=kt(t,"context");o==="direct"?(Rc(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await Tc(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await ne(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function Pc(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await Y(r,["add","-A",...o]).catch(()=>{});let n;try{n=await ne(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...o])}catch{return[]}let i=n.split(`
538
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Zf(kt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as rm}from"node:fs";import{join as om}from"node:path";var Pn=8*1024,Yt=class extends Error{},Tr="meta/build-result.json";function Ec(t){let e=om(t,Tr),r;try{r=rm(e,"utf-8")}catch{throw new Yt(`BUILD produced no ${Tr} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(u){throw new Yt(`${Tr} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!o||typeof o!="object")throw new Yt(`${Tr} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new Yt(`${Tr}: "ok" must be a boolean`);let i=n.ok,a=(Array.isArray(n.steps)?n.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let f=u,p=typeof f.name=="string"?f.name:null,g=typeof f.exitCode=="number"?f.exitCode:null;if(p===null||g===null)return[];let d={name:p,exitCode:g};return typeof f.durationMs=="number"&&(d.durationMs=f.durationMs),[d]}),c=typeof n.logTail=="string"?nm(n.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof n.failedStep=="string"&&n.failedStep)l.failedStep=n.failedStep;else if(!i){let u=a.find(f=>f.exitCode!==0);u&&(l.failedStep=u.name)}return l}function nm(t){let e=Buffer.from(t,"utf-8");return e.length<=Pn?t:`\u2026 [${e.length-Pn} bytes elided] \u2026
539
- `+e.subarray(e.length-Pn).toString("utf-8")}import{lstatSync as im,mkdtempSync as sm,readFileSync as am,readdirSync as _c,rmSync as Ac}from"node:fs";import{tmpdir as cm}from"node:os";import{join as To,relative as lm}from"node:path";var Oc=new Set(["code","context"]);function Nc(t){let e=sm(To(cm(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Ac(e,{recursive:!0,force:!0}),listFiles:()=>Uc(e,e),readFile:r=>am(To(e,r),"utf-8"),clean:()=>{for(let r of _c(e))Oc.has(r)||Ac(To(e,r),{recursive:!0,force:!0})}}}function Uc(t,e){let r=[];for(let o of _c(e)){let n=To(e,o),i=im(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Oc.has(o))continue;r.push(...Uc(t,n))}else r.push(lm(t,n))}return r}var Io=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),gm=new Set(["implement","resolve-conflict"]);function hm(t){let e=Buffer.from(t,"utf-8");if(e.length<=Io)return t;let r=Math.floor(Io/4),o=Io-r,n=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-o).toString("utf-8"),s=e.length-r-o;return`${n}
532
+ `,{mode:384}),hc(o,`[credential]
533
+ helper = store --file=${n}
534
+ `+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{am(r,{recursive:!0,force:!0})}catch{}}}}function jo(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(lm)),t.bitbucket?.apiToken&&(e.push(`https://${ft}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(um)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(pm)),yc(e,r)}function wc(t,e){if(t.contextWrite?.token){let r=Ct(e)??"github.com",n=Mr(r);return yc([`https://${n}:${t.contextWrite.token}@${r}`],[xn(r)])}return jo(t)}import{spawn as kc}from"node:child_process";import{existsSync as Sn,mkdirSync as Cn,readFileSync as dm,rmSync as Po,symlinkSync as fm}from"node:fs";import{homedir as mm}from"node:os";import{dirname as Rn,join as bt}from"node:path";function $c(){return bt(mm(),".codepipe-sandbox","repos")}var Ft=new Map;function vc(t,e){let n=(Ft.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Ft.get(t)===o&&Ft.delete(t)},()=>{Ft.get(t)===o&&Ft.delete(t)});return Ft.set(t,o),n}function bc(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 xc(t,e,r,n,o){if(Sn(bt(t,".git"))){let i=async s=>{await Y(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],o),await Y(t,["reset","--hard",`origin/${s}`],o),await Y(t,["clean","-fdx"],o)};try{return await i(r),r}catch(s){if(!n||n===r||!bc(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}}Sn(t)&&Po(t,{recursive:!0,force:!0}),Cn(Rn(t),{recursive:!0});try{return await Y(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(i){if(!n||n===r||!bc(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Sn(t)&&Po(t,{recursive:!0,force:!0}),Cn(Rn(t),{recursive:!0}),await Y(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}}async function Sc(t){await Y(t.workspacePath,["reset","--hard",t.baseSha]),await Y(t.workspacePath,["clean","-fdx"])}var Ht="CodePipe Agent",Kt="codepipe@codepartner.ee";async function Cc(t,e){let r=t.workspacePath;await Y(r,["add","-A"]);let n=(await oe(r,["write-tree"])).trim(),o=(await oe(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt};return(await oe(r,["commit-tree",n,"-m",e],i)).trim()}async function Rc(t,e,r,n,o){try{await Y(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Ct(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 Tc(t,e){return oe(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Ic(t,e,r,n,o){await Y(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await Y(t.workspacePath,["checkout","--force",r])}async function jc(t,e,r,n,o,i){let s=t.workspacePath;await Y(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await oe(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=d=>oe(s,["rev-parse","-q","--verify",`${d}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await oe(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(h=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(h)}`)}),await c(n)||await Y(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt},u=(await oe(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),f=(await oe(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await Y(s,["cherry-pick","--quit"],l).catch(()=>{});let p=null;try{await Y(s,["cherry-pick","--no-commit",f],l)}catch(d){p=d instanceof Error?d.message:String(d)}let g=(await oe(s,["diff","--name-only","--diff-filter=U"])).split(`
535
+ `).map(d=>d.trim()).filter(d=>d.length>0);if(p&&g.length===0)throw await Y(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${p}`);return g}async function Eo(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt};(await oe(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(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 Y(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await Y(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await oe(n,["diff","--name-only","--diff-filter=U"])).split(`
536
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await oe(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 Y(t,e,r){return new Promise((n,o)=>{let i=kc("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}):
537
+ ${s.join("").trim()||"(no stderr)"}`))})})}function oe(t,e,r){return new Promise((n,o)=>{let i=kc("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}):
538
+ ${a.join("").trim()||"(no stderr)"}`))})})}function Pc(t,e){Sn(t)&&Po(t,{recursive:!0,force:!0}),Cn(Rn(t),{recursive:!0}),fm(e,t,"dir")}async function Ec(t,e,r){await Y(t,["worktree","prune"]).catch(()=>{}),Cn(Rn(r),{recursive:!0}),await Y(t,["worktree","add","--detach",r,`origin/${e}`])}async function Ac(t,e,r,n="worktree",o){return r.length===0?[]:vc(e,async()=>{let i=[];for(let s of r){let a=bt($c(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await xc(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 oe(a,["rev-parse","HEAD"])).trim(),u=bt(t,"code",s.name);n==="direct"?(Pc(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await Ec(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 _c(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=r;return vc(e,async()=>{let s=bt($c(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await xc(s,i.cloneUrl,i.ref,void 0,o)}catch(l){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(l instanceof Error?l.message:String(l)))}let a=bt(t,"context");n==="direct"?(Pc(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await Ec(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await oe(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function Oc(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await Y(r,["add","-A",...n]).catch(()=>{});let o;try{o=await oe(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
539
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=dm(bt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as gm}from"node:fs";import{join as hm}from"node:path";var Ao=8*1024,Wt=class extends Error{},Cr="meta/build-result.json";function Nc(t){let e=hm(t,Cr),r;try{r=gm(e,"utf-8")}catch{throw new Wt(`BUILD produced no ${Cr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Wt(`${Cr} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Wt(`${Cr} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Wt(`${Cr}: "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"?ym(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 ym(t){let e=Buffer.from(t,"utf-8");return e.length<=Ao?t:`\u2026 [${e.length-Ao} bytes elided] \u2026
540
+ `+e.subarray(e.length-Ao).toString("utf-8")}import{lstatSync as wm,mkdtempSync as bm,readFileSync as km,readdirSync as Lc,rmSync as Uc}from"node:fs";import{tmpdir as $m}from"node:os";import{join as Tn,relative as vm}from"node:path";var Dc=new Set(["code","context"]);function Bc(t){let e=bm(Tn($m(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Uc(e,{recursive:!0,force:!0}),listFiles:()=>Gc(e,e),readFile:r=>km(Tn(e,r),"utf-8"),clean:()=>{for(let r of Lc(e))Dc.has(r)||Uc(Tn(e,r),{recursive:!0,force:!0})}}}function Gc(t,e){let r=[];for(let n of Lc(e)){let o=Tn(e,n),i=wm(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Dc.has(n))continue;r.push(...Gc(t,o))}else r.push(vm(t,o))}return r}var In=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Im=new Set(["implement","resolve-conflict"]);function jm(t){let e=Buffer.from(t,"utf-8");if(e.length<=In)return t;let r=Math.floor(In/4),n=In-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}
540
541
 
541
- \u2026 [${s} bytes elided \u2014 log capped at ${Io} bytes for upload] \u2026
542
+ \u2026 [${s} bytes elided \u2014 log capped at ${In} bytes for upload] \u2026
542
543
 
543
- ${i}`}function ym(){let t=[],e=!1,r=null,o=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},n=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||o(i)},finalize(){e||(o({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,n()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function jr(t={}){$o();let e=ie(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=zr("SANDBOX_LOG","sandbox",mm("./logs"));if(o.enabled){let x=new Pt(o);Xr(x),console.log(`[log] file logging \u2192 ${x.path} (rotate at ${o.maxBytes}B, keep ${o.maxFiles})`)}console.log(`codepipe-sandbox v${fe} (protocol ${Ie})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let n=sc(e.llm);console.log(`llm backend: ${n?n.name():"(none \u2014 will not claim agent jobs)"}`);let i=lc();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new Gt(e.hubUrl,e.token),a=!1,c=new AbortController,l=new Map,u=null,f=null,p=!1,g=()=>{let x=s.openControlSocket();return u=x,x.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:fe,protocolVersion:Ie};x.send(JSON.stringify(m))}),x.on("message",m=>{let T=m.toString("utf-8"),b=null;try{let S=JSON.parse(T);S&&typeof S=="object"&&(b=S)}catch{}if(b&&b.type==="hello"){let S=b;f=Br(S.protocolVersion);let j=f?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${j}`),f&&(p=!1);return}if(b&&b.type==="pause_job"){let S=typeof b.jobId=="string"?b.jobId:"",j=S?l.get(S):void 0;j?(console.warn(`[ws] pause_job ${S} \u2014 aborting agent`),j.paused=!0,j.abort.abort()):console.log(`[ws] pause_job ${S} \u2014 not a running job, ignoring`),S&&x.send(JSON.stringify({type:"job_paused",jobId:S}));return}if(b&&(b.type==="chat_user_message"||b.type==="chat_finalize")){let S=typeof b.jobId=="string"?b.jobId:"",j=S?l.get(S):void 0;if(j?.chatInbox)if(b.type==="chat_user_message"){let w=typeof b.text=="string"?b.text:"";w.trim()&&j.chatInbox.push({kind:"user",text:w})}else j.chatInbox.finalize();else console.log(`[ws] ${String(b.type)} ${S} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${T}`)}),x.on("close",(m,T)=>{console.log(`[ws] closed code=${m} reason=${T?.toString()||""}`),u===x&&(u=null),!a&&setTimeout(g,2e3)}),x.on("error",m=>console.warn(`[ws] error: ${m.message}`)),x},d=g(),h=async x=>{for(;!a;){if(f===!1){p||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${fe}, protocol ${Ie}) \u2014 not claiming jobs until versions align.`),p=!0),await new Promise(m=>setTimeout(m,5e3));continue}try{let m=await s.claim(c.signal,x);if(m.status===204)continue;if(m.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,a=!0;break}if(!m.ok){console.warn(`[claim:${x}] ${m.status} \u2014 backoff 5s`),await new Promise(b=>setTimeout(b,5e3));continue}let T=await m.json();await C(s,T)}catch(m){if(c.signal.aborted)break;let T=m instanceof Error?m.message:String(m);console.warn(`[claim:${x}] error: ${T} \u2014 backoff 5s`),await new Promise(b=>setTimeout(b,5e3))}}};async function C(x,m){let T={abort:new AbortController,paused:!1};m.role==="chat"&&(T.chatInbox=ym()),l.set(m.jobId,T);let b=!1,S=null,j=null,w=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),I=async()=>{try{await x.heartbeat(m.jobId)==="claim_lost"&&(b=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(F){let ke=F instanceof Error?F.message:String(F);console.warn(`[job] ${m.jobId} heartbeat error: ${ke}`)}};I();let B=setInterval(()=>{I()},w),K=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(y(m.prompt," \u2502 "));let Re=[],ct=null,E=400,pe=25,We=500,Ue=()=>{if(ct&&(clearTimeout(ct),ct=null),Re.length===0)return;let F=Re.splice(0,Re.length),ke=u;if(!ke||ke.readyState!==ke.OPEN)return;let Le={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:F};try{ke.send(JSON.stringify(Le))}catch{}},Uo=F=>{Re.push(F),Re.length>We&&Re.shift(),Re.length>=pe?Ue():ct||(ct=setTimeout(Ue,E))},lt=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,ee=new Set,Lo=null;try{if(!n){b||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:K,finishedAt:new Date().toISOString()});return}let F=Nc(m.jobId);console.log(`[job] ${m.jobId} workspace=${F.dir}`);let ke=k(m,r);S=ke.gitCreds,j=ke.contextGitCreds;let Le=S?.env,Zn=ke.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ke.claudeOauthToken}:void 0,De=[],ar=null,Do=null;try{let _="worktree";De=await Ic(F.dir,m.projectId,m.projectRepos,_,Le);let O=await jc(F.dir,m.projectId,m.contextRepo,_,Le);Do=O,ar=O?.workspacePath??null}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} materialize failed: ${O}`),b||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${O}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let ei=async()=>{if(!m.deliveries||m.deliveries.length===0)return[];let _=m.contextRepo?.cloneUrl;if(!_||!Le)throw new Error(_?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let O=[];for(let G of m.deliveries){let H=De.find(de=>de.name===G.name);if(H){if(m.role==="implement"&&G.baseSha&&G.baseSha!==H.baseSha){let de=await Cc(H,G.deliveryRef,G.deliverySha,G.baseSha,_,Le);console.log(`[job] ${m.jobId} ${H.name}: base moved ${G.baseSha.slice(0,10)} \u2192 ${H.baseSha.slice(0,10)} \u2014 re-applied delivery ${G.deliverySha.slice(0,10)} (${de.length} conflicted file(s))`),de.length>0&&O.push(`- **${H.name}**:`,...de.map(cr=>` - \`${cr}\``));continue}await Sc(H,G.deliveryRef,G.deliverySha,_,Le),console.log(`[job] ${m.jobId} ${H.name}: checked out delivery ${G.deliverySha.slice(0,10)} for ${m.role}`)}}return O},Bo=[];if(m.role==="build"||m.role==="implement")try{Bo=await ei()}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} delivery checkout failed: ${O}`),b||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${O}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let Go=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},ti="";if(m.role==="resolve-conflict"){if(!De.some(_=>Go[_.name])){let _="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${m.jobId} ${_}`),b||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}try{let _=[];for(let O of De){let G=Go[O.name];if(!G)continue;let H=await jn(O,G,Le);console.log(`[job] ${m.jobId} ${O.name}: merged ${G} into ${O.ref} \u2014 ${H.length} conflicted file(s)`),H.length>0?_.push(`- **${O.name}**:`,...H.map(de=>` - \`${de}\``)):_.push(`- **${O.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}ti=`
544
+ ${i}`}function Pm(){let t=[],e=!1,r=null,n=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},o=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||n(i)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function Tr(t={}){$n();let e=ie(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=Vr("SANDBOX_LOG","sandbox",Tm("./logs"));if(n.enabled){let x=new jt(n);Jr(x),console.log(`[log] file logging \u2192 ${x.path} (rotate at ${n.maxBytes}B, keep ${n.maxFiles})`)}console.log(`codepipe-sandbox v${me} (protocol ${Ie})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let o=uc(e.llm);console.log(`llm backend: ${o?o.name():"(none \u2014 will not claim agent jobs)"}`);let i=fc();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new Dt(e.hubUrl,e.token),a=!1,c=new AbortController,l=new Map,u=null,f=null,p=!1,g=()=>{let x=s.openControlSocket();return u=x,x.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:me,protocolVersion:Ie};x.send(JSON.stringify(m))}),x.on("message",m=>{let T=m.toString("utf-8"),b=null;try{let S=JSON.parse(T);S&&typeof S=="object"&&(b=S)}catch{}if(b&&b.type==="hello"){let S=b;f=Lr(S.protocolVersion);let j=f?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${j}`),f&&(p=!1);return}if(b&&b.type==="pause_job"){let S=typeof b.jobId=="string"?b.jobId:"",j=S?l.get(S):void 0;j?(console.warn(`[ws] pause_job ${S} \u2014 aborting agent`),j.paused=!0,j.abort.abort()):console.log(`[ws] pause_job ${S} \u2014 not a running job, ignoring`),S&&x.send(JSON.stringify({type:"job_paused",jobId:S}));return}if(b&&(b.type==="chat_user_message"||b.type==="chat_finalize")){let S=typeof b.jobId=="string"?b.jobId:"",j=S?l.get(S):void 0;if(j?.chatInbox)if(b.type==="chat_user_message"){let w=typeof b.text=="string"?b.text:"";w.trim()&&j.chatInbox.push({kind:"user",text:w})}else j.chatInbox.finalize();else console.log(`[ws] ${String(b.type)} ${S} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${T}`)}),x.on("close",(m,T)=>{console.log(`[ws] closed code=${m} reason=${T?.toString()||""}`),u===x&&(u=null),!a&&setTimeout(g,2e3)}),x.on("error",m=>console.warn(`[ws] error: ${m.message}`)),x},d=g(),h=async x=>{for(;!a;){if(f===!1){p||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${me}, protocol ${Ie}) \u2014 not claiming jobs until versions align.`),p=!0),await new Promise(m=>setTimeout(m,5e3));continue}try{let m=await s.claim(c.signal,x);if(m.status===204)continue;if(m.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,a=!0;break}if(!m.ok){console.warn(`[claim:${x}] ${m.status} \u2014 backoff 5s`),await new Promise(b=>setTimeout(b,5e3));continue}let T=await m.json();await C(s,T)}catch(m){if(c.signal.aborted)break;let T=m instanceof Error?m.message:String(m);console.warn(`[claim:${x}] error: ${T} \u2014 backoff 5s`),await new Promise(b=>setTimeout(b,5e3))}}};async function C(x,m){let T={abort:new AbortController,paused:!1};m.role==="chat"&&(T.chatInbox=Pm()),l.set(m.jobId,T);let b=!1,S=null,j=null,w=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),I=async()=>{try{await x.heartbeat(m.jobId)==="claim_lost"&&(b=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(F){let ke=F instanceof Error?F.message:String(F);console.warn(`[job] ${m.jobId} heartbeat error: ${ke}`)}};I();let B=setInterval(()=>{I()},w),K=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(y(m.prompt," \u2502 "));let Re=[],ct=null,E=400,de=25,We=500,Ue=()=>{if(ct&&(clearTimeout(ct),ct=null),Re.length===0)return;let F=Re.splice(0,Re.length),ke=u;if(!ke||ke.readyState!==ke.OPEN)return;let Le={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:F};try{ke.send(JSON.stringify(Le))}catch{}},Un=F=>{Re.push(F),Re.length>We&&Re.shift(),Re.length>=de?Ue():ct||(ct=setTimeout(Ue,E))},lt=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,ee=new Set,Ln=null;try{if(!o){b||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:K,finishedAt:new Date().toISOString()});return}let F=Bc(m.jobId);console.log(`[job] ${m.jobId} workspace=${F.dir}`);let ke=k(m,r);S=ke.gitCreds,j=ke.contextGitCreds;let Le=S?.env,ti=ke.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ke.claudeOauthToken}:void 0,De=[],ir=null,Dn=null;try{let _="worktree";De=await Ac(F.dir,m.projectId,m.projectRepos,_,Le);let O=await _c(F.dir,m.projectId,m.contextRepo,_,Le);Dn=O,ir=O?.workspacePath??null}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} materialize failed: ${O}`),b||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${O}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let ri=async()=>{if(!m.deliveries||m.deliveries.length===0)return[];let _=m.contextRepo?.cloneUrl;if(!_||!Le)throw new Error(_?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let O=[];for(let G of m.deliveries){let H=De.find(fe=>fe.name===G.name);if(H){if(m.role==="implement"&&G.baseSha&&G.baseSha!==H.baseSha){let fe=await jc(H,G.deliveryRef,G.deliverySha,G.baseSha,_,Le);console.log(`[job] ${m.jobId} ${H.name}: base moved ${G.baseSha.slice(0,10)} \u2192 ${H.baseSha.slice(0,10)} \u2014 re-applied delivery ${G.deliverySha.slice(0,10)} (${fe.length} conflicted file(s))`),fe.length>0&&O.push(`- **${H.name}**:`,...fe.map(sr=>` - \`${sr}\``));continue}await Ic(H,G.deliveryRef,G.deliverySha,_,Le),console.log(`[job] ${m.jobId} ${H.name}: checked out delivery ${G.deliverySha.slice(0,10)} for ${m.role}`)}}return O},Bn=[];if(m.role==="build"||m.role==="implement")try{Bn=await ri()}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} delivery checkout failed: ${O}`),b||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${O}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let Gn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},ni="";if(m.role==="resolve-conflict"){if(!De.some(_=>Gn[_.name])){let _="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${m.jobId} ${_}`),b||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}try{let _=[];for(let O of De){let G=Gn[O.name];if(!G)continue;let H=await Eo(O,G,Le);console.log(`[job] ${m.jobId} ${O.name}: merged ${G} into ${O.ref} \u2014 ${H.length} conflicted file(s)`),H.length>0?_.push(`- **${O.name}**:`,...H.map(fe=>` - \`${fe}\``)):_.push(`- **${O.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}ni=`
544
545
 
545
546
  ## Conflicts to resolve
546
547
 
547
548
  `+(_.length>0?_.join(`
548
549
  `):"(no task branches to merge)")+`
549
- `}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} conflict merge failed: ${O}`),b||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${O}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}}let su=Bo.length>0?`
550
+ `}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} conflict merge failed: ${O}`),b||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${O}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}}let uu=Bn.length>0?`
550
551
 
551
552
  ## Base branch moved \u2014 conflicts to resolve
552
553
 
553
554
  The base branch advanced since the previous iteration; its delivery was re-applied on top of the fresh base. These files now contain git conflict markers (\`<<<<<<<\`) \u2014 resolve them (keep both the base branch's changes and this task's changes) as part of this job:
554
555
 
555
- `+Bo.join(`
556
+ `+Bn.join(`
556
557
  `)+`
557
- `:"",au=v($(m.prompt,De,ar),ar,m.taskId)+ti+su,Mo=[...De.map(_=>_.workspacePath),...ar?[ar]:[]];Mo.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${Mo.join(", ")}`),lt&&(Lo=setInterval(()=>{let O=u;if(!O||O.readyState!==O.OPEN)return;let G;try{G=pm(Ir(F.dir,"drafts")).filter(H=>H.endsWith(".json")).sort()}catch{return}for(let H of G){if(ee.has(H))continue;if(ee.size>=fi)break;let de;try{let ce=JSON.parse(En(Ir(F.dir,"drafts",H),"utf-8")),ut=typeof ce.localRef=="string"?ce.localRef:"",D=typeof ce.title=="string"?ce.title:"",oe=typeof ce.body=="string"?ce.body:"";if(!ut||!D)continue;de={localRef:ut,title:D,body:oe,...ce.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ce.links)?{links:ce.links}:{}}}catch{continue}ee.add(H);let cr={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:lt,child:de};try{O.send(JSON.stringify(cr))}catch{}}},1500));try{let _={workspaceDir:F.dir,role:m.role,prompt:au,addDirs:Mo,metadata:m.metadata??{},...m.model?{model:m.model}:{},...Zn?{env:Zn}:{},signal:T.abort.signal,onActivity:Uo},O=T.chatInbox?await n.run({..._,interactive:{inbox:T.chatInbox.iterable}}):await pc(n,_,{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{F.clean();for(let D of De)try{await kc(D);let oe=Go[D.name];m.role==="resolve-conflict"&&oe&&await jn(D,oe,Le)}catch(oe){let lr=oe instanceof Error?oe.message:String(oe);console.warn(`[job] ${m.jobId} worktree reset failed (${D.name}): ${lr}`)}try{await ei()}catch(D){let oe=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${oe}`)}},aborted:()=>b||T.paused}),G=[];if(gm.has(m.role)&&De.length>0){let D=m.metadata??{},oe=typeof D.commitMessage=="string"?D.commitMessage:`${m.taskId}: changes`,lr=m.contextRepo?.cloneUrl,ri=j?.env;if(!lr||!ri)throw new Error("delivery requested but "+(lr?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let cu=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let Be of De){let ur=await $c(Be,oe);if(!ur){console.log(`[job] ${m.jobId} ${Be.name}: no changes \u2014 no delivery`);continue}let Fo=`codepipe/deliveries/${cu}/${m.jobId}/${Be.name}`;await vc(Be,ur,Fo,lr,ri),G.push({name:Be.name,deliveryRef:Fo,deliverySha:ur,baseSha:Be.baseSha}),console.log(`[job] ${m.jobId} ${Be.name}: delivered ${ur.slice(0,10)} \u2192 ${Fo}`);let oi=await xc(Be,ur);if(oi.trim().length>0){let lu=Ir("display",`${Be.name}.diff`),ni=Ir(F.dir,lu);um(fm(ni),{recursive:!0}),dm(ni,oi)}}}if(m.role==="resolve-conflict"&&G.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=Ec(F.dir),console.log(`[job] ${m.jobId} build verdict: ok=${H.ok}`+(H.failedStep?` failedStep=${H.failedStep}`:"")));let de=O.artifactPaths.length>0?O.artifactPaths:F.listFiles(),cr=Array.from(new Set(de)),ce;if(Do)try{let D=await Pc(Do,m.role==="index"?["adr/SOURCES.md"]:[]);D.length>0&&(ce=D,console.log(`[job] ${m.jobId} captured ${D.length} knowledge file(s) for Context Repo`))}catch(D){let oe=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${oe}`)}let ut={jobId:m.jobId,status:"succeeded",artifacts:cr.map(D=>({path:D,contentBase64:En(`${F.dir}/${D}`).toString("base64")})),...ce?{contextWrites:ce}:{},...G.length>0?{deliveries:G}:{},log:hm(O.log),startedAt:K,finishedAt:new Date().toISOString(),usage:O.usage,...O.rateLimit?{rateLimit:O.rateLimit}:{},...H?{build:H}:{}};if(b||T.paused)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${T.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await x.submitResult(ut),console.log(`[job] ${m.jobId} done \u2014 uploaded ${ut.artifacts.length} artifact(s):`);for(let D of ut.artifacts){let oe=Buffer.from(D.contentBase64,"base64").length;console.log(` \xB7 ${D.path} (${oe} bytes)`)}ut.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(_){let O=_ instanceof Error?_.message:String(_);if(T.paused)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(b)console.warn(`[job] ${m.jobId} failed after claim lost (${O}) \u2014 skipping result upload`);else{let G=uc(_);console.warn(G?`[job] ${m.jobId} failed: ${O} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${O}`),await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:K,finishedAt:new Date().toISOString(),...G?{authError:!0}:{}})}}finally{F.dispose()}}finally{clearInterval(B),Lo&&clearInterval(Lo),Ue(),T.chatInbox?.close(),l.delete(m.jobId),S?.cleanup(),j?.cleanup()}}function k(x,m){if(!x.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${x.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let T;try{T=JSON.parse(so(m,x.credBundle).toString("utf-8"))}catch(w){return console.warn(`[job] ${x.jobId} failed to open credBundle: ${w instanceof Error?w.message:String(w)}`),{gitCreds:null,contextGitCreds:null}}let b=Tn(T);b&&console.log(`[job] ${x.jobId} cred bundle opened \u2014 git creds configured`);let S=mc(T,x.contextRepo.cloneUrl),j={gitCreds:b,contextGitCreds:S};return T.claudeOauthToken&&(j.claudeOauthToken=T.claudeOauthToken),j}function y(x,m){return x.split(`
558
+ `:"",pu=v($(m.prompt,De,ir),ir,m.taskId)+ni+uu,Mn=[...De.map(_=>_.workspacePath),...ir?[ir]:[]];Mn.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${Mn.join(", ")}`),lt&&(Ln=setInterval(()=>{let O=u;if(!O||O.readyState!==O.OPEN)return;let G;try{G=Sm(Rr(F.dir,"drafts")).filter(H=>H.endsWith(".json")).sort()}catch{return}for(let H of G){if(ee.has(H))continue;if(ee.size>=gi)break;let fe;try{let le=JSON.parse(_o(Rr(F.dir,"drafts",H),"utf-8")),ut=typeof le.localRef=="string"?le.localRef:"",D=typeof le.title=="string"?le.title:"",ne=typeof le.body=="string"?le.body:"";if(!ut||!D)continue;fe={localRef:ut,title:D,body:ne,...le.isEpic===!0?{isEpic:!0}:{},...Array.isArray(le.links)?{links:le.links}:{}}}catch{continue}ee.add(H);let sr={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:lt,child:fe};try{O.send(JSON.stringify(sr))}catch{}}},1500));try{let _={workspaceDir:F.dir,role:m.role,prompt:pu,addDirs:Mn,metadata:m.metadata??{},...m.model?{model:m.model}:{},...ti?{env:ti}:{},signal:T.abort.signal,onActivity:Un},O=T.chatInbox?await o.run({..._,interactive:{inbox:T.chatInbox.iterable}}):await gc(o,_,{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{F.clean();for(let D of De)try{await Sc(D);let ne=Gn[D.name];m.role==="resolve-conflict"&&ne&&await Eo(D,ne,Le)}catch(ne){let ar=ne instanceof Error?ne.message:String(ne);console.warn(`[job] ${m.jobId} worktree reset failed (${D.name}): ${ar}`)}try{await ri()}catch(D){let ne=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${ne}`)}},aborted:()=>b||T.paused}),G=[];if(Im.has(m.role)&&De.length>0){let D=m.metadata??{},ne=typeof D.commitMessage=="string"?D.commitMessage:`${m.taskId}: changes`,ar=m.contextRepo?.cloneUrl,oi=j?.env;if(!ar||!oi)throw new Error("delivery requested but "+(ar?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let du=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let Be of De){let cr=await Cc(Be,ne);if(!cr){console.log(`[job] ${m.jobId} ${Be.name}: no changes \u2014 no delivery`);continue}let Fn=`codepipe/deliveries/${du}/${m.jobId}/${Be.name}`;await Rc(Be,cr,Fn,ar,oi),G.push({name:Be.name,deliveryRef:Fn,deliverySha:cr,baseSha:Be.baseSha}),console.log(`[job] ${m.jobId} ${Be.name}: delivered ${cr.slice(0,10)} \u2192 ${Fn}`);let ii=await Tc(Be,cr);if(ii.trim().length>0){let fu=Rr("display",`${Be.name}.diff`),si=Rr(F.dir,fu);xm(Rm(si),{recursive:!0}),Cm(si,ii)}}}if(m.role==="resolve-conflict"&&G.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=Nc(F.dir),console.log(`[job] ${m.jobId} build verdict: ok=${H.ok}`+(H.failedStep?` failedStep=${H.failedStep}`:"")));let fe=O.artifactPaths.length>0?O.artifactPaths:F.listFiles(),sr=Array.from(new Set(fe)),le;if(Dn)try{let D=await Oc(Dn,m.role==="index"?["adr/SOURCES.md"]:[]);D.length>0&&(le=D,console.log(`[job] ${m.jobId} captured ${D.length} knowledge file(s) for Context Repo`))}catch(D){let ne=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${ne}`)}let ut={jobId:m.jobId,status:"succeeded",artifacts:sr.map(D=>({path:D,contentBase64:_o(`${F.dir}/${D}`).toString("base64")})),...le?{contextWrites:le}:{},...G.length>0?{deliveries:G}:{},log:jm(O.log),startedAt:K,finishedAt:new Date().toISOString(),usage:O.usage,...O.rateLimit?{rateLimit:O.rateLimit}:{},...H?{build:H}:{}};if(b||T.paused)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${T.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await x.submitResult(ut),console.log(`[job] ${m.jobId} done \u2014 uploaded ${ut.artifacts.length} artifact(s):`);for(let D of ut.artifacts){let ne=Buffer.from(D.contentBase64,"base64").length;console.log(` \xB7 ${D.path} (${ne} bytes)`)}ut.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(_){let O=_ instanceof Error?_.message:String(_);if(T.paused)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(b)console.warn(`[job] ${m.jobId} failed after claim lost (${O}) \u2014 skipping result upload`);else{let G=mc(_);console.warn(G?`[job] ${m.jobId} failed: ${O} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${O}`),await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:K,finishedAt:new Date().toISOString(),...G?{authError:!0}:{}})}}finally{F.dispose()}}finally{clearInterval(B),Ln&&clearInterval(Ln),Ue(),T.chatInbox?.close(),l.delete(m.jobId),S?.cleanup(),j?.cleanup()}}function k(x,m){if(!x.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${x.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let T;try{T=JSON.parse(on(m,x.credBundle).toString("utf-8"))}catch(w){return console.warn(`[job] ${x.jobId} failed to open credBundle: ${w instanceof Error?w.message:String(w)}`),{gitCreds:null,contextGitCreds:null}}let b=jo(T);b&&console.log(`[job] ${x.jobId} cred bundle opened \u2014 git creds configured`);let S=wc(T,x.contextRepo.cloneUrl),j={gitCreds:b,contextGitCreds:S};return T.claudeOauthToken&&(j.claudeOauthToken=T.claudeOauthToken),j}function y(x,m){return x.split(`
558
559
  `).map(T=>m+T).join(`
559
- `)}function $(x,m,T){let b=m[0]?.workspacePath??"";return x.replace(/\{\{codeDir\}\}/g,b).replace(/\{\{codeRoot\}\}/g,b?b.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,T??"")}function v(x,m,T){let b=x,S=T.includes("::")?"":T.split(":",2)[1]??"",j=w=>{if(!m||!S)return"";try{return En(Ir(m,"tasks",S,w),"utf-8").trim()}catch{return""}};if(b.includes("{{solutionMd}}")){let w=j("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";b=b.replace(/\{\{solutionMd\}\}/g,()=>w)}if(b.includes("{{taskDescription}}")){let w=j("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";b=b.replace(/\{\{taskDescription\}\}/g,()=>w)}return b}let N=x=>{if(a)return;a=!0,console.log(`
560
- [${x}] shutting down`),c.abort();let m=[...l.keys()];for(let S of l.values())S.abort.abort();let T=new AbortController,b=setTimeout(()=>T.abort(),3e3);(async()=>(await Promise.all(m.map(async S=>{try{await s.releaseJob(S,`sandbox ${x}`,T.signal),console.log(`[${x}] released job ${S}`)}catch(j){let w=j instanceof Error?j.message:String(j);console.warn(`[${x}] release failed: ${w} (sweeper will reclaim)`)}})),clearTimeout(b),d.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM"));let P=[h("implementation")];e.planningLane!==!1?P.push(h("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(P)}async function Lc(t={profile:void 0}){let e=ge(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=fo(e.hubUrl,e.cliToken),o=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let f=JSON.parse(u);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of o.events)console.log(` ${i}`);o.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await M(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let n=ie(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as Bm}from"node:child_process";import{existsSync as Xt,mkdirSync as rl,readFileSync as ol,readdirSync as Gm,writeFileSync as nl}from"node:fs";import{join as $t,resolve as il}from"node:path";import{setTimeout as Nn}from"node:timers/promises";import{cancel as Mm,confirm as Qt,intro as sl,isCancel as Dn,log as R,outro as Un,password as Zt,select as vt,spinner as al,text as Q}from"@clack/prompts";import{simpleGit as Eo}from"simple-git";async function Jt(t,e,r){return e.host==="github"?bm(t,e,r):e.host==="gitlab"?Rm(t,e,r):Im(t,e,r)}async function Dc(t,e,r={}){let o=r.explain??!0,n=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await it(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await Bc(e.githubToken,t):n}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await nt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await Gc(e.gitlabToken,t):n}}return e.bitbucket?(await Vt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await Mc(e.bitbucket,t):n}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(i){return{found:"unknown",detail:i instanceof Error?i.message:String(i)}}}async function Bc(t,e){let r=!1;try{r=(await it(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 Gc(t,e){let r=!1;try{r=(await nt(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 Mc(t,e){let r=!1;try{r=(await Vt(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}var wm="https://api.github.com";async function it(t,e,r,o){let n={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};o!==void 0&&(n.body=JSON.stringify(o),n.headers["Content-Type"]="application/json");let i=await fetch(wm+r,n),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function bm(t,e,r){let o=r.githubToken;if(!o)throw new Error("GitHub PAT required to provision a github-hosted Context Repo \u2014 set GH_TOKEN / GITHUB_TOKEN or provide it during `codepipe init`");let n=await km(o,e,r),i=await vm(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=Nt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await xm(o,n.owner,n.name,a.path,i)||await Sm(o,n.owner,n.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:n.owner,name:n.name,cloneUrl:n.sshUrl,branch:i}}async function km(t,e,r){let o=await it(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(o.status===200&&o.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:o.data.owner.login,name:o.data.name,sshUrl:o.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await Bc(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await $m(t,e.owner),i=n?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${n?"org":"user"})`);let s=await it(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 $m(t,e){let{status:r,data:o}=await it(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function vm(t,e,r){let{data:o}=await it(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function xm(t,e,r,o,n){let{status:i,data:s}=await it(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function Sm(t,e,r,o,n,i,s,a){let c={message:i,content:Buffer.from(n,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await it(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var Cm="https://gitlab.com/api/v4";async function nt(t,e,r,o){let n={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...o!==void 0?{"Content-Type":"application/json"}:{}}};o!==void 0&&(n.body=JSON.stringify(o));let i=await fetch(Cm+r,n),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Rm(t,e,r){let o=r.gitlabToken;if(!o)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let n=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await nt(o,"GET",`/projects/${n}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Gc(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await nt(o,"GET","/user"),p={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let d=await nt(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(d.status===404||!d.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);p.namespace_id=d.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await nt(o,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Nt(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let g=(await nt(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let d of g)l.add(d.path);if(g.length<100)break}let u=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return u.length>0?await nt(o,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var Tm="https://api.bitbucket.org/2.0";async function Vt(t,e,r,o){let n={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};o?.json!==void 0?(n.body=JSON.stringify(o.json),n.headers["Content-Type"]="application/json"):o?.form&&(n.body=o.form);let i=await fetch(Tm+r,n),s=await i.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(i.status>=400&&i.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${i.status} ${s}`);return{status:i.status,data:a}}async function Im(t,e,r){let o=r.bitbucket;if(!o)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let n=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await Vt(o,"GET",n);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Mc(o,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let f=await Vt(o,"POST",n,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=f.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Nt(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await Vt(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let g of l)f.set(g.path,g.content);if((await Vt(o,"POST",`${n}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let 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 jm={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function we(t){let e=t.trim();if(!e)return null;let r,o;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),o=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),o=a[2]}let n=jm[r];if(!n)return null;let i=o.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:n,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as Pm}from"node:crypto";import{existsSync as Fc,mkdirSync as Em,readFileSync as Hc,readdirSync as Am,rmSync as jo,writeFileSync as _m}from"node:fs";import{homedir as Om}from"node:os";import{dirname as Nm,join as An}from"node:path";var Um=24*60*60*1e3;function Kc(){return An(Om(),".codepipe","init-drafts")}function _n(t){let e=Pm("sha256").update(t).digest("hex").slice(0,16);return An(Kc(),`${e}.json`)}function Wc(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Um)}function qc(t){let e=_n(t);if(!Fc(e))return null;try{let r=JSON.parse(Hc(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Wc(r.savedAt)?(jo(e,{force:!0}),null):r}catch{return null}}function On(t){jo(_n(t),{force:!0})}function Yc(){let t=Kc();if(Fc(t))for(let e of Am(t)){let r=An(t,e);try{let o=JSON.parse(Hc(r,"utf-8"));Wc(o.savedAt)&&jo(r,{force:!0})}catch{jo(r,{force:!0})}}}var zt=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let o=await r();return this.set(e,o),o}clear(){On(this.cwd)}persist(){let e=_n(this.cwd);Em(Nm(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};_m(e,JSON.stringify(r,null,2)+`
561
- `,{mode:384})}};function Vc(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 Jc(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 zc}from"node:fs";import{join as Xc}from"node:path";import{simpleGit as Qc}from"simple-git";var Lm={info:t=>console.log(t),warn:t=>console.warn(t)};async function Pr(t,e,r={}){let o=r.log??Lm,n=[];for(let i of e){let s=Xc(t,i.mountAs),a=yi(i);if(!zc(s)){if(r.dryRun){o.info(`would clone ${a} \u2192 ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{o.info(`cloning ${a} \u2192 ${i.mountAs}/`),await Qc().clone(a,s),n.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let f=u instanceof Error?u.message:String(u);o.warn(`clone failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!zc(Xc(s,".git"))){o.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=Qc(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Dm(l,a)){o.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let f=u instanceof Error?u.message:String(u);o.warn(`fetch failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}}return n}function Dm(t,e){return Zc(t)===Zc(e)}function Zc(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function el(t={}){let e=me();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 Pr(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let o of r)console.log(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}var tl=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function J(t){Mm(t),process.exit(1)}function be(t){return Dn(t)&&J("aborted"),t}function W(t){return Dn(t)&&J("aborted"),typeof t=="string"?t:""}async function cl(t={}){sl("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Yc();let r=qc(e),o,n=!1;r&&Object.keys(r.answers).length>0?be(await Qt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(R.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new zt(e,r),n=!0):(On(e),o=new zt(e)):o=new zt(e);let i=t.force===!0?null:await Bn(e),s=await o.ask("target",async()=>be(await vt({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?R.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):n&&o.get("contextRepo")!==void 0||ul(e,t.force===!0));let c=await o.ask("hubUrl",async()=>W(await Q({message:"HUB URL",placeholder:Te,initialValue:L("HUB_URL")??Te,validate:E=>E.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await o.ask("email",()=>er()),{cliToken:u,accountEmail:f}=await o.ask("bootstrap",()=>tr(c,l)),p=null;s==="farm"&&(p=await Fm(c,u));let g=a?Km(a.parsed.repoName):"",d=await o.ask("projectId",async()=>W(await Q({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:E=>dt.test(E.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await o.ask("projectName",async()=>W(await Q({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 o.ask("automationLevel",async()=>be(await vt({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),k=await o.ask("youtrack",()=>yl()),y=await o.ask("youtrackProjectKey",async()=>W(await Q({message:"YouTrack project key",placeholder:"DEV",validate:E=>E.trim().length>0?void 0:"required"})).trim()),$=await o.ask("youtrackWrites",async()=>be(await Qt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),v=o.get("tokens")??{},N=()=>o.set("tokens",v),P=await o.ask("repos",()=>Vm(v,l,a,{onCred:N,initial:o.get("reposPartial")??[],onProgress:E=>o.set("reposPartial",E)}));o.delete("reposPartial");let x=await Jm(await o.ask("contextRepo",()=>ml(d,P,v,l)),d,P,v,l,N,E=>o.set("contextRepo",E)),{spec:m,mode:T}=x;R.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let b=await o.ask("assigneeLogin",async()=>W(await Q({message:"your YouTrack login (the assignee value)",...k.login?{initialValue:k.login}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),S=await o.ask("claudeToken",()=>rg(s==="farm")),j={projectId:d,name:h,automationLevel:C,repos:P,youtrackProjectKey:y};R.step(`${T==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let w;try{w=await Jt(j,m,{...gl(v),youtrackWrites:$,trackerUrl:k.url,mode:T,log:{info:E=>R.message(E),warn:E=>R.warn(E)}})}catch(E){J(`Context Repo provisioning failed: ${E instanceof Error?E.message:String(E)}`)}j.contextRepo=w,R.success(`Context Repo ready: ${w.owner}/${w.name}@${w.branch}`),R.step(`registering project on ${c}\u2026`);let I;try{I=await tt(c,u,j)}catch(E){if(E instanceof A&&E.status===409){R.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{I=await M(c,u,d)}catch(pe){throw pe instanceof A&&J(`HUB \u2192 ${pe.status} ${pe.message}`),pe}}else if(E instanceof A&&E.status===401)o.delete("cliToken"),J("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(E instanceof A)J(`HUB \u2192 ${E.status} ${E.message}`);else throw E}let B=I.contextRepo??w;R.success(`project ${I.projectId} ready (${I.provisioningStatus})`);let K=await eg(B),Re={url:k.url,token:k.token};if(s==="farm"){let E=p,pe={...v,...K?{contextWrite:K}:{},...S?{claude:{oauthToken:S}}:{},youtrack:Re},We=v.github?.token;if(B.host==="github"&&We)try{let ee=Ba(`devpipe-${d}`);await Ga(B,We,ee.publicKey,`devpipe-${d}`),pe.contextSsh={privateKey:ee.privateKey},R.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ee){R.warn(`could not set up Context Repo SSH deploy key (${ee instanceof Error?ee.message:String(ee)}); the farm will fall back to the token path.`)}let Ue={projectId:d,config:{hubUrl:c,cliToken:u,projectId:d},secrets:pe,contextRepo:B,projectConfig:_e(j,$,k.url,b||void 0)},Uo=He(E.farm.publicKey,JSON.stringify(Ue));R.step(`handing project ${d} to farm ${E.farm.name}\u2026`);let lt;try{lt=await mo(c,u,E.farm.farmId,{projectId:d,sealedBundle:Uo})}catch(ee){throw ee instanceof A&&J(ee.status===409?`farm ${E.farm.name} is offline \u2014 start it and re-run.`:ee.status===504?`farm ${E.farm.name} did not respond in time.`:`HUB \u2192 ${ee.status} ${ee.message}`),ee}lt.ok||J(`farm rejected provisioning: ${lt.error??"unknown error"}`),await Ln(c,u,d,B,We),o.clear(),Un(`done. project ${d} is now hosted on farm ${E.farm.name} (daemon ${lt.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}hl(v),await pl(e,B.cloneUrl,B.branch),fl(e),a&&await qm(e);{let E=$t(e,Pe);_t(E);let pe=_e(j,$,k.url,b||void 0),We=mr(E,pe);We.length>0&&R.success(`local project config \u2192 .codepipe/{${We.join(", ")}}`),gt(d,pe,{info:Ue=>R.message(Ue),warn:Ue=>R.warn(Ue)})}await dl(e,I.repos);let ct={hubUrl:c,cliToken:u,projectId:d,...v,...K?{contextWrite:K}:{},...S?{claude:{oauthToken:S}}:{},youtrack:Re};V(ct),Me({hubUrl:c,cliToken:u,projectId:d,accountEmail:f},d),R.success(`secrets \u2192 ${Ee(d)}`),await Ln(c,u,d,B,v.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),Un("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Ln(t,e,r,o,n){let i=await Jc(o,n),s=Vc(i),a=await vt({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Dn(a)||a!==s.proceedValue))try{let{jobId:c}=await ho(t,e,r,{reindex:s.reindex});R.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){R.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function Fm(t,e){let r;try{r=await ca(t,e)}catch(c){throw c instanceof A&&J(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&J("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let n=be(await vt({message:"target farm",options:o.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=o.find(c=>c.farmId===n),s;try{s=Lt(i.farmId,i.publicKey)}catch(c){J(c instanceof Error?c.message:String(c))}return be(await Qt({message:`confirm farm ${i.name} cred-channel fingerprint:
560
+ `)}function $(x,m,T){let b=m[0]?.workspacePath??"";return x.replace(/\{\{codeDir\}\}/g,b).replace(/\{\{codeRoot\}\}/g,b?b.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,T??"")}function v(x,m,T){let b=x,S=T.includes("::")?"":T.split(":",2)[1]??"",j=w=>{if(!m||!S)return"";try{return _o(Rr(m,"tasks",S,w),"utf-8").trim()}catch{return""}};if(b.includes("{{solutionMd}}")){let w=j("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";b=b.replace(/\{\{solutionMd\}\}/g,()=>w)}if(b.includes("{{taskDescription}}")){let w=j("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";b=b.replace(/\{\{taskDescription\}\}/g,()=>w)}return b}let N=x=>{if(a)return;a=!0,console.log(`
561
+ [${x}] shutting down`),c.abort();let m=[...l.keys()];for(let S of l.values())S.abort.abort();let T=new AbortController,b=setTimeout(()=>T.abort(),3e3);(async()=>(await Promise.all(m.map(async S=>{try{await s.releaseJob(S,`sandbox ${x}`,T.signal),console.log(`[${x}] released job ${S}`)}catch(j){let w=j instanceof Error?j.message:String(j);console.warn(`[${x}] release failed: ${w} (sweeper will reclaim)`)}})),clearTimeout(b),d.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM"));let P=[h("implementation")];e.planningLane!==!1?P.push(h("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(P)}async function Mc(t={profile:void 0}){let e=he(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=fn(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 M(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ie(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 Qm}from"node:child_process";import{existsSync as Jt,mkdirSync as sl,readFileSync as al,readdirSync as Zm,writeFileSync as cl}from"node:fs";import{join as kt,resolve as ll}from"node:path";import{setTimeout as Lo}from"node:timers/promises";import{cancel as eg,confirm as zt,intro as ul,isCancel as Go,log as R,outro as Do,password as Xt,select as $t,spinner as pl,text as Q}from"@clack/prompts";import{simpleGit as En}from"simple-git";async function Yt(t,e,r){return e.host==="github"?Am(t,e,r):e.host==="gitlab"?Bm(t,e,r):Mm(t,e,r)}async function Fc(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 it(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Hc(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 ot(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Kc(e.gitlabToken,t):o}}return e.bitbucket?(await qt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Wc(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 Hc(t,e){let r=!1;try{r=(await it(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 Kc(t,e){let r=!1;try{r=(await ot(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 Wc(t,e){let r=!1;try{r=(await qt(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 Em="https://api.github.com";async function it(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(Em+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 Am(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 _m(n,e,r),i=await Nm(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Ot(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Um(n,o.owner,o.name,a.path,i)||await Lm(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 _m(t,e,r){let n=await it(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 Hc(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Om(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 it(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 Om(t,e){let{status:r,data:n}=await it(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Nm(t,e,r){let{data:n}=await it(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Um(t,e,r,n,o){let{status:i,data:s}=await it(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Lm(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 it(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var Dm="https://gitlab.com/api/v4";async function ot(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(Dm+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 Bm(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 ot(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 Kc(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await ot(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 ot(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 ot(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=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let g=(await ot(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 ot(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 Gm="https://api.bitbucket.org/2.0";async function qt(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(Gm+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 Mm(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 qt(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 Wc(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 qt(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=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await qt(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 qt(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 Fm={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function we(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=Fm[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 Hm}from"node:crypto";import{existsSync as qc,mkdirSync as Km,readFileSync as Yc,readdirSync as Wm,rmSync as jn,writeFileSync as qm}from"node:fs";import{homedir as Ym}from"node:os";import{dirname as Vm,join as Oo}from"node:path";var Jm=24*60*60*1e3;function Vc(){return Oo(Ym(),".codepipe","init-drafts")}function No(t){let e=Hm("sha256").update(t).digest("hex").slice(0,16);return Oo(Vc(),`${e}.json`)}function Jc(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Jm)}function zc(t){let e=No(t);if(!qc(e))return null;try{let r=JSON.parse(Yc(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Jc(r.savedAt)?(jn(e,{force:!0}),null):r}catch{return null}}function Uo(t){jn(No(t),{force:!0})}function Xc(){let t=Vc();if(qc(t))for(let e of Wm(t)){let r=Oo(t,e);try{let n=JSON.parse(Yc(r,"utf-8"));Jc(n.savedAt)&&jn(r,{force:!0})}catch{jn(r,{force:!0})}}}var Vt=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(){Uo(this.cwd)}persist(){let e=No(this.cwd);Km(Vm(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};qm(e,JSON.stringify(r,null,2)+`
562
+ `,{mode:384})}};function Qc(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 Zc(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 el}from"node:fs";import{join as tl}from"node:path";import{simpleGit as rl}from"simple-git";var zm={info:t=>console.log(t),warn:t=>console.warn(t)};async function Ir(t,e,r={}){let n=r.log??zm,o=[];for(let i of e){let s=tl(t,i.mountAs),a=bi(i);if(!el(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 rl().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(!el(tl(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=rl(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Xm(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 Xm(t,e){return nl(t)===nl(e)}function nl(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function ol(t={}){let e=ge();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 Ir(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 il=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function J(t){eg(t),process.exit(1)}function be(t){return Go(t)&&J("aborted"),t}function W(t){return Go(t)&&J("aborted"),typeof t=="string"?t:""}async function dl(t={}){ul("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Xc();let r=zc(e),n,o=!1;r&&Object.keys(r.answers).length>0?be(await zt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(R.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Vt(e,r),o=!0):(Uo(e),n=new Vt(e)):n=new Vt(e);let i=t.force===!0?null:await Mo(e),s=await n.ask("target",async()=>be(await $t({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?R.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||ml(e,t.force===!0));let c=await n.ask("hubUrl",async()=>W(await Q({message:"HUB URL",placeholder:Te,initialValue:L("HUB_URL")??Te,validate:E=>E.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Qt()),{cliToken:u,accountEmail:f}=await n.ask("bootstrap",()=>Zt(c,l)),p=null;s==="farm"&&(p=await tg(c,u));let g=a?ng(a.parsed.repoName):"",d=await n.ask("projectId",async()=>W(await Q({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:E=>dt.test(E.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await n.ask("projectName",async()=>W(await Q({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()=>be(await $t({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),k=await n.ask("youtrack",()=>$l()),y=await n.ask("youtrackProjectKey",async()=>W(await Q({message:"YouTrack project key",placeholder:"DEV",validate:E=>E.trim().length>0?void 0:"required"})).trim()),$=await n.ask("youtrackWrites",async()=>be(await zt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),v=n.get("tokens")??{},N=()=>n.set("tokens",v),P=await n.ask("repos",()=>ag(v,l,a,{onCred:N,initial:n.get("reposPartial")??[],onProgress:E=>n.set("reposPartial",E)}));n.delete("reposPartial");let x=await cg(await n.ask("contextRepo",()=>wl(d,P,v,l)),d,P,v,l,N,E=>n.set("contextRepo",E)),{spec:m,mode:T}=x;R.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let b=await n.ask("assigneeLogin",async()=>W(await Q({message:"your YouTrack login (the assignee value)",...k.login?{initialValue:k.login}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),S=await n.ask("claudeToken",()=>gg(s==="farm")),j={projectId:d,name:h,automationLevel:C,repos:P,youtrackProjectKey:y};R.step(`${T==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let w;try{w=await Yt(j,m,{...bl(v),youtrackWrites:$,trackerUrl:k.url,mode:T,log:{info:E=>R.message(E),warn:E=>R.warn(E)}})}catch(E){J(`Context Repo provisioning failed: ${E instanceof Error?E.message:String(E)}`)}j.contextRepo=w,R.success(`Context Repo ready: ${w.owner}/${w.name}@${w.branch}`),R.step(`registering project on ${c}\u2026`);let I;try{I=await tt(c,u,j)}catch(E){if(E instanceof A&&E.status===409){R.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{I=await M(c,u,d)}catch(de){throw de instanceof A&&J(`HUB \u2192 ${de.status} ${de.message}`),de}}else if(E instanceof A&&E.status===401)n.delete("cliToken"),J("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(E instanceof A)J(`HUB \u2192 ${E.status} ${E.message}`);else throw E}let B=I.contextRepo??w;R.success(`project ${I.projectId} ready (${I.provisioningStatus})`);let K=await fg(B),Re={url:k.url,token:k.token};if(s==="farm"){let E=p,de={...v,...K?{contextWrite:K}:{},...S?{claude:{oauthToken:S}}:{},youtrack:Re},We=v.github?.token;if(B.host==="github"&&We)try{let ee=Ha(`devpipe-${d}`);await Ka(B,We,ee.publicKey,`devpipe-${d}`),de.contextSsh={privateKey:ee.privateKey},R.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ee){R.warn(`could not set up Context Repo SSH deploy key (${ee instanceof Error?ee.message:String(ee)}); the farm will fall back to the token path.`)}let Ue={projectId:d,config:{hubUrl:c,cliToken:u,projectId:d},secrets:de,contextRepo:B,projectConfig:_e(j,$,k.url,b||void 0)},Un=He(E.farm.publicKey,JSON.stringify(Ue));R.step(`handing project ${d} to farm ${E.farm.name}\u2026`);let lt;try{lt=await mn(c,u,E.farm.farmId,{projectId:d,sealedBundle:Un})}catch(ee){throw ee instanceof A&&J(ee.status===409?`farm ${E.farm.name} is offline \u2014 start it and re-run.`:ee.status===504?`farm ${E.farm.name} did not respond in time.`:`HUB \u2192 ${ee.status} ${ee.message}`),ee}lt.ok||J(`farm rejected provisioning: ${lt.error??"unknown error"}`),await Bo(c,u,d,B,We),n.clear(),Do(`done. project ${d} is now hosted on farm ${E.farm.name} (daemon ${lt.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}kl(v),await gl(e,B.cloneUrl,B.branch),yl(e),a&&await ig(e);{let E=kt(e,Pe);At(E);let de=_e(j,$,k.url,b||void 0),We=dr(E,de);We.length>0&&R.success(`local project config \u2192 .codepipe/{${We.join(", ")}}`),gt(d,de,{info:Ue=>R.message(Ue),warn:Ue=>R.warn(Ue)})}await hl(e,I.repos);let ct={hubUrl:c,cliToken:u,projectId:d,...v,...K?{contextWrite:K}:{},...S?{claude:{oauthToken:S}}:{},youtrack:Re};V(ct),Me({hubUrl:c,cliToken:u,projectId:d,accountEmail:f},d),R.success(`secrets \u2192 ${Ee(d)}`),await Bo(c,u,d,B,v.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),n.clear(),Do("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Bo(t,e,r,n,o){let i=await Zc(n,o),s=Qc(i),a=await $t({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Go(a)||a!==s.proceedValue))try{let{jobId:c}=await hn(t,e,r,{reindex:s.reindex});R.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){R.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function tg(t,e){let r;try{r=await ua(t,e)}catch(c){throw c instanceof A&&J(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&J("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=be(await $t({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=dn(i.farmId,i.publicKey)}catch(c){J(c instanceof Error?c.message:String(c))}return be(await zt({message:`confirm farm ${i.name} cred-channel fingerprint:
562
563
  ${s}
563
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||J("farm fingerprint not confirmed \u2014 aborting."),yt(i.farmId,s),{farm:i,fingerprint:s}}async function ll(t){sl(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();ul(e,t.force===!0);let r=W(await Q({message:"HUB URL",initialValue:L("HUB_URL")??Te,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await er(),{cliToken:n,accountEmail:i}=await tr(r,o);R.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await M(r,n,t.projectId)}catch(f){throw f instanceof A&&J(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||J(`project ${t.projectId} has no Context Repo on HUB`);let a=await yl(),c={},l=new Set(s.repos.map(f=>f.host));l.add(s.contextRepo.host);for(let f of l)await Po(f,c,f===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===f)?.owner,o);hl(c),await pl(e,s.contextRepo.cloneUrl,s.contextRepo.branch),fl(e);{let f=$t(e,Pe);_t(f);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=_e(p,!0,a.url),d=mr(f,g);d.length>0&&R.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),gt(t.projectId,g,{info:h=>R.message(h),warn:h=>R.warn(h)})}await dl(e,s.repos);let u={hubUrl:r,cliToken:n,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};V(u),Me({hubUrl:r,cliToken:n,projectId:t.projectId,accountEmail:i},t.projectId),R.success(`secrets \u2192 ${Ee(t.projectId)}`),await Ln(r,n,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Un("done.")}function ul(t,e){if(!Xt(t)){rl(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=Gm(t).filter(n=>!r.has(n));o.length!==0&&(e||J(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function Bn(t){if(!Xt($t(t,".git")))return null;try{let r=(await Eo(t).remote(["get-url","origin"])||"").toString().trim(),o=r?we(r):null;return o?{parsed:o,defaultBranch:await Hm(t)}:null}catch{return null}}async function Hm(t){let e=Eo(t);try{let o=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(o)return o}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function Km(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return dt.test(e)?e:""}function Wm(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function qm(t){let e=$t(t,".gitignore"),r=Xt(e)?ol(e,"utf-8"):"";if(Wm(r))return;if(!be(await Qt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){R.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let n=r.length===0||r.endsWith(`
564
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||J("farm fingerprint not confirmed \u2014 aborting."),pn(i.farmId,s),{farm:i,fingerprint:s}}async function fl(t){ul(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();ml(e,t.force===!0);let r=W(await Q({message:"HUB URL",initialValue:L("HUB_URL")??Te,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Qt(),{cliToken:o,accountEmail:i}=await Zt(r,n);R.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await M(r,o,t.projectId)}catch(f){throw f instanceof A&&J(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||J(`project ${t.projectId} has no Context Repo on HUB`);let a=await $l(),c={},l=new Set(s.repos.map(f=>f.host));l.add(s.contextRepo.host);for(let f of l)await Pn(f,c,f===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===f)?.owner,n);kl(c),await gl(e,s.contextRepo.cloneUrl,s.contextRepo.branch),yl(e);{let f=kt(e,Pe);At(f);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=_e(p,!0,a.url),d=dr(f,g);d.length>0&&R.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),gt(t.projectId,g,{info:h=>R.message(h),warn:h=>R.warn(h)})}await hl(e,s.repos);let u={hubUrl:r,cliToken:o,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};V(u),Me({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),R.success(`secrets \u2192 ${Ee(t.projectId)}`),await Bo(r,o,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Do("done.")}function ml(t,e){if(!Jt(t)){sl(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=Zm(t).filter(o=>!r.has(o));n.length!==0&&(e||J(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Mo(t){if(!Jt(kt(t,".git")))return null;try{let r=(await En(t).remote(["get-url","origin"])||"").toString().trim(),n=r?we(r):null;return n?{parsed:n,defaultBranch:await rg(t)}:null}catch{return null}}async function rg(t){let e=En(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 ng(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return dt.test(e)?e:""}function og(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function ig(t){let e=kt(t,".gitignore"),r=Jt(e)?al(e,"utf-8"):"";if(og(r))return;if(!be(await zt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){R.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
564
565
  `)?"":`
565
- `;nl(e,r+n+`
566
+ `;cl(e,r+o+`
566
567
  # codepipe workspace (added by \`codepipe init\`)
567
568
  .codepipe/
568
- `),R.success(`.codepipe/ added to ${il(e)}`)}function Ym(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let o=Bm(e,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}catch{}}async function er(){let t="";try{t=(await Eo().raw(["config","--global","user.email"])||"").trim()}catch{}return W(await Q({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function tr(t,e){R.step(`connecting account ${e}`);let r;try{r=await fa(t,e)}catch(s){throw s instanceof vr&&J(`${e} is not authorized on this HUB yet.
569
+ `),R.success(`.codepipe/ added to ${ll(e)}`)}function sg(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Qm(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function Qt(){let t="";try{t=(await En().raw(["config","--global","user.email"])||"").trim()}catch{}return W(await Q({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Zt(t,e){R.step(`connecting account ${e}`);let r;try{r=await ga(t,e)}catch(s){throw s instanceof kr&&J(`${e} is not authorized on this HUB yet.
569
570
  Sign up at ${t} (registration form on the login screen),
570
571
  wait for the operator to approve it by email, then re-run
571
- \`codepipe init\` with the same email.`),s}r.accountCreated&&R.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&R.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Ym(r.authorizeUrl),R.message(`a browser tab was opened to confirm this CLI:
572
+ \`codepipe init\` with the same email.`),s}r.accountCreated&&R.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&R.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(sg(r.authorizeUrl),R.message(`a browser tab was opened to confirm this CLI:
572
573
  ${r.authorizeUrl}
573
574
  `+(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
574
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&R.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),R.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let o=!1,n=Date.now(),i=n+15*6e4;for(;Date.now()<i;){let s;try{s=await ma(t,r.requestId)}catch(a){R.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Nn(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&R.message(`connected as ${a} (the account confirmed in the browser).`),R.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&J("the HUB rejected this account"),s.status==="expired"&&J("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){o||(o=!0,i=n+24*60*6e4,R.message(`email confirmed. waiting for the operator to approve your account\u2026
575
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Nn(5e3);continue}await Nn(2e3)}J("bootstrap timed out")}async function pl(t,e,r){let o=$t(t,Pe);if(Xt($t(o,".git"))){R.message(`${o} already cloned \u2014 skipping`);return}Xt(o)&&J(`${o} exists but is not a git repo \u2014 remove it and re-run`),rl(o,{recursive:!0}),R.step(`cloning Context Repo \u2192 ${o}`);try{await Eo().clone(e,o,["--branch",r]),R.success(`cloned ${e}`)}catch(n){J(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function dl(t,e){if(e.length===0)return;R.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(n=>({name:n.name,host:n.host,owner:n.owner,repoName:n.repoName,defaultBranch:n.defaultBranch??"main",mountAs:n.mountAs??n.name})),o=await Pr(t,r,{log:{info:n=>R.message(n),warn:n=>R.warn(n)}});for(let n of o)R.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function fl(t){let e=$t(t,Pe,".gitignore"),r="";if(Xt(e)&&(r=ol(e,"utf-8")),tl.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
575
+ otherwise use the emailed link the page offers.`))),r.approvalRequired&&R.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),R.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 ha(t,r.requestId)}catch(a){R.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&&R.message(`connected as ${a} (the account confirmed in the browser).`),R.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&J("the HUB rejected this account"),s.status==="expired"&&J("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,R.message(`email confirmed. waiting for the operator to approve your account\u2026
576
+ (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)}J("bootstrap timed out")}async function gl(t,e,r){let n=kt(t,Pe);if(Jt(kt(n,".git"))){R.message(`${n} already cloned \u2014 skipping`);return}Jt(n)&&J(`${n} exists but is not a git repo \u2014 remove it and re-run`),sl(n,{recursive:!0}),R.step(`cloning Context Repo \u2192 ${n}`);try{await En().clone(e,n,["--branch",r]),R.success(`cloned ${e}`)}catch(o){J(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function hl(t,e){if(e.length===0)return;R.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 Ir(t,r,{log:{info:o=>R.message(o),warn:o=>R.warn(o)}});for(let o of n)R.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function yl(t){let e=kt(t,Pe,".gitignore"),r="";if(Jt(e)&&(r=al(e,"utf-8")),il.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
576
577
  `)||r.length===0?"":`
577
- `,i=tl.join(`
578
+ `,i=il.join(`
578
579
  `)+`
579
- `;nl(e,r+n+(r?`
580
- `:"")+i),R.message(`appended runtime entries to ${il(e)}`)}async function Vm(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;R.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Po(s.host,t,s.owner,e),i?.();let c=W(await Q({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=W(await Q({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();n.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),o.onProgress?.(n)}for(;be(await Qt({message:n.length===0?"Add a project repository?":"Want to add another repository?",initialValue:n.length===0}));){let a=W(await Q({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||we(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=we(a);R.message(`${c.host}: ${c.owner}/${c.repoName}`),await Po(c.host,t,c.owner,e),i?.();let l=W(await Q({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=W(await Q({message:"default branch (optional)",placeholder:"main"})).trim(),f=W(await Q({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),p={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(p.defaultBranch=u),f&&f!==l&&(p.mountAs=f),n.push(p),o.onProgress?.(n)}return n}async function ml(t,e,r,o){R.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let n=be(await vt({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));n==="attach"&&R.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=W(await Q({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Ge(t),validate:u=>{let f=(u??"").trim();if(!f)return"required";if(!we(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=we(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await zm(),l=W(await Q({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=W(await Q({message:"Context Repo name",placeholder:Ge(t),initialValue:Ge(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:n}}function gl(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??jt()}}async function Jm(t,e,r,o,n,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Po(c.host,o,c.owner,n),i?.();let u=al();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await Dc(c,gl(o),{explain:l==="attach"});if(f.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(f.detail,1);let p=be(await vt({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"&&J("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await ml(e,r,o,n),s(a)}}async function zm(){return be(await vt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Er(t,e){let r=al();r.start(`verifying ${t}\u2026`);try{let o=await e();return r.stop(`${t} OK \u2014 ${o}`),!0}catch(o){return r.stop(`${t} failed \u2014 ${o instanceof Error?o.message:String(o)}`,1),!1}}function hl(t){br(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),kr(t.gitlab?.token??process.env.GITLAB_TOKEN),$r(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Po(t,e,r,o){if(!e[t])if(t==="github"){let n=await Xm(r);n?e.github=n:R.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await Qm(r,o);n?e.bitbucket=n:R.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let n=await Zm();n?e.gitlab=n:R.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Xm(t){for(;;){let e=W(await Zt({message:`GitHub PAT \u2014 blank to skip
580
+ `;cl(e,r+o+(r?`
581
+ `:"")+i),R.message(`appended runtime entries to ${ll(e)}`)}async function ag(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;R.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Pn(s.host,t,s.owner,e),i?.();let c=W(await Q({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=W(await Q({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(;be(await zt({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=W(await Q({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||we(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=we(a);R.message(`${c.host}: ${c.owner}/${c.repoName}`),await Pn(c.host,t,c.owner,e),i?.();let l=W(await Q({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=W(await Q({message:"default branch (optional)",placeholder:"main"})).trim(),f=W(await Q({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 wl(t,e,r,n){R.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=be(await $t({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"&&R.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=W(await Q({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Ge(t),validate:u=>{let f=(u??"").trim();if(!f)return"required";if(!we(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=we(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await lg(),l=W(await Q({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=W(await Q({message:"Context Repo name",placeholder:Ge(t),initialValue:Ge(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function bl(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??It()}}async function cg(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Pn(c.host,n,c.owner,o),i?.();let u=pl();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await Fc(c,bl(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=be(await $t({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"&&J("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await wl(e,r,n,o),s(a)}}async function lg(){return be(await $t({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function jr(t,e){let r=pl();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 kl(t){yr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),wr(t.gitlab?.token??process.env.GITLAB_TOKEN),br(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Pn(t,e,r,n){if(!e[t])if(t==="github"){let o=await ug(r);o?e.github=o:R.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let o=await pg(r,n);o?e.bitbucket=o:R.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 dg();o?e.gitlab=o:R.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function ug(t){for(;;){let e=W(await Xt({message:`GitHub PAT \u2014 blank to skip
581
582
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
582
583
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
583
584
  if org: approve token in org Settings \u2192 Personal access tokens.
584
585
  (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
585
- set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Er("GitHub",()=>ze(e,t?{owner:t}:void 0)))return{token:e};R.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Qm(t,e){for(R.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
586
+ set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await jr("GitHub",()=>ze(e,t?{owner:t}:void 0)))return{token:e};R.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function pg(t,e){for(R.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
586
587
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
587
588
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
588
589
  read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
589
590
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
590
- The token is shown ONCE \u2014 copy it right away.`);;){let r=W(await Q({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:n=>!n||!n.trim()||n.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let o=W(await Zt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){R.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Er("Bitbucket",()=>Xe(r,o,t)))return{email:r,apiToken:o};R.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Zm(){for(;;){let t=W(await Zt({message:`GitLab PAT \u2014 blank to skip
591
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Er("GitLab",()=>Qe(t))){let e=await rs(t);return e&&R.warn(e),{token:t}}R.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function eg(t){if(be(await Qt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
591
+ The token is shown ONCE \u2014 copy it right away.`);;){let r=W(await Q({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=W(await Xt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!n){R.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await jr("Bitbucket",()=>Xe(r,n,t)))return{email:r,apiToken:n};R.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function dg(){for(;;){let t=W(await Xt({message:`GitLab PAT \u2014 blank to skip
592
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await jr("GitLab",()=>Qe(t))){let e=await os(t);return e&&R.warn(e),{token:t}}R.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function fg(t){if(be(await zt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
592
593
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
593
594
  credential. A scoped token hardens setups where the SANDBOX runs outside
594
595
  your trusted network.`,initialValue:!1})))for(t.host==="github"?R.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
595
596
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
596
597
  required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):R.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
597
- (${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=W(await Zt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Er("contextWrite",()=>tg(r,t)))return{token:r};R.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function tg(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(o.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let n=await o.json();if(n.permissions&&n.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return n.full_name??`${e.owner}/${e.name}`}async function rg(t){if(qo()?.claude?.oauthToken&&!t)return R.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`)."),"";R.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?`
598
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=W(await Zt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||R.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):(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 yl(){for(;;){let t=W(await Q({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let o=r.trim();if(!o)return"required";if(!o.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=W(await Zt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Er("YouTrack",()=>et({baseUrl:t,token:e}))){let r=await As({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}R.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as og}from"node:fs";function Z(t){throw new Error(t)}function re(t,e){return(typeof t!="string"||t.trim().length===0)&&Z(`config: '${e}' must be a non-empty string`),t.trim()}function Ar(t,e){if(t==null)return;typeof t!="string"&&Z(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function ng(t){(!t||typeof t!="object")&&Z("config: expected a JSON object");let e=t,r=re(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Z("config: 'hubUrl' must start with http(s)://");let o=re(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&Z("config: 'project' is required");let i=n,s=re(i.id,"project.id");dt.test(s)||Z("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=re(i.name,"project.name"),c=re(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Z("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Z("config: 'project.repos' must be an array");let u=l.map((y,$)=>{(!y||typeof y!="object")&&Z(`config: project.repos[${$}] must be an object`);let v=y,N=re(v.host,`project.repos[${$}].host`);N!=="github"&&N!=="bitbucket"&&N!=="gitlab"&&Z(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let P={name:re(v.name,`project.repos[${$}].name`),host:N,owner:re(v.owner,`project.repos[${$}].owner`),repoName:re(v.repoName,`project.repos[${$}].repoName`)},x=Ar(v.defaultBranch,`project.repos[${$}].defaultBranch`);x&&(P.defaultBranch=x);let m=Ar(v.mountAs,`project.repos[${$}].mountAs`);return m&&(P.mountAs=m),P}),f=i.contextRepo;(!f||typeof f!="object")&&Z("config: 'project.contextRepo' is required");let p=f,g=Ar(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&Z("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:g,owner:re(p.owner,"project.contextRepo.owner"),name:Ar(p.name,"project.contextRepo.name")??Ge(s)},h={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:d}},C=Ar(i.youtrackProjectKey,"project.youtrackProjectKey");C&&(h.project.youtrackProjectKey=C),i.index!==void 0&&(typeof i.index!="boolean"&&Z("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Z("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites);let k=e.secrets;if(k!==void 0){(typeof k!="object"||k===null)&&Z("config: 'secrets' must be an object");let y=k,$={};if(y.github){let v=y.github;$.github={token:re(v.token,"secrets.github.token")}}if(y.bitbucket){let v=y.bitbucket;$.bitbucket={email:re(v.email,"secrets.bitbucket.email"),apiToken:re(v.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let v=y.gitlab;$.gitlab={token:re(v.token,"secrets.gitlab.token")}}if(y.youtrack){let v=y.youtrack;$.youtrack={url:re(v.url,"secrets.youtrack.url").replace(/\/$/,""),token:re(v.token,"secrets.youtrack.token")}}if(y.contextWrite){let v=y.contextWrite;$.contextWrite={token:re(v.token,"secrets.contextWrite.token")}}h.secrets=$}return h}async function ig(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function sg(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await ze(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${o}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(n=>n.host==="bitbucket")?.owner,o=await Xe(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await Qe(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await et({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function wl(t){let e=!t.configPath||t.configPath==="-"?await ig():og(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){Z(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let o=ng(r),{hubUrl:n,cliToken:i,project:s}=o;console.log(`codepipe init --headless \u2192 ${n} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await sg(o));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Jt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??jt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:p=>console.log(` ${p}`),warn:p=>console.warn(` ${p}`)}})}catch(p){Z(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${n}\u2026`);let u;try{u=await tt(n,i,a)}catch(p){if(p instanceof A&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await M(n,i,s.id);else if(p instanceof A)Z(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(V(f),Me({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ee(s.id)}`),gt(s.id,_e(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await ho(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${p}); runs once a SANDBOX claims it.`)}catch(p){console.warn(`could not enqueue index job: ${p instanceof Error?p.message:String(p)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as bl,intro as kl,isCancel as $l,log as Gn,outro as ag,password as vl}from"@clack/prompts";async function cg(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function xl(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await cg(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){kl("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Gn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await vl({message:"Claude OAuth token"});$l(i)&&(bl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),_i({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Jr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=ge(t.profile);if(!e){kl(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Gn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await vl({message:"Claude OAuth token"});$l(i)&&(bl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=U(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},V(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Gn.success("Claude OAuth token saved."),ag("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as lg,confirm as ug,intro as pg,isCancel as Sl,log as se,outro as dg,select as Cl,text as st}from"@clack/prompts";function Rl(t){lg(t),process.exit(1)}function rr(t){return Sl(t)&&Rl("aborted"),t}function _r(t){return Sl(t)&&Rl("aborted"),typeof t=="string"?t:""}async function fg(t,e){let r=rr(await Cl({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),o=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",n=_r(await st({message:"Context Repo owner (org / group / workspace / user)",placeholder:o||"your-org",initialValue:o,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=_r(await st({message:"Context Repo name",placeholder:Ge(t),initialValue:Ge(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function Tl(t={profile:void 0}){let e=ge(t.profile);pg(`codepipe project add \u2192 ${e.hubUrl}`);let r=rr(await st({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>dt.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=rr(await st({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),n=rr(await Cl({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=rr(await st({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=rr(await ug({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=_r(await st({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:k=>!k||!k.trim()||we(k)?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=we(p);se.message(`${g.host}: ${g.owner}/${g.repoName}`);let d=_r(await st({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:k=>k.trim().length>0?void 0:"required"})).trim(),h=_r(await st({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:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let l=await fg(r,a),u=U(e.projectId);se.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??jt(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>se.message(p),warn:p=>se.warn(p)}})}catch(p){se.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=f,se.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await tt(e.hubUrl,e.cliToken,c);se.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),gt(r,_e(c,s,u?.youtrack?.url),{info:g=>se.message(g),warn:g=>se.warn(g)}),p.contextRepo&&(se.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),se.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&se.error(` error: ${p.provisioningError}`),dg("done")}catch(p){p instanceof A?(se.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&se.message(JSON.stringify(p.payload,null,2))):se.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{existsSync as mg,rmSync as gg}from"node:fs";import{confirm as hg,intro as yg,isCancel as wg,log as at,outro as bg,spinner as kg}from"@clack/prompts";function Ne(t){at.error(t),process.exit(1)}var Il=t=>t.trim().replace(/\/+$/,"");async function jl(t){yg("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??me()?.spec.projectId??void 0;e||Ne("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=$e(e);r||Ne(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let o=Il(r.hubUrl),n=r.projectId,i=Il(t.hub);i.startsWith("http")||Ne("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??n,c=s===e;c&&a===n&&i===o&&Ne(`profile '${e}' is already on ${o} \u2014 nothing to move.`);let l;{let k=kg();k.start(`reading project ${n} from ${o}\u2026`);try{l=await M(o,r.cliToken,n),k.stop(`read project ${n} (${l.name})`)}catch(y){throw k.stop("could not read the source project",1),y instanceof A&&Ne(`source HUB ${o} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||Ne(`project ${n} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=U(n),f=(t.account??r.accountEmail??await er()).trim().toLowerCase();if(at.message(`move project '${n}'
599
- from : ${o} (profile ${e})
598
+ (${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=W(await Xt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await jr("contextWrite",()=>mg(r,t)))return{token:r};R.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function mg(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 gg(t){if(qn()?.claude?.oauthToken&&!t)return R.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`)."),"";R.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?`
599
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=W(await Xt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||R.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):(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 $l(){for(;;){let t=W(await Q({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=W(await Xt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await jr("YouTrack",()=>et({baseUrl:t,token:e}))){let r=await Os({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}R.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as hg}from"node:fs";function Z(t){throw new Error(t)}function re(t,e){return(typeof t!="string"||t.trim().length===0)&&Z(`config: '${e}' must be a non-empty string`),t.trim()}function Pr(t,e){if(t==null)return;typeof t!="string"&&Z(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function yg(t){(!t||typeof t!="object")&&Z("config: expected a JSON object");let e=t,r=re(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Z("config: 'hubUrl' must start with http(s)://");let n=re(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&Z("config: 'project' is required");let i=o,s=re(i.id,"project.id");dt.test(s)||Z("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=re(i.name,"project.name"),c=re(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Z("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Z("config: 'project.repos' must be an array");let u=l.map((y,$)=>{(!y||typeof y!="object")&&Z(`config: project.repos[${$}] must be an object`);let v=y,N=re(v.host,`project.repos[${$}].host`);N!=="github"&&N!=="bitbucket"&&N!=="gitlab"&&Z(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let P={name:re(v.name,`project.repos[${$}].name`),host:N,owner:re(v.owner,`project.repos[${$}].owner`),repoName:re(v.repoName,`project.repos[${$}].repoName`)},x=Pr(v.defaultBranch,`project.repos[${$}].defaultBranch`);x&&(P.defaultBranch=x);let m=Pr(v.mountAs,`project.repos[${$}].mountAs`);return m&&(P.mountAs=m),P}),f=i.contextRepo;(!f||typeof f!="object")&&Z("config: 'project.contextRepo' is required");let p=f,g=Pr(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&Z("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:g,owner:re(p.owner,"project.contextRepo.owner"),name:Pr(p.name,"project.contextRepo.name")??Ge(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:d}},C=Pr(i.youtrackProjectKey,"project.youtrackProjectKey");C&&(h.project.youtrackProjectKey=C),i.index!==void 0&&(typeof i.index!="boolean"&&Z("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Z("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites);let k=e.secrets;if(k!==void 0){(typeof k!="object"||k===null)&&Z("config: 'secrets' must be an object");let y=k,$={};if(y.github){let v=y.github;$.github={token:re(v.token,"secrets.github.token")}}if(y.bitbucket){let v=y.bitbucket;$.bitbucket={email:re(v.email,"secrets.bitbucket.email"),apiToken:re(v.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let v=y.gitlab;$.gitlab={token:re(v.token,"secrets.gitlab.token")}}if(y.youtrack){let v=y.youtrack;$.youtrack={url:re(v.url,"secrets.youtrack.url").replace(/\/$/,""),token:re(v.token,"secrets.youtrack.token")}}if(y.contextWrite){let v=y.contextWrite;$.contextWrite={token:re(v.token,"secrets.contextWrite.token")}}h.secrets=$}return h}async function wg(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function bg(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await ze(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 Xe(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await Qe(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await et({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function vl(t){let e=!t.configPath||t.configPath==="-"?await wg():hg(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){Z(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let n=yg(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 bg(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 Yt(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??It(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:p=>console.log(` ${p}`),warn:p=>console.warn(` ${p}`)}})}catch(p){Z(`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 tt(o,i,a)}catch(p){if(p instanceof A&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await M(o,i,s.id);else if(p instanceof A)Z(`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(V(f),Me({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ee(s.id)}`),gt(s.id,_e(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 hn(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 xl,intro as Sl,isCancel as Cl,log as Fo,outro as kg,password as Rl}from"@clack/prompts";async function $g(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Tl(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await $g(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Sl("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Fo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Rl({message:"Claude OAuth token"});Cl(i)&&(xl("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 ${Yr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=he(t.profile);if(!e){Sl(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Fo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Rl({message:"Claude OAuth token"});Cl(i)&&(xl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=U(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},V(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Fo.success("Claude OAuth token saved."),kg("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as vg,confirm as xg,intro as Sg,isCancel as Il,log as se,outro as Cg,select as jl,text as st}from"@clack/prompts";function Pl(t){vg(t),process.exit(1)}function er(t){return Il(t)&&Pl("aborted"),t}function Er(t){return Il(t)&&Pl("aborted"),typeof t=="string"?t:""}async function Rg(t,e){let r=er(await jl({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=Er(await st({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=Er(await st({message:"Context Repo name",placeholder:Ge(t),initialValue:Ge(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function El(t={profile:void 0}){let e=he(t.profile);Sg(`codepipe project add \u2192 ${e.hubUrl}`);let r=er(await st({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>dt.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=er(await st({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),o=er(await jl({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=er(await st({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=er(await xg({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=Er(await st({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:k=>!k||!k.trim()||we(k)?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=we(p);se.message(`${g.host}: ${g.owner}/${g.repoName}`);let d=Er(await st({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:k=>k.trim().length>0?void 0:"required"})).trim(),h=Er(await st({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 Rg(r,a),u=U(e.projectId);se.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Yt(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??It(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>se.message(p),warn:p=>se.warn(p)}})}catch(p){se.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=f,se.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await tt(e.hubUrl,e.cliToken,c);se.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),gt(r,_e(c,s,u?.youtrack?.url),{info:g=>se.message(g),warn:g=>se.warn(g)}),p.contextRepo&&(se.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),se.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&se.error(` error: ${p.provisioningError}`),Cg("done")}catch(p){p instanceof A?(se.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&se.message(JSON.stringify(p.payload,null,2))):se.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{existsSync as Tg,rmSync as Ig}from"node:fs";import{confirm as jg,intro as Pg,isCancel as Eg,log as at,outro as Ag,spinner as _g}from"@clack/prompts";function Ne(t){at.error(t),process.exit(1)}var Al=t=>t.trim().replace(/\/+$/,"");async function _l(t){Pg("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ge()?.spec.projectId??void 0;e||Ne("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=$e(e);r||Ne(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Al(r.hubUrl),o=r.projectId,i=Al(t.hub);i.startsWith("http")||Ne("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Ne(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let k=_g();k.start(`reading project ${o} from ${n}\u2026`);try{l=await M(n,r.cliToken,o),k.stop(`read project ${o} (${l.name})`)}catch(y){throw k.stop("could not read the source project",1),y instanceof A&&Ne(`source HUB ${n} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||Ne(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=U(o),f=(t.account??r.accountEmail??await Qt()).trim().toLowerCase();if(at.message(`move project '${o}'
600
+ from : ${n} (profile ${e})
600
601
  to : ${i} (profile ${s}, project ${a}, account ${f})
601
602
  \u2022 the source registration on the old HUB is left intact (non-destructive)
602
603
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
603
- `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${o}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${o}`)),!t.yes){let k=await hg({message:"Continue?",initialValue:!0});(wg(k)||!k)&&Ne("aborted")}!c&&a===n&&at.warn(`source and destination share the same project id, so they share one secrets file (${Ee(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:p,accountEmail:g}=await tr(i,f),d={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:g,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};at.step(`registering project on ${i}\u2026`);let h;try{h=await tt(i,p,d)}catch(k){if(k instanceof A&&k.status===409){at.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await M(i,p,a)}catch(y){throw y instanceof A&&Ne(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if(k instanceof A&&k.status===403)Ne(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(k instanceof A)Ne(`target HUB \u2192 ${k.status} ${k.message}`);else throw k}at.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),Me({hubUrl:i,cliToken:p,projectId:a,accountEmail:g},s);let C={...u??{},hubUrl:i,cliToken:p,projectId:a};if(delete C.sandboxPins,V(C),at.success(`profile '${s}' \u2192 ${Ee(a)}`),c){let k=Ce(s);mg(k)&&(gg(k),at.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}bg(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as Mn,rmSync as $g,statSync as vg}from"node:fs";import{join as Ao,relative as xg,resolve as Sg}from"node:path";import{cancel as Cg,intro as El,isCancel as Rg,log as z,outro as Al,text as xt}from"@clack/prompts";import{simpleGit as _l}from"simple-git";function le(t){Cg(t),process.exit(1)}function St(t){return Rg(t)&&le("aborted"),typeof t=="string"?t:""}async function Pl(t){try{let e=await _l(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function Tg(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function Ig(t,e){let r=U(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(Tg(r,e)){z.message(`reusing existing ${e} credentials`);return}if(z.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let o=St(await xt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),n=St(await xt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:o,apiToken:n}}else{let o=St(await xt({message:`${e} access token (read access to the repo)`,validate:n=>n.trim()?void 0:"required"})).trim();e==="github"?r.github={token:o}:r.gitlab={token:o}}V(r),z.success(`saved ${e} credentials`)}async function Ol(t){let e=ge(t.profile);El(`codepipe repo add \u2192 project ${e.projectId}`);let r=me()??void 0,o;try{o=(await M(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){le(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let n=t.target?.trim();if(!n){let y=await Pl(process.cwd());y?(n=process.cwd(),z.message(`using the current directory (${y})`)):n=St(await xt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:$=>$.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Mn(n)&&vg(n).isDirectory()){i=Sg(n);let y=await Pl(i);y||le(`${i} is not a git repository (no origin remote)`);let $=we(y);$||le(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=y,z.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let y=we(n);y||le(`"${n}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,s=n,z.message(`${a}: ${c}/${l}`)}let u=St(await xt({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:y=>y.trim()?void 0:"required"})).trim();o.some(y=>y.name===u)&&le(`a repo named "${u}" is already registered`);let f=St(await xt({message:"default branch (optional)",placeholder:"main"})).trim(),p=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let y=xg(r.root,i);p=y===""?".":y}let g=St(await xt({message:"mount_as (directory relative to the workspace root)",placeholder:p,initialValue:p})).trim()||p;o.some(y=>(y.mountAs??y.name)===g)&&le(`mount_as "${g}" is already used by another repo`),await Ig(e,a);let d={name:u,host:a,owner:c,repoName:l,mountAs:g,...f?{defaultBranch:f}:{}};if(!i){let y=r?Ao(r.root,g):ve(e.projectId,u);if(Mn(Ao(y,".git")))z.message(`already cloned at ${y}`);else{z.info(`cloning ${s} \u2192 ${y} \u2026`);try{await _l().clone(s,y),z.success(`cloned into ${y}`)}catch($){le(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
604
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await $a(e.hubUrl,e.cliToken,e.projectId,d)}catch(y){y instanceof A&&le(`HUB \u2192 ${y.status} ${y.message}`),le(y instanceof Error?y.message:String(y))}let{updated:C,errors:k}=gr(e.projectId,h.repos,r?.contextDir);for(let y of C)z.message(`updated ${y}`);for(let y of k)z.warn(`could not update ${y.path}: ${y.error}`);z.success(`added "${u}" \u2014 project now has ${h.repos.length} repo(s)`),Al("done")}async function Nl(t){let e=ge(t.profile);El(`codepipe repo remove \u2192 project ${e.projectId}`);let r=me()??void 0,o;try{let c=(await M(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);o=c?c.mountAs??c.name:void 0}catch{}let n;try{n=await va(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof A&&(a.status===404&&le(`no repo named "${t.name}" in this project`),le(`HUB \u2192 ${a.status} ${a.message}`)),le(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=gr(e.projectId,n.repos,r?.contextDir);for(let a of i)z.message(`updated ${a}`);for(let a of s)z.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(o===".")z.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&o?Ao(r.root,o):ve(e.projectId,t.name);if(Mn(Ao(a,".git")))try{$g(a,{recursive:!0,force:!0}),z.message(`deleted local clone ${a}`)}catch(c){z.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else z.message(`no local clone found to purge (${a})`)}z.success(`removed "${t.name}" \u2014 ${n.repos.length} repo(s) left`),Al("done")}async function Ul(t){let e=ge(t.profile),r;try{r=(await M(e.hubUrl,e.cliToken,e.projectId)).repos}catch(o){console.error(`could not read project from HUB: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let o of r){let n=o.mountAs??o.name,i=o.defaultBranch?` @${o.defaultBranch}`:"";console.log(` ${o.name} ${o.host}:${o.owner}/${o.repoName}${i} \u2192 ${n}`)}}import{spawn as jg}from"node:child_process";import{existsSync as Ll}from"node:fs";import{homedir as Pg,hostname as Eg}from"node:os";import{join as _o}from"node:path";async function Ag(t,e,r){let o=ie(e);if(!o)return!0;if(o.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Ce(e)} points at a different HUB (${o.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let n;try{n=await pa(t.hubUrl.replace(/\/$/,""),o.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(n==="unsupported")return console.log(`[up] worker already registered as ${o.sandboxId} (${o.name})`),!1;if(n==="ok")return console.log(`[up] worker already registered as ${o.sandboxId} (${o.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${o.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${Ce(e)} still holds its token.
605
- Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${o.sandboxId} \u2014 replacing the registration`),Ai(t.projectId,o.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${o.sandboxId}`),!0}async function _g(t,e,r){let o=ie(e)!==null;if(!await Ag(t,e,r))return;console.log(o?"[up] re-registering the worker \u2014 requesting an account-issued token from HUB":"[up] no worker registration \u2014 requesting an account-issued token from HUB");let n;try{({secret:n}=await go(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof A&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof A&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof A?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await wt({hub:t.hubUrl,token:n,name:r.name??`${Eg()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...o?{force:!0}:{},...e?{profile:e}:{}})}function Og(t,e){let r=ie(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=he(r.sealPublicKey);if(!U(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=Vr(t,r.sandboxId,o);if(n==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${o}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${n==="pinned"?"auto-pinned":"already pinned"} for ${t} (${o})`)}async function Ng(t,e){let r=process.cwd(),o=_o(r,Pe);if(Wr(t.projectId,r)){console.log(`[up] using the workspace context at ${o}`);return}if(Ll(o)){console.warn(`[up] ${o} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let n;try{n=await M(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Bn(r);if(!hi(r,i?.parsed??null,n.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=U(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await ko({cfg:t,secrets:s,contextDir:o,log:a});if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=_o(Pg(),".codepipe",e?_o("profiles",e,"context-config"):"context-config");if(Zr(c.contextDir,l,a),!Ll(_o(c.contextDir,"project.yaml"))){_t(c.contextDir);let u={projectId:t.projectId,name:n.name,automationLevel:n.automationLevel,repos:n.repos,...n.youtrackProjectKey?{youtrackProjectKey:n.youtrackProjectKey}:{}};mr(c.contextDir,_e(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${o}`)}async function Dl(t){let{cfg:e,profile:r}=Yr(t.profile);await Ng(e,r),await _g(e,r,t),Og(e.projectId,r);let o=process.argv[1];if(!o)throw new Error("cannot resolve the codepipe entry script for child processes");let n=(g,d)=>{let h=C=>k=>{for(let y of k.toString("utf-8").split(`
604
+ `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let k=await jg({message:"Continue?",initialValue:!0});(Eg(k)||!k)&&Ne("aborted")}!c&&a===o&&at.warn(`source and destination share the same project id, so they share one secrets file (${Ee(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:p,accountEmail:g}=await Zt(i,f),d={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:g,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};at.step(`registering project on ${i}\u2026`);let h;try{h=await tt(i,p,d)}catch(k){if(k instanceof A&&k.status===409){at.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await M(i,p,a)}catch(y){throw y instanceof A&&Ne(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if(k instanceof A&&k.status===403)Ne(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(k instanceof A)Ne(`target HUB \u2192 ${k.status} ${k.message}`);else throw k}at.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),Me({hubUrl:i,cliToken:p,projectId:a,accountEmail:g},s);let C={...u??{},hubUrl:i,cliToken:p,projectId:a};if(delete C.sandboxPins,V(C),at.success(`profile '${s}' \u2192 ${Ee(a)}`),c){let k=Ce(s);Tg(k)&&(Ig(k),at.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}Ag(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as Ho,rmSync as Og,statSync as Ng}from"node:fs";import{join as An,relative as Ug,resolve as Lg}from"node:path";import{cancel as Dg,intro as Nl,isCancel as Bg,log as z,outro as Ul,text as vt}from"@clack/prompts";import{simpleGit as Ll}from"simple-git";function ue(t){Dg(t),process.exit(1)}function xt(t){return Bg(t)&&ue("aborted"),typeof t=="string"?t:""}async function Ol(t){try{let e=await Ll(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function Gg(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function Mg(t,e){let r=U(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(Gg(r,e)){z.message(`reusing existing ${e} credentials`);return}if(z.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=xt(await vt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=xt(await vt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=xt(await vt({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}V(r),z.success(`saved ${e} credentials`)}async function Dl(t){let e=he(t.profile);Nl(`codepipe repo add \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{n=(await M(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){ue(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let o=t.target?.trim();if(!o){let y=await Ol(process.cwd());y?(o=process.cwd(),z.message(`using the current directory (${y})`)):o=xt(await vt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:$=>$.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Ho(o)&&Ng(o).isDirectory()){i=Lg(o);let y=await Ol(i);y||ue(`${i} is not a git repository (no origin remote)`);let $=we(y);$||ue(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=y,z.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let y=we(o);y||ue(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,s=o,z.message(`${a}: ${c}/${l}`)}let u=xt(await vt({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:y=>y.trim()?void 0:"required"})).trim();n.some(y=>y.name===u)&&ue(`a repo named "${u}" is already registered`);let f=xt(await vt({message:"default branch (optional)",placeholder:"main"})).trim(),p=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let y=Ug(r.root,i);p=y===""?".":y}let g=xt(await vt({message:"mount_as (directory relative to the workspace root)",placeholder:p,initialValue:p})).trim()||p;n.some(y=>(y.mountAs??y.name)===g)&&ue(`mount_as "${g}" is already used by another repo`),await Mg(e,a);let d={name:u,host:a,owner:c,repoName:l,mountAs:g,...f?{defaultBranch:f}:{}};if(!i){let y=r?An(r.root,g):ve(e.projectId,u);if(Ho(An(y,".git")))z.message(`already cloned at ${y}`);else{z.info(`cloning ${s} \u2192 ${y} \u2026`);try{await Ll().clone(s,y),z.success(`cloned into ${y}`)}catch($){ue(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
605
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await xa(e.hubUrl,e.cliToken,e.projectId,d)}catch(y){y instanceof A&&ue(`HUB \u2192 ${y.status} ${y.message}`),ue(y instanceof Error?y.message:String(y))}let{updated:C,errors:k}=fr(e.projectId,h.repos,r?.contextDir);for(let y of C)z.message(`updated ${y}`);for(let y of k)z.warn(`could not update ${y.path}: ${y.error}`);z.success(`added "${u}" \u2014 project now has ${h.repos.length} repo(s)`),Ul("done")}async function Bl(t){let e=he(t.profile);Nl(`codepipe repo remove \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{let c=(await M(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await Sa(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof A&&(a.status===404&&ue(`no repo named "${t.name}" in this project`),ue(`HUB \u2192 ${a.status} ${a.message}`)),ue(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=fr(e.projectId,o.repos,r?.contextDir);for(let a of i)z.message(`updated ${a}`);for(let a of s)z.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")z.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?An(r.root,n):ve(e.projectId,t.name);if(Ho(An(a,".git")))try{Og(a,{recursive:!0,force:!0}),z.message(`deleted local clone ${a}`)}catch(c){z.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else z.message(`no local clone found to purge (${a})`)}z.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Ul("done")}async function Gl(t){let e=he(t.profile),r;try{r=(await M(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}import{spawn as Fg}from"node:child_process";import{existsSync as Ml}from"node:fs";import{homedir as Hg,hostname as Kg}from"node:os";import{join as _n}from"node:path";async function Wg(t,e,r){let n=ie(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Ce(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 fa(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 ${Ce(e)} still holds its token.
606
+ 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`),Oi(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function qg(t,e,r){let n=ie(e)!==null;if(!await Wg(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 gn(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof A&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof A&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof A?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await yt({hub:t.hubUrl,token:o,name:r.name??`${Kg()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function Yg(t,e){let r=ie(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=ae(r.sealPublicKey);if(!U(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=qr(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 Vg(t,e){let r=process.cwd(),n=_n(r,Pe);if(Hr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Ml(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 M(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Mo(r);if(!wi(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=U(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await kn({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=_n(Hg(),".codepipe",e?_n("profiles",e,"context-config"):"context-config");if(Xr(c.contextDir,l,a),!Ml(_n(c.contextDir,"project.yaml"))){At(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};dr(c.contextDir,_e(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 Fl(t){let{cfg:e,profile:r}=Wr(t.profile);await Vg(e,r),await qg(e,r,t),Yg(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=>k=>{for(let y of k.toString("utf-8").split(`
606
607
  `))y.length>0&&C.write(`${d} ${y}
607
- `)};g.stdout?.on("data",h(process.stdout)),g.stderr?.on("data",h(process.stderr))},i=(g,d)=>{let h=jg(process.execPath,[o,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return n(h,g),h};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=g=>{if(!l){l=!0,console.log(`
608
- [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,k)=>h({name:g,code:C??(k?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 zl,mkdirSync as Gg,readFileSync as Mg,writeFileSync as Fg}from"node:fs";import{homedir as Hg}from"node:os";import{dirname as Kg,join as Xl}from"node:path";import*as nr from"node:readline";import{existsSync as Kn,readFileSync as Ug,writeFileSync as Lg}from"node:fs";import{join as Nr}from"node:path";import{simpleGit as Hn}from"simple-git";var Bl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Dg="apply-queue.json";function Gl(t){return Nr(t,Dg)}function or(t){let e=Gl(t);if(!Kn(e))return{};try{return JSON.parse(Ug(e,"utf-8"))}catch{return{}}}function Ml(t,e){Lg(Gl(t),JSON.stringify(e,null,2)+`
609
- `)}async function Fl(t,e,r,o,n){let i;try{i=await ya(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(k=>k.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let d=Nr(t.root,g.mountAs);if(!Kn(Nr(d,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Hn(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=Hn(p.dir),d=await Bg(g),h=p.claimRepo;try{await g.fetch()}catch(y){return await Fn(a,n),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${Or(y)}`}}let C=`origin/${h.baseRef}`,k;try{k=await no(g,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(y){return await Fn(a,n),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${Or(y)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:d,branch:h.branchName,baseSha:C,deliveryCommit:k,startPoint:C})}let c=[];for(let p of a)try{if(o==="apply"){await p.git.checkout(["-B",p.branch,p.startPoint]),await p.git.raw([...Bl,"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([...Bl,"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 Fn(a,n),{ok:!1,message:`apply failed in ${p.mountAs}: ${Or(g)} (rolled back all repos)`}}let l=or(t.contextDir);l[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},Ml(t.contextDir,l);let u=c.map(p=>p.mountAs).join(", "),f=o==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${o==="apply"?"applied":"unstashed"} ${r} in ${u}
608
+ `)};g.stdout?.on("data",h(process.stdout)),g.stderr?.on("data",h(process.stderr))},i=(g,d)=>{let h=Fg(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(`
609
+ [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,k)=>h({name:g,code:C??(k?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 eu,mkdirSync as Zg,readFileSync as eh,writeFileSync as th}from"node:fs";import{homedir as rh}from"node:os";import{dirname as nh,join as tu}from"node:path";import*as rr from"node:readline";import{existsSync as qo,readFileSync as Jg,writeFileSync as zg}from"node:fs";import{join as _r}from"node:path";import{simpleGit as Wo}from"simple-git";var Hl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Xg="apply-queue.json";function Kl(t){return _r(t,Xg)}function tr(t){let e=Kl(t);if(!qo(e))return{};try{return JSON.parse(Jg(e,"utf-8"))}catch{return{}}}function Wl(t,e){zg(Kl(t),JSON.stringify(e,null,2)+`
610
+ `)}async function ql(t,e,r,n,o){let i;try{i=await ba(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(k=>k.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let d=_r(t.root,g.mountAs);if(!qo(_r(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 Qg(g),h=p.claimRepo;try{await g.fetch()}catch(y){return await Ko(a,o),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${Ar(y)}`}}let C=`origin/${h.baseRef}`,k;try{k=await rn(g,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(y){return await Ko(a,o),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${Ar(y)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:d,branch:h.branchName,baseSha:C,deliveryCommit:k,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([...Hl,"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([...Hl,"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 Ko(a,o),{ok:!1,message:`apply failed in ${p.mountAs}: ${Ar(g)} (rolled back all repos)`}}let l=tr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Wl(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}
610
611
  ${f}
611
- or: /abort ${r} --reason "..."`}}function Wn(t,e){let r=or(t);r[e]&&(delete r[e],Ml(t,r))}async function Fn(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(o){e.warn(`rollback failed in ${r.mountAs}: ${Or(o)} \u2014 check manually`)}}async function Hl(t,e,r){let n=or(t.contextDir)[e];if(n){for(let i of n.repos){let s=Nr(t.root,i.mountAs);if(!Kn(Nr(s,".git")))continue;let a=Hn(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}: ${Or(u)} \u2014 check manually`)}}Wn(t.contextDir,e)}}async function Bg(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Or(t){return t instanceof Error?t.message.trim():String(t)}var Oo=Xl(Hg(),".codepipe","history"),Kl=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Ql=500,Wl=40;async function Zl(){let t=me();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=U(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),fr(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=or(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
612
- \u26A0 unfinished local apply: ${o.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
613
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=nr.createInterface({input:process.stdin,output:process.stdout,completer:Wg,history:ph(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};ls(s=>Ct(i,s)),i.daemon=bo({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>Ct(i,s),warn:s=>Ct(i,s)},onEvent:s=>ih(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Yn(i),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await qg(i,a)){Jl(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Yn(i),n.prompt()}),n.on("close",()=>{Jl(i)})}function Wg(t){let e=Kl.filter(r=>r.startsWith(t));return[e.length?e:Kl,t]}async function qg(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return Yg(),!1;case"/status":return await Vg(t),!1;case"/tasks":return await Jg(t,o),!1;case"/task":return await zg(t,o),!1;case"/sync":return await Xg(t),!1;case"/logs":return sh(t,o),!1;case"/monitor":return ah(t),!1;case"/apply":return await ql(t,o,"apply"),!1;case"/unstash":return await ql(t,o,"unstash"),!1;case"/applied":return await Qg(t,o),!1;case"/abort":return await Zg(t,o),!1;case"/approve":return await Yl(t,o,"approve"),!1;case"/merge":return await Yl(t,o,"merge"),!1;case"/login":return th(t,o),!1;case"/secret":return rh(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Yg(){console.log(["/help show this list","/status connection, project, Context Repo branch, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon logs / toggle live / clear buffer","/monitor toggle live daemon log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and exit"].join(`
614
- `))}async function Vg(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let r of t.ws.spec.repos){let o=zl(Xl(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function Jg(t,e){let r=ch(e,"--phase");try{let o=await ga(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),n=r?o.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):o;if(n.length===0){console.log(" (no tasks)");return}for(let i of n)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(o){Lr(o)}}async function zg(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await ha(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${o.task.phase} \u2014 ${o.task.title}`),o.artifacts.length>0){console.log(" artifacts:");for(let n of o.artifacts)console.log(` ${n.path}`)}}catch(o){Lr(o)}}async function Xg(t){let e=await Pr(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 ql(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}let n=await Fl(t.ws,t.secrets,o,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${n.message}`)}async function Qg(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=or(t.ws.contextDir)[r],i=lh(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,f;if(l>0?(u=c.slice(0,l),f=c.slice(l+1)):(f=c,u=n?.repos.length===1?eh(t,n.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let p=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!p){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:u,url:f,number:Number(p[1])})}try{let c=await wa(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Wn(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Lr(c)}}async function Yl(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await ka(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){Lr(n)}}async function Zg(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=uh(e,"--reason")||"local apply aborted";await Hl(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await ba(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){Lr(n)}}function eh(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function th(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},V(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function rh(t,e){let[r,o,...n]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
615
- `)}`:" (none)");return}if(r==="set"){let i=n.join(" ");if(!o||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}oh(t.secrets,o,i),V(t.secrets),fr(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}nh(t.secrets,o),V(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function oh(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 nh(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 ih(t,e){switch(e.kind){case"connected":t.connection="connecting",Ct(t,"[hub] connected");break;case"registered":t.connection="registered",Ct(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Ur(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Ct(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Ur(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Ur(t,`[hub] HUB v${e.hubVersion??"?"} (protocol ${e.hubProtocol??"?"}) is incompatible with this CLI \u2014 WriteActions are refused. Update: ${e.updateCommand}`);break;case"action":e.ok?Ct(t,`[hub] action ${e.actionType} done`):Ur(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Ct(t,e){t.logBuffer.push(e),t.logBuffer.length>Ql&&t.logBuffer.shift(),t.follow&&Ur(t,e)}function sh(t,e){let r=e[0];if(r==="follow"||r==="on"){qn(t,!0);return}if(r==="off"){qn(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(Ql,Number(r)||Wl)):Wl,n=t.logBuffer.slice(-o);if(n.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of n)console.log(` ${i}`);console.log(` \u2014 ${n.length} line(s); /monitor for live stream`)}function ah(t){qn(t,!t.follow)}function qn(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Ur(t,e){nr.cursorTo(process.stdout,0),nr.clearLine(process.stdout,0),process.stdout.write(e+`
616
- `),t.unread+=1,Yn(t),t.rl.prompt(!0)}function Yn(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Vl=!1;function Jl(t){Vl||(Vl=!0,dh(t.rl),t.daemon.stop(),console.log(`
617
- bye.`),setTimeout(()=>process.exit(0),150))}function ch(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function lh(t,e){let r=[];for(let o=0;o<t.length;o++)t[o]===e&&t[o+1]&&r.push(t[o+1]);return r}function uh(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Lr(t){t instanceof A?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function ph(){if(!zl(Oo))return[];try{return Mg(Oo,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function dh(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{Gg(Kg(Oo),{recursive:!0}),Fg(Oo,r.slice().reverse().join(`
612
+ or: /abort ${r} --reason "..."`}}function Yo(t,e){let r=tr(t);r[e]&&(delete r[e],Wl(t,r))}async function Ko(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${Ar(n)} \u2014 check manually`)}}async function Yl(t,e,r){let o=tr(t.contextDir)[e];if(o){for(let i of o.repos){let s=_r(t.root,i.mountAs);if(!qo(_r(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}: ${Ar(u)} \u2014 check manually`)}}Yo(t.contextDir,e)}}async function Qg(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Ar(t){return t instanceof Error?t.message.trim():String(t)}var On=tu(rh(),".codepipe","history"),Vl=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],ru=500,Jl=40;async function nu(){let t=ge();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=U(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),pr(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=tr(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
613
+ \u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
614
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=rr.createInterface({input:process.stdin,output:process.stdout,completer:oh,history:Sh(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};ps(s=>St(i,s)),i.daemon=bn({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>St(i,s),warn:s=>St(i,s)},onEvent:s=>wh(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Jo(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await ih(i,a)){Zl(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Jo(i),o.prompt()}),o.on("close",()=>{Zl(i)})}function oh(t){let e=Vl.filter(r=>r.startsWith(t));return[e.length?e:Vl,t]}async function ih(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return sh(),!1;case"/status":return await ah(t),!1;case"/tasks":return await ch(t,n),!1;case"/task":return await lh(t,n),!1;case"/sync":return await uh(t),!1;case"/logs":return bh(t,n),!1;case"/monitor":return kh(t),!1;case"/apply":return await zl(t,n,"apply"),!1;case"/unstash":return await zl(t,n,"unstash"),!1;case"/applied":return await ph(t,n),!1;case"/abort":return await dh(t,n),!1;case"/approve":return await Xl(t,n,"approve"),!1;case"/merge":return await Xl(t,n,"merge"),!1;case"/login":return mh(t,n),!1;case"/secret":return gh(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function sh(){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(`
615
+ `))}async function ah(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=eu(tu(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function ch(t,e){let r=$h(e,"--phase");try{let n=await ya(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){Nr(n)}}async function lh(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await wa(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){Nr(n)}}async function uh(t){let e=await Ir(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 zl(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await ql(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function ph(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=tr(t.ws.contextDir)[r],i=vh(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?fh(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 ka(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Yo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Nr(c)}}async function Xl(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await va(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Nr(o)}}async function dh(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=xh(e,"--reason")||"local apply aborted";await Yl(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await $a(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Nr(o)}}function fh(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function mh(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},V(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function gh(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(`
616
+ `)}`:" (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}hh(t.secrets,n,i),V(t.secrets),pr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}yh(t.secrets,n),V(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function hh(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 yh(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 wh(t,e){switch(e.kind){case"connected":t.connection="connecting",St(t,"[hub] connected");break;case"registered":t.connection="registered",St(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Or(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",St(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Or(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Or(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?St(t,`[hub] action ${e.actionType} done`):Or(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function St(t,e){t.logBuffer.push(e),t.logBuffer.length>ru&&t.logBuffer.shift(),t.follow&&Or(t,e)}function bh(t,e){let r=e[0];if(r==="follow"||r==="on"){Vo(t,!0);return}if(r==="off"){Vo(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(ru,Number(r)||Jl)):Jl,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 kh(t){Vo(t,!t.follow)}function Vo(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Or(t,e){rr.cursorTo(process.stdout,0),rr.clearLine(process.stdout,0),process.stdout.write(e+`
617
+ `),t.unread+=1,Jo(t),t.rl.prompt(!0)}function Jo(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Ql=!1;function Zl(t){Ql||(Ql=!0,Ch(t.rl),t.daemon.stop(),console.log(`
618
+ bye.`),setTimeout(()=>process.exit(0),150))}function $h(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function vh(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 xh(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Nr(t){t instanceof A?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Sh(){if(!eu(On))return[];try{return eh(On,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Ch(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{Zg(nh(On),{recursive:!0}),th(On,r.slice().reverse().join(`
618
619
  `)+`
619
- `)}catch{}}import{hostname as fh}from"node:os";import{cancel as mh,confirm as eu,intro as gh,isCancel as ou,log as ir,multiselect as hh,outro as tu,password as yh,select as Vn,text as Jn}from"@clack/prompts";function Dr(t){mh(t),process.exit(1)}function sr(t){return ou(t)&&Dr("aborted"),t}function No(t){return ou(t)&&Dr("aborted"),typeof t=="string"?t:""}function zn(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function ru(t,e){try{let{secret:r}=await go(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&Dr("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 wh(t,e){if(sr(await Vn({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let n=await da(t,e);if(n.length>0)return sr(await hh({message:"pick the projects (space to toggle, enter to confirm)",options:n.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));ir.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){ir.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return No(await Jn({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:n=>n.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function Xn(t){gh("codepipe worker \u2014 set up this machine as a runner");let e=ie(t.profile);e&&(ir.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),sr(await eu({message:"re-register this worker?",initialValue:!1}))||Dr("keeping the existing registration"));let r=$e(t.profile)??$e(),o=No(await Jn({message:"HUB URL",placeholder:Te,initialValue:L("HUB_URL")??r?.hubUrl??Te,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=sr(await Vn({message:"how to authorize the registration?",options:[...n?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:n?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await ru(o,a),ir.success("account-issued registration token minted");else if(i==="login"){let p=await er();a=(await tr(o,p)).cliToken,s=await ru(o,a),ir.success("account-issued registration token minted")}else s=No(await yh({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Dr("a registration token is required");let c=await wh(o,a),l=No(await Jn({message:"worker name",initialValue:fh(),validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=sr(await Vn({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 wt({hub:o,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),ir.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!sr(await eu({message:"start the claim-loop now?",initialValue:!0}))){tu("registered. start later with `codepipe worker`.");return}tu("starting the claim-loop\u2026"),await jr(t.profile?{profile:t.profile}:{})}function kh(){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 X=kh();$i(X);Si();var ue=new bh;ue.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(fe).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 Zl()}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 wl({configPath:t.config,skipVerify:t.skipVerify===!0}):await cl({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>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Oi({...t,profile:X})}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 ll({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 Ya({profile:X})}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 el({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 xl({profile:X,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 Lc({profile:X})}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 Dl({profile:X,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var nu=ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");nu.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")??$e(X)?.hubUrl??Te,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&zn()){await Xn({profile:X});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let o=L("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??L("WORKER_NAME"),i=t.llm??L("WORKER_LLM");await wt({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...X?{profile:X}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});nu.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ie(X)&&zn()){await Xn({profile:X});return}await jr(X?{profile:X}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var iu=ue.command("project").description("Manage CodePipe projects");iu.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Tl({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});iu.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await jl({...t,cliProfile:X})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Qn=ue.command("repo").description("Manage the project's git repositories");Qn.command("add").description("Add a repo to this project (a path to an existing clone, or a clone URL)").argument("[target]","Path to an already-cloned repo, or a repo clone URL").action(async t=>{try{await Ol({profile:X,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Qn.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await Nl({profile:X,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Qn.command("list").description("List the project's repos").action(async()=>{try{await Ul({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.parseAsync();
620
+ `)}catch{}}import{hostname as Rh}from"node:os";import{cancel as Th,confirm as ou,intro as Ih,isCancel as au,log as nr,multiselect as jh,outro as iu,password as Ph,select as zo,text as Xo}from"@clack/prompts";function Ur(t){Th(t),process.exit(1)}function or(t){return au(t)&&Ur("aborted"),t}function Nn(t){return au(t)&&Ur("aborted"),typeof t=="string"?t:""}function Qo(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function su(t,e){try{let{secret:r}=await gn(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&Ur("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 Eh(t,e){if(or(await zo({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let o=await ma(t,e);if(o.length>0)return or(await jh({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}));nr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){nr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Nn(await Xo({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 Zo(t){Ih("codepipe worker \u2014 set up this machine as a runner");let e=ie(t.profile);e&&(nr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),or(await ou({message:"re-register this worker?",initialValue:!1}))||Ur("keeping the existing registration"));let r=$e(t.profile)??$e(),n=Nn(await Xo({message:"HUB URL",placeholder:Te,initialValue:L("HUB_URL")??r?.hubUrl??Te,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=or(await zo({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 su(n,a),nr.success("account-issued registration token minted");else if(i==="login"){let p=await Qt();a=(await Zt(n,p)).cliToken,s=await su(n,a),nr.success("account-issued registration token minted")}else s=Nn(await Ph({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Ur("a registration token is required");let c=await Eh(n,a),l=Nn(await Xo({message:"worker name",initialValue:Rh(),validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=or(await zo({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await yt({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),nr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!or(await ou({message:"start the claim-loop now?",initialValue:!0}))){iu("registered. start later with `codepipe worker`.");return}iu("starting the claim-loop\u2026"),await Tr(t.profile?{profile:t.profile}:{})}function _h(){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 X=_h();xi(X);Ri();var pe=new Ah;pe.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(me).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await nu()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.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 vl({configPath:t.config,skipVerify:t.skipVerify===!0}):await dl({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Ui({...t,profile:X})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.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 fl({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});pe.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Xa({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.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 ol({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.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 Tl({profile:X,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});pe.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Mc({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.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 Fl({profile:X,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var cu=pe.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");cu.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")??$e(X)?.hubUrl??Te,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Qo()){await Zo({profile:X});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=L("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??L("WORKER_NAME"),i=t.llm??L("WORKER_LLM");await yt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...X?{profile:X}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});cu.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ie(X)&&Qo()){await Zo({profile:X});return}await Tr(X?{profile:X}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var lu=pe.command("project").description("Manage CodePipe projects");lu.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await El({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});lu.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await _l({...t,cliProfile:X})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var ei=pe.command("repo").description("Manage the project's git repositories");ei.command("add").description("Add a repo to this project (a path to an existing clone, or a clone URL)").argument("[target]","Path to an already-cloned repo, or a repo clone URL").action(async t=>{try{await Dl({profile:X,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ei.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await Bl({profile:X,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ei.command("list").description("List the project's repos").action(async()=>{try{await Gl({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.parseAsync();