@code-partner/codepipe 0.3.5 → 0.3.6-dev.107.g88d53ec

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 +110 -110
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,35 +1,35 @@
1
1
  #!/usr/bin/env node
2
- var me="0.3.5",Te="https://hub.codepipe.dev";var Ie=4,bu=4;function Dr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=bu&&t<=Ie}var je=".codepipe-context.yaml",lr=".devpipe-context.yaml",ui=[{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 Br(t=2){return`# CodePipe Context Repo format version.
2
+ var me="0.3.6-dev.107.g88d53ec",Ce="https://hub.dev.codepipe.dev";var Te=4,Su=4;function Lr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Su&&t<=Te}var Ie=".codepipe-context.yaml",lr=".devpipe-context.yaml",di=[{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",Ie]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Ie]}];function Br(t=2){return`# CodePipe Context Repo format version.
3
3
  # Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
4
4
  template_version: ${t}
5
- `}function pi(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 di(t,e=ui){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 fi(t,e=ui){return e.filter(r=>r.version>t)}var mi=["estimate","analyze","implement","resolve-conflict","rework","draft","build","index","backfill","analysis","chat"];function dt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ge="opus",Gr="sonnet",ku="haiku",qn=[Ge,Gr,ku],gi={analyze:Ge,implement:Ge,"resolve-conflict":Ge,rework:Ge,estimate:Gr,build:Gr,draft:Gr,index:Ge,backfill:Ge,analysis:Ge,chat:Ge};var $u=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{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:[...qn],help:"Overrides the recommended defaults for every role not listed below."},...mi.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...qn],help:`recommended: ${gi[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 hi(t=$u){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...hi(r.groups));return e}function xu(t,e){let r=JSON.stringify(e);return hi().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function yi(t){let e=xu(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":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:{ok:!0,field:e,value:i}}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 ft=/^[a-z][a-z0-9-]{1,30}$/,vu="-codepipe-ctx";function Me(t){return`${t}${vu}`}var Su=[{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 Mr(t){for(let e of Su){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 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 n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}var mt="x-bitbucket-api-token-auth";function Fr(t){switch(t){case ur.gitlab:return"oauth2";case ur.bitbucket:return"x-token-auth";default:return"x-access-token"}}var wi=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Vh}from"commander";import{homedir as vi}from"node:os";import{mkdirSync as Ou,readFileSync as Nu,writeFileSync as Uu,existsSync as Vn}from"node:fs";import{dirname as Ri,join as Wr,resolve as Lu}from"node:path";import{fileURLToPath as Du}from"node:url";import{existsSync as Hr,readFileSync as ki,readdirSync as Cu,writeFileSync as Tu}from"node:fs";import{dirname as Iu,join as Ve}from"node:path";import{parse as ju}from"yaml";import{existsSync as bi,renameSync as Ru}from"node:fs";function gt(t,e,r=n=>console.error(n)){if(bi(e)||!bi(t))return!1;try{return Ru(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",Yn=".devpipe";function Pu(t=process.cwd()){let e=t;for(;;){if(Hr(Ve(e,Pe,"project.yaml")))return e;if(Hr(Ve(e,Yn,"project.yaml")))return gt(Ve(e,Yn),Ve(e,Pe))&&Au(e),e;let r=Iu(e);if(r===e)return null;e=r}}function Eu(t){let e=Ve(t,Pe);return Hr(e)?e:Ve(t,Yn)}function Au(t){let e=Ve(t,".gitignore");if(!Hr(e))return;let r=ki(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&&Tu(e,n)}function ge(t=process.cwd()){let e=Pu(t);if(!e)return null;let r=Eu(e),n=_u(ki(Ve(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function $i(t,e,r){return Cu(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 Kr(t,e=process.cwd()){try{let r=ge(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function _u(t){let e=ju(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,d=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:d,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function xi(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 Si=Lu(Ri(Du(import.meta.url)),"..");function Ci(t){let e=Wr(Si,".env");if(Vn(e)&&process.loadEnvFile(e),t){let r=Wr(Si,"profiles",t,".env");Vn(r)&&process.loadEnvFile(r)}}function Ct(t){let e=L("CONFIG");return e||(t?Wr(vi(),".codepipe","profiles",t,"config.json"):Wr(vi(),".codepipe","config.json"))}function $e(t){let e=Ct(t);if(!Vn(e))return null;let r=Nu(e,"utf-8");return JSON.parse(r)}function Fe(t,e){let r=Ct(e);Ou(Ri(r),{recursive:!0}),Uu(r,JSON.stringify(t,null,2)+`
7
- `,{mode:384})}function qr(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 ${Ct(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as Ti}from"node:os";import{join as Ii}from"node:path";function ji(){gt(Ii(Ti(),".devpipe"),Ii(Ti(),".codepipe"))}import{homedir as Pi}from"node:os";import{existsSync as Ei,mkdirSync as Ai,readFileSync as _i,writeFileSync as Oi}from"node:fs";import{dirname as Ni,join as Ui}from"node:path";function Yr(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 Li(t,e){let r=U(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],V(r),!0):!1}function Ee(t){return Ui(Pi(),".codepipe","secrets",`${t}.json`)}function U(t){let e=Ee(t);return Ei(e)?JSON.parse(_i(e,"utf-8")):null}function V(t){let e=Ee(t.projectId);Ai(Ni(e),{recursive:!0}),Oi(e,JSON.stringify(t,null,2)+`
8
- `,{mode:384})}function Vr(){return Ui(Pi(),".codepipe","shared.json")}function Jn(){let t=Vr();return Ei(t)?JSON.parse(_i(t,"utf-8")):null}function Di(t){let e=Vr();Ai(Ni(e),{recursive:!0}),Oi(e,JSON.stringify(t,null,2)+`
9
- `,{mode:384})}function Tt(t){let e=U(t)?.claude?.oauthToken;return e||Jn()?.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 Bi(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 ${Ct(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Fe({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=${Ct(e)}`)}import{homedir as Io}from"node:os";import{join as vr}from"node:path";import{appendFileSync as Bu,existsSync as Gi,mkdirSync as Gu,renameSync as Mi,statSync as Mu,unlinkSync as Fu}from"node:fs";import{Writable as Hu}from"node:stream";import{join as Ku}from"node:path";var Fi={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},jt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Gu(e.dir,{recursive:!0}),this.currentPath=Ku(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 fi(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 mi(t,e=di){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 gi(t,e=di){return e.filter(r=>r.version>t)}var hi=["estimate","analyze","implement","resolve-conflict","rework","draft","build","index","backfill","analysis","chat"];function dt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Be="opus",Mr="sonnet",Ru="haiku",Yn=[Be,Mr,Ru],yi={analyze:Be,implement:Be,"resolve-conflict":Be,rework:Be,estimate:Mr,build:Mr,draft:Mr,index:Be,backfill:Be,analysis:Be,chat:Be};var Cu=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{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:[...Yn],help:"Overrides the recommended defaults for every role not listed below."},...hi.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Yn],help:`recommended: ${yi[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 wi(t=Cu){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...wi(r.groups));return e}function Tu(t,e){let r=JSON.stringify(e);return wi().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function bi(t){let e=Tu(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":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:{ok:!0,field:e,value:i}}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}}}}function ki(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}var ft=/^[a-z][a-z0-9-]{1,30}$/,Iu="-codepipe-ctx";function Me(t){return`${t}${Iu}`}var ju=[{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 ju){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 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 n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}var mt="x-bitbucket-api-token-auth";function Fr(t){switch(t){case ur.gitlab:return"oauth2";case ur.bitbucket:return"x-token-auth";default:return"x-access-token"}}var $i=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as oy}from"commander";import{homedir as Ci}from"node:os";import{mkdirSync as Bu,readFileSync as Mu,writeFileSync as Gu,existsSync as Jn}from"node:fs";import{dirname as Ii,join as Wr,resolve as Fu}from"node:path";import{fileURLToPath as Hu}from"node:url";import{existsSync as Hr,readFileSync as vi,readdirSync as Eu,writeFileSync as Au}from"node:fs";import{dirname as _u,join as Ve}from"node:path";import{parse as Ou}from"yaml";import{existsSync as xi,renameSync as Pu}from"node:fs";function gt(t,e,r=n=>console.error(n)){if(xi(e)||!xi(t))return!1;try{return Pu(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 je=".codepipe",Vn=".devpipe";function Nu(t=process.cwd()){let e=t;for(;;){if(Hr(Ve(e,je,"project.yaml")))return e;if(Hr(Ve(e,Vn,"project.yaml")))return gt(Ve(e,Vn),Ve(e,je))&&Du(e),e;let r=_u(e);if(r===e)return null;e=r}}function Uu(t){let e=Ve(t,je);return Hr(e)?e:Ve(t,Vn)}function Du(t){let e=Ve(t,".gitignore");if(!Hr(e))return;let r=vi(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&&Au(e,n)}function ge(t=process.cwd()){let e=Nu(t);if(!e)return null;let r=Uu(e),n=Lu(vi(Ve(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Si(t,e,r){return Eu(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 Kr(t,e=process.cwd()){try{let r=ge(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Lu(t){let e=Ou(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 p=a.host,d=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:l,host:d,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function Ri(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 Ti=Fu(Ii(Hu(import.meta.url)),"..");function ji(t){let e=Wr(Ti,".env");if(Jn(e)&&process.loadEnvFile(e),t){let r=Wr(Ti,"profiles",t,".env");Jn(r)&&process.loadEnvFile(r)}}function Ct(t){let e=L("CONFIG");return e||(t?Wr(Ci(),".codepipe","profiles",t,"config.json"):Wr(Ci(),".codepipe","config.json"))}function $e(t){let e=Ct(t);if(!Jn(e))return null;let r=Mu(e,"utf-8");return JSON.parse(r)}function Ge(t,e){let r=Ct(e);Bu(Ii(r),{recursive:!0}),Gu(r,JSON.stringify(t,null,2)+`
7
+ `,{mode:384})}function qr(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 ${Ct(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as Pi}from"node:os";import{join as Ei}from"node:path";function Ai(){gt(Ei(Pi(),".devpipe"),Ei(Pi(),".codepipe"))}import{homedir as _i}from"node:os";import{existsSync as Oi,mkdirSync as Ni,readFileSync as Ui,writeFileSync as Di}from"node:fs";import{dirname as Li,join as Bi}from"node:path";function Yr(t,e,r){let n=D(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,Y(n),"pinned")}function Mi(t,e){let r=D(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],Y(r),!0):!1}function Pe(t){return Bi(_i(),".codepipe","secrets",`${t}.json`)}function D(t){let e=Pe(t);return Oi(e)?JSON.parse(Ui(e,"utf-8")):null}function Y(t){let e=Pe(t.projectId);Ni(Li(e),{recursive:!0}),Di(e,JSON.stringify(t,null,2)+`
8
+ `,{mode:384})}function Vr(){return Bi(_i(),".codepipe","shared.json")}function zn(){let t=Vr();return Oi(t)?JSON.parse(Ui(t,"utf-8")):null}function Gi(t){let e=Vr();Ni(Li(e),{recursive:!0}),Di(e,JSON.stringify(t,null,2)+`
9
+ `,{mode:384})}function Tt(t){let e=D(t)?.claude?.oauthToken;return e||zn()?.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 Fi(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 ${Ct(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Ge({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...D(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};Y(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Ct(e)}`)}import{homedir as jo}from"node:os";import{join as vr}from"node:path";import{appendFileSync as Ku,existsSync as Hi,mkdirSync as Wu,renameSync as Ki,statSync as qu,unlinkSync as Yu}from"node:fs";import{Writable as Vu}from"node:stream";import{join as Ju}from"node:path";var Wi={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},jt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Wu(e.dir,{recursive:!0}),this.currentPath=Ju(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
- `;Bu(this.currentPath,r,"utf-8")}asWritable(){return new Hu({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||!Gi(this.currentPath)||Mu(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Gi(n)&&(r>=this.cfg.maxFiles?Fu(n):Mi(n,`${this.currentPath}.${r+1}`))}Mi(this.currentPath,`${this.currentPath}.1`)}}};function Jr(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Wu(process.env[`${t}_MAX_BYTES`]??String(Fi.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Fi.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Wu(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 zr(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(qu(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 qu(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Yu(o)).join(" ");return`${r} ${t} ${n}`}function Yu(t){try{return JSON.stringify(t)}catch{return String(t)}}import{existsSync as Ma,rmSync as ff}from"node:fs";import{join as xr}from"node:path";import{simpleGit as mf}from"simple-git";import"ws";import{createHash as Vu}from"node:crypto";import{existsSync as Ju,readFileSync as zu}from"node:fs";import{homedir as Xu,hostname as zn}from"node:os";import{join as Qu}from"node:path";function Hi(t){return Vu("sha256").update(t).digest("hex").slice(0,12)}function Zu(){let t=L("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Qu(Xu(),".claude","credentials.json");if(!Ju(e))return;let r=JSON.parse(zu(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 Ki(t){let e=Zu(),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-${Hi(o)}`,label:n||zn(),...e?{email:e}:{}}:{accountId:`acct-${Hi(`host:${zn()}`)}`,label:n||zn(),...e?{email:e}:{}}}import{existsSync as ep}from"node:fs";import{join as tp}from"node:path";import{simpleGit as rp}from"simple-git";async function Wi(t,e){if(!ep(tp(t,".git")))return{status:"skipped"};let r=rp(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${np(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 np(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Xn,readFileSync as qi,readdirSync as op,watch as ip}from"node:fs";import{join as Qn}from"node:path";var Xr=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(Xn(this.contextDir))try{this.watcher=ip(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=Qn(this.contextDir,e);if(!Xn(r))return null;try{return qi(r,"utf-8")}catch{return null}}readPrompts(){let e=Qn(this.contextDir,"prompts"),r={};if(!Xn(e))return r;let n;try{n=op(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=qi(Qn(e,o),"utf-8")}catch{}}return r}};import{existsSync as oo,readFileSync as Zi,readdirSync as hp}from"node:fs";import{join as es}from"node:path";import{simpleGit as yp}from"simple-git";import{existsSync as lp,mkdirSync as up,rmSync as pp,writeFileSync as Ji}from"node:fs";import{dirname as dp,isAbsolute as fp,join as Xi,normalize as no}from"node:path";import{simpleGit as Qi}from"simple-git";import{existsSync as Je,mkdirSync as Yi,readFileSync as Zn,writeFileSync as Pt}from"node:fs";import{homedir as sp}from"node:os";import{join as Ae}from"node:path";import{simpleGit as ap}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);Je(s)||(Pt(s,i),r.push(o))}return r}function ht(t,e,r){let n=Ae(sp(),".codepipe","profiles",t,"context-config");return Yi(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 Qr(t,e,r){if(Je(e))for(let n of Et){let o=Ae(e,n),i=Ae(t,n);if(!(!Je(o)||Je(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 cp=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function At(t){let e=Ae(t,".gitignore"),r=Je(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(`
11
+ `;Ku(this.currentPath,r,"utf-8")}asWritable(){return new Vu({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||!Hi(this.currentPath)||qu(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Hi(n)&&(r>=this.cfg.maxFiles?Yu(n):Ki(n,`${this.currentPath}.${r+1}`))}Ki(this.currentPath,`${this.currentPath}.1`)}}};function Jr(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=zu(process.env[`${t}_MAX_BYTES`]??String(Wi.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Wi.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function zu(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 zr(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(Xu(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 Xu(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Qu(o)).join(" ");return`${r} ${t} ${n}`}function Qu(t){try{return JSON.stringify(t)}catch{return String(t)}}import{existsSync as qa,rmSync as vf}from"node:fs";import{join as xr}from"node:path";import{simpleGit as Sf}from"simple-git";import"ws";import{createHash as Zu}from"node:crypto";import{existsSync as ep,readFileSync as tp}from"node:fs";import{homedir as rp,hostname as Xn}from"node:os";import{join as np}from"node:path";function qi(t){return Zu("sha256").update(t).digest("hex").slice(0,12)}function op(){let t=L("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=np(rp(),".claude","credentials.json");if(!ep(e))return;let r=JSON.parse(tp(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 Yi(t){let e=op(),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-${qi(o)}`,label:n||Xn(),...e?{email:e}:{}}:{accountId:`acct-${qi(`host:${Xn()}`)}`,label:n||Xn(),...e?{email:e}:{}}}import{existsSync as ip}from"node:fs";import{join as sp}from"node:path";import{simpleGit as ap}from"simple-git";async function Vi(t,e){if(!ip(sp(t,".git")))return{status:"skipped"};let r=ap(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${cp(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 cp(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Qn,readFileSync as Ji,readdirSync as lp,watch as up}from"node:fs";import{join as Zn}from"node:path";var Xr=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(Qn(this.contextDir))try{this.watcher=up(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=Zn(this.contextDir,e);if(!Qn(r))return null;try{return Ji(r,"utf-8")}catch{return null}}readPrompts(){let e=Zn(this.contextDir,"prompts"),r={};if(!Qn(e))return r;let n;try{n=lp(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Ji(Zn(e,o),"utf-8")}catch{}}return r}};import{existsSync as io,readFileSync as rs,readdirSync as $p}from"node:fs";import{join as ns}from"node:path";import{simpleGit as xp}from"simple-git";import{existsSync as mp,mkdirSync as gp,rmSync as hp,writeFileSync as Qi}from"node:fs";import{dirname as yp,isAbsolute as wp,join as es,normalize as oo}from"node:path";import{simpleGit as ts}from"simple-git";import{existsSync as Je,mkdirSync as zi,readFileSync as eo,writeFileSync as Pt}from"node:fs";import{homedir as pp}from"node:os";import{join as Ee}from"node:path";import{simpleGit as dp}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=Ee(t,o);Je(s)||(Pt(s,i),r.push(o))}return r}function ht(t,e,r){let n=Ee(pp(),".codepipe","profiles",t,"context-config");return zi(n,{recursive:!0}),Pt(Ee(n,"project.yaml"),e.projectYaml),Pt(Ee(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Qr(t,e,r){if(Je(e))for(let n of Et){let o=Ee(e,n),i=Ee(t,n);if(!(!Je(o)||Je(i)))try{Pt(i,eo(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 fp=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function At(t){let e=Ee(t,".gitignore"),r=Je(e)?eo(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 Pt(e,r+i+cp.join(`
13
+ `;return Pt(e,r+i+fp.join(`
14
14
  `)+`
15
- `),!0}async function Vi(t,e){try{if(!Je(Ae(t,".git")))return;let r=ap(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 ro(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 eo(t){let e=new Map;for(let r of Et){let n=Ae(t,r);Je(n)&&e.set(r,Zn(n))}return e}function to(t,e){Yi(t,{recursive:!0});for(let[r,n]of e){let o=Ae(t,r);Je(o)||Pt(o,n)}}var zi=3,mp=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function _t(t,e,r){if(!lp(Xi(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=He(t,i.path);if(i.deleted){pp(s,{force:!0});continue}up(dp(s),{recursive:!0}),i.encoding==="base64"?Ji(s,Buffer.from(i.content,"base64")):Ji(s,i.content)}let n=Qi(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 ro(t))}async function ro(t){let e=Qi(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=zi;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 gp(e);if(i.length>0&&i.every(s=>mp.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 ${zi} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function gp(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
- `).map(r=>r.trim()).filter(Boolean)}function He(t,e){if(fp(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=no(Xi(t,e)),n=no(t+"/");if(r!==no(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var wp=/^(\d{4})-(.+)\.md$/,bp="0000-template.md";function kp(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 $p(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
19
- `),a=s.findIndex(b=>b.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],d="",p=null,g=a>=0?a+1:0;for(let b=g;b<s.length;b++){let h=(s[b]??"").trim();if(h===""){g=b+1;continue}let x=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(h);if(!x)break;let S=(x[1]??"").trim().toLowerCase(),N=(x[2]??"").trim(),I=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(h);I&&(p=parseInt(I[1]??"",10)),S==="tasks"&&(d=N),l.has(S)||u.push(h),g=b+1}let f=d?d.includes(n)?d:`${d}, ${n}`:n,y=s.slice(g).join(`
20
- `).replace(/^\n+/,""),w=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",y].join(`
21
- `);return{content:w.endsWith(`
22
- `)?w:w+`
23
- `,supersedes:p}}function xp(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
24
-
25
- - **Status:** superseded by ADR-${r}`):n}function vp(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((n,o)=>n.num-o.num)){let n=String(r.num).padStart(4,"0"),o=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${n} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${o}`)}return e.join(`
15
+ `),!0}async function Xi(t,e){try{if(!Je(Ee(t,".git")))return;let r=dp(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 no(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 to(t){let e=new Map;for(let r of Et){let n=Ee(t,r);Je(n)&&e.set(r,eo(n))}return e}function ro(t,e){zi(t,{recursive:!0});for(let[r,n]of e){let o=Ee(t,r);Je(o)||Pt(o,n)}}var Zi=3,bp=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function _t(t,e,r){if(!mp(es(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Fe(t,i.path);if(i.deleted){hp(s,{force:!0});continue}gp(yp(s),{recursive:!0}),i.encoding==="base64"?Qi(s,Buffer.from(i.content,"base64")):Qi(s,i.content)}let n=ts(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 no(t))}async function no(t){let e=ts(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Zi;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 kp(e);if(i.length>0&&i.every(s=>bp.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 ${Zi} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function kp(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
+ `).map(r=>r.trim()).filter(Boolean)}function Fe(t,e){if(wp(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=oo(es(t,e)),n=oo(t+"/");if(r!==oo(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var vp=/^(\d{4})-(.+)\.md$/,Sp="0000-template.md";function Rp(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 Cp(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"]),p=[],d="",u=null,g=a>=0?a+1:0;for(let k=g;k<s.length;k++){let h=(s[k]??"").trim();if(h===""){g=k+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(h);if(!$)break;let S=($[1]??"").trim().toLowerCase(),U=($[2]??"").trim(),I=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(h);I&&(u=parseInt(I[1]??"",10)),S==="tasks"&&(d=U),l.has(S)||p.push(h),g=k+1}let f=d?d.includes(n)?d:`${d}, ${n}`:n,w=s.slice(g).join(`
20
+ `).replace(/^\n+/,""),b=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...p,"",w].join(`
21
+ `);return{content:b.endsWith(`
22
+ `)?b:b+`
23
+ `,supersedes:u}}function Tp(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
24
+
25
+ - **Status:** superseded by ADR-${r}`):n}function Ip(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 ts(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await yp(t).pull(void 0,void 0,["--rebase"])}catch{}let i=w=>o==="staging"?`adr/DRAFT-${w}.md`:`tasks/${e}/adr/DRAFT-${w}.md`,s=[],a=[];for(let w of r){let b=He(t,i(w));if(!oo(b)){a.push(w);continue}s.push({slug:w,content:Zi(b,"utf-8")})}let c=es(t,"adr"),l=new Map;if(oo(c))for(let w of hp(c)){let b=wp.exec(w);!b||w===bp||l.set(w,{num:parseInt(b[1]??"",10),slug:b[2]??"",content:Zi(es(c,w),"utf-8")})}let u=Math.max(0,...[...l.values()].map(w=>w.num))+1,d=new Map,p=[],g=[];for(let w of s){if([...l.entries()].find(([,I])=>I.slug===w.slug&&I.content.includes(e))){g.push(w.slug);continue}let h=u++,x=`${String(h).padStart(4,"0")}-${w.slug}.md`,{content:S,supersedes:N}=$p(w.content,h,w.slug,e,n);if(d.set(x,S),l.set(x,{num:h,slug:w.slug,content:S}),p.push(`adr/${x}`),N!==null){let I=[...l.keys()].find(v=>v.startsWith(`${String(N).padStart(4,"0")}-`));if(I&&I!==x){let v=xp(d.get(I)??l.get(I).content,h);d.set(I,v),l.set(I,{...l.get(I),content:v})}}}let f=[];if(o==="staging")for(let w of s)oo(He(t,`adr/DRAFT-${w.slug}.md`))&&f.push({path:`adr/DRAFT-${w.slug}.md`,content:"",deleted:!0});if(p.length===0&&f.length===0)return{promoted:p,skipped:g,missing:a};if(p.length>0){let w=[...l.entries()].map(([b,h])=>({num:h.num,file:b,header:kp(h.content)}));d.set("INDEX.md",vp(w))}for(let[w,b]of d.entries())f.push({path:`adr/${w}`,content:b});let y=p.length>0?`adr(${e}): promote ${s.map(w=>w.slug).join(", ")}`:`adr(${e}): drop stale staged ${g.join(", ")}`;return await _t(t,f,y),{promoted:p,skipped:g,missing:a}}import{existsSync as rs,readFileSync as Rp}from"node:fs";import{join as ns}from"node:path";function Cp(t){for(let e of[je,lr]){let r=ns(t,e);if(rs(r))try{return pi(Rp(r,"utf-8"))}catch{return 0}}return 0}function Tp(t,e,r,n=2){let o=e<n,i=o?di(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Zr(t,e){return Tp(e,Cp(t),r=>rs(ns(t,r)))}import{existsSync as as,mkdirSync as Fp,mkdtempSync as Hp,rmSync as cs,writeFileSync as ls}from"node:fs";import{tmpdir as Kp}from"node:os";import{dirname as Wp,join as tn}from"node:path";import{simpleGit as lo}from"simple-git";var yt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function os(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 en(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 Ip(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 Ip(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 ss(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 io=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let 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 yt(`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()}`)}},so=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 yt(`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 d of u.check_runs??[])l=!0,d.status!=="completed"?a=!0:d.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(d.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let 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 d of l.filter(p=>p.conclusion&&i.includes(p.conclusion))){let p=await fetch(`${o}/actions/runs/${d.id}/jobs?per_page=50`,{headers:n});if(!p.ok)continue;let g=(await p.json()).jobs??[];for(let f of g.filter(y=>y.conclusion==="failure")){let y=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!y.ok)continue;let w=await y.text();u.push(`### CI job: ${f.name}
27
+ `}async function os(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await xp(t).pull(void 0,void 0,["--rebase"])}catch{}let i=b=>o==="staging"?`adr/DRAFT-${b}.md`:`tasks/${e}/adr/DRAFT-${b}.md`,s=[],a=[];for(let b of r){let k=Fe(t,i(b));if(!io(k)){a.push(b);continue}s.push({slug:b,content:rs(k,"utf-8")})}let c=ns(t,"adr"),l=new Map;if(io(c))for(let b of $p(c)){let k=vp.exec(b);!k||b===Sp||l.set(b,{num:parseInt(k[1]??"",10),slug:k[2]??"",content:rs(ns(c,b),"utf-8")})}let p=Math.max(0,...[...l.values()].map(b=>b.num))+1,d=new Map,u=[],g=[];for(let b of s){if([...l.entries()].find(([,I])=>I.slug===b.slug&&I.content.includes(e))){g.push(b.slug);continue}let h=p++,$=`${String(h).padStart(4,"0")}-${b.slug}.md`,{content:S,supersedes:U}=Cp(b.content,h,b.slug,e,n);if(d.set($,S),l.set($,{num:h,slug:b.slug,content:S}),u.push(`adr/${$}`),U!==null){let I=[...l.keys()].find(E=>E.startsWith(`${String(U).padStart(4,"0")}-`));if(I&&I!==$){let E=Tp(d.get(I)??l.get(I).content,h);d.set(I,E),l.set(I,{...l.get(I),content:E})}}}let f=[];if(o==="staging")for(let b of s)io(Fe(t,`adr/DRAFT-${b.slug}.md`))&&f.push({path:`adr/DRAFT-${b.slug}.md`,content:"",deleted:!0});if(u.length===0&&f.length===0)return{promoted:u,skipped:g,missing:a};if(u.length>0){let b=[...l.entries()].map(([k,h])=>({num:h.num,file:k,header:Rp(h.content)}));d.set("INDEX.md",Ip(b))}for(let[b,k]of d.entries())f.push({path:`adr/${b}`,content:k});let w=u.length>0?`adr(${e}): promote ${s.map(b=>b.slug).join(", ")}`:`adr(${e}): drop stale staged ${g.join(", ")}`;return await _t(t,f,w),{promoted:u,skipped:g,missing:a}}import{existsSync as is,readFileSync as Pp}from"node:fs";import{join as ss}from"node:path";function Ep(t){for(let e of[Ie,lr]){let r=ss(t,e);if(is(r))try{return fi(Pp(r,"utf-8"))}catch{return 0}}return 0}function Ap(t,e,r,n=2){let o=e<n,i=o?mi(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Zr(t,e){return Ap(e,Ep(t),r=>is(ss(t,r)))}import{existsSync as us,mkdirSync as Yp,mkdtempSync as Vp,rmSync as ps,writeFileSync as ds}from"node:fs";import{tmpdir as Jp}from"node:os";import{dirname as zp,join as tn}from"node:path";import{simpleGit as uo}from"simple-git";var yt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function as(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 en(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 _p(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 _p(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 ls(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 so=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 yt(`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()}`)}},ao=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 yt(`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 p=await i.json();for(let d of p.check_runs??[])l=!0,d.status!=="completed"?a=!0:d.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(d.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(l=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let 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??[],p=[];for(let d of l.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${o}/actions/runs/${d.id}/jobs?per_page=50`,{headers:n});if(!u.ok)continue;let g=(await u.json()).jobs??[];for(let f of g.filter(w=>w.conclusion==="failure")){let w=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!w.ok)continue;let b=await w.text();p.push(`### CI job: ${f.name}
29
29
 
30
- ${os(w,8e3)}`)}}return u.length===0?void 0:os(u.join(`
30
+ ${as(b,8e3)}`)}}return p.length===0?void 0:as(p.join(`
31
31
 
32
- `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async closePR(e,r,n){if(n&&n.length>0){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},ao=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let 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 yt(`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=jp(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 jp(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 co=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(is(e,r,"merge"))}async closePR(e,r,n){throw new Error(is(e,r,"close"))}};function is(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 Ke(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new so(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new io(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new ao(e)}return new co}function Ot(t,e,r,n){return[{path:"README.md",content:Bp(t,e)},{path:".gitignore",content:Op()},{path:"CLAUDE.md",content:Up(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Np()},{path:"knowledge/README.md",content:Lp()},{path:"knowledge/build.yaml",content:Dp()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:_p()},{path:"adr/README.md",content:Pp()},{path:"adr/0000-template.md",content:Ep()},{path:"adr/INDEX.md",content:Ap()},{path:je,content:Br()}]}function Pp(){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()}`)}},co=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 yt(`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=Op(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 p=await a.json().catch(()=>null);s=p?.sha??p?.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 Op(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 lo=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(cs(e,r,"merge"))}async closePR(e,r,n){throw new Error(cs(e,r,"close"))}};function cs(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 He(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new ao(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new so(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new co(e)}return new lo}function Ot(t,e,r,n){return[{path:"README.md",content:Kp(t,e)},{path:".gitignore",content:Bp()},{path:"CLAUDE.md",content:Gp(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Mp()},{path:"knowledge/README.md",content:Fp()},{path:"knowledge/build.yaml",content:Hp()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Lp()},{path:"adr/README.md",content:Np()},{path:"adr/0000-template.md",content:Up()},{path:"adr/INDEX.md",content:Dp()},{path:Ie,content:Br()}]}function Np(){return`# ADR \u2014 architecture decision records
33
33
 
34
34
  Accepted architectural decisions of this project \u2014 its **framework**. The
35
35
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -57,7 +57,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
57
57
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
58
58
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
59
59
  open a PR to this repository.
60
- `}function Ep(){return`# ADR-NNNN: <title>
60
+ `}function Up(){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 Ap(){return`# ADR index
82
+ `}function Dp(){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 _p(){return`# Audit
87
+ `}function Lp(){return`# Audit
88
88
 
89
89
  Pipeline event logs. Naming is per-writer: each codepipe
90
90
  project appends only to its own file \u2014
@@ -93,14 +93,14 @@ project appends only to its own file \u2014
93
93
 
94
94
  \u2014 so several team members' CLIs never contend on one file. Do not create a
95
95
  shared aggregate here.
96
- `}function _e(t,e,r,n){return{projectYaml:Gp(t,r,n),regimenYaml:Mp(t.automationLevel,e)}}function Op(){return`# codepipe project config is local to each member's workspace
96
+ `}function Ae(t,e,r,n){return{projectYaml:Wp(t,r,n),regimenYaml:qp(t.automationLevel,e)}}function Bp(){return`# codepipe project config is local to each member's workspace
97
97
  project.yaml
98
98
  regimen.yaml
99
99
 
100
100
  # codepipe runtime
101
101
  session.log
102
102
  apply-queue.json
103
- `}function Np(){return`# Index prompt
103
+ `}function Mp(){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 Up(t){return`# Project context for the CodePipe agent
160
+ `}function Gp(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 Lp(){return`# Knowledge
188
+ `}function Fp(){return`# Knowledge
189
189
 
190
190
  Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
191
191
  **memory** across tasks. Architectural decisions, domain rules,
@@ -202,7 +202,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
202
202
  concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
203
203
  REGENERATED from the entries by the index job: don't hand-edit it, and treat
204
204
  any merge conflict in it as noise (either side converges on the next run).
205
- `}function Dp(){return`# BUILD phase config. Discovered & maintained by the agent.
205
+ `}function Hp(){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 Bp(t,e){return`# ${e.name}
221
+ `}function Kp(t,e){return`# ${e.name}
222
222
 
223
223
  Context Repo for the **${t.name}** project (CodePipe).
224
224
 
@@ -244,7 +244,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
244
244
  pipeline \u2014 don't edit them by hand.
245
245
 
246
246
  Automation level: **${t.automationLevel}**.
247
- `}function Gp(t,e,r){let n=e?`
247
+ `}function Wp(t,e,r){let n=e?`
248
248
  tracker_url: ${e}`:`
249
249
  # tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
250
250
  assignee: ${r}`:`require_assignee: false
@@ -324,7 +324,7 @@ branch:
324
324
 
325
325
  repos:
326
326
  ${s}
327
- `}function Mp(t,e){let r=t==="full",n=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
327
+ `}function qp(t,e){let r=t==="full",n=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
328
328
  automation:
329
329
  level: ${t}
330
330
 
@@ -437,33 +437,33 @@ llm:
437
437
  # # the previous task's branch (auto-merge without reworking the
438
438
  # # tail of the chain).
439
439
  # mode: parallel
440
- `}function qp(t){return`codepipe/context-migration-v${t}`}function Yp(t){let e=fi(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(`
441
- `)}async function us(t,e,r,n){let o=lo(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Zr(t,e);if(!i.outdated)return i;let s=qp(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 Vp(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=Ke(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 d=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Yp(i)});return n.info(`[ctx] migration PR opened: ${d.url}`),{...i,migrationPrUrl:d.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 Vp(t,e,r,n,o,i,s){let a=lo(t),c=Hp(tn(Kp(),"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`},d=new Map(Ot(l,u).map(y=>[y.path,y.content])),p=0;for(let y of n.missingPaths){if(y===je)continue;let w=d.get(y);if(w==null){s.warn(`[ctx] migration: no template for ${y} \u2014 skipped`);continue}let b=tn(c,y);as(b)||(Fp(Wp(b),{recursive:!0}),ls(b,w),p++)}ls(tn(c,je),Br(n.currentVersion)),p++;let g=tn(c,lr);as(g)&&(cs(g,{force:!0}),p++);let f=lo(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${p} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),cs(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as Jp,readFileSync as zp,writeFileSync as Xp}from"node:fs";import{homedir as Qp}from"node:os";import{join as ps}from"node:path";import{parseDocument as Zp}from"yaml";function ed(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 td(t,e){let r=Zp(t);return r.set("repos",e.map(ed)),r.toString()}function rd(t,e){let r=[ps(Qp(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(ps(e,"project.yaml")),r}function fr(t,e,r){let n=[],o=[];for(let i of rd(t,r))if(Jp(i))try{let s=zp(i,"utf-8"),a=td(s,e);a!==s&&(Xp(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 nd}from"node:os";import{existsSync as od,mkdirSync as id}from"node:fs";import{join as uo}from"node:path";import{simpleGit as ms}from"simple-git";var ds=t=>console.log(t);function fs(t){ds=t}function mr(t,e="info"){ds(t,e)}function xe(t,e,r){let n=r??uo(nd(),".codepipe","repos");return uo(n,t,e)}async function rn(t,e,r={}){let n=xe(t,e.name,r.baseDir),o=r.cloneUrlOverride??po(e);if(!od(uo(n,".git"))){id(n,{recursive:!0});let a=ms();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}
442
- ${l.trim()}`)}}let i=ms(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
443
- ${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 gs=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function nn(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([...gs,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function hs(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 ys(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:d}=r,p=await hs(t,i,()=>nn(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));d&&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([...gs,"cherry-pick",p])}catch(b){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let h=b instanceof Error?b.message:String(b);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
444
- ${h.trim()}`)}}let y=(await t.revparse(["HEAD"])).trim(),w=d?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(w),await t.push([n,"--delete",o]).catch(()=>{}),{commit:y}}async function ws(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await hs(t,i,()=>nn(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 bs(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 po(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 sd,createDecipheriv as ad,createHash as cd,createPrivateKey as ld,createPublicKey as fo,diffieHellman as ks,generateKeyPairSync as $s,hkdfSync as xs,randomBytes as ud}from"node:crypto";var vs=Buffer.from("devpipe-sealedbox-v1","utf-8");function on(){let{publicKey:t,privateKey:e}=$s("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(cd("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function We(t,e){let r=fo({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=$s("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=ks({privateKey:o,publicKey:r}),c=Buffer.from(xs("sha256",a,Buffer.concat([i,s]),vs,32)),l=ud(12),u=sd("aes-256-gcm",c,l),d=typeof e=="string"?Buffer.from(e,"utf-8"):e,p=Buffer.concat([u.update(d),u.final()]),g=u.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:g.toString("base64"),ct:p.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function sn(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=ld({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=fo({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=fo(n).export({type:"spki",format:"der"}),a=ks({privateKey:n,publicKey:o}),c=Buffer.from(xs("sha256",a,Buffer.concat([i,s]),vs,32)),l=ad("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 pd(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 Ss(t,e,r,n){let o=pd(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=Yr(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=We(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 Ts}from"node:crypto";import{readFileSync as dd}from"node:fs";import Ze from"node:tls";var Is=typeof Ze.getCACertificates=="function"&&typeof Ze.setDefaultCACertificates=="function",Rs=!1,Cs=new Map,js=t=>console.warn(t);function fd(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Ps(t=js){if(Rs)return;Rs=!0;let e=L("EXTRA_CA_FILE");if(!(!e||!Is))try{let r=fd(dd(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 Es(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 md(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
445
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function gd(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 Ts(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function mo(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 hd(t){try{let e=await fetch(t);return e.ok?new Ts(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function As(t,e=443,r=js){let n=`${t}:${e}`,o=Cs.get(n);if(o)return o;let i=yd(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Cs.set(n,i),i}async function yd(t,e,r){if(!Is)return!1;let n=8e3;if(await mo(t,e,n))return!0;let o=await gd(t,e,n),i=Ze.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=md(o);if(!c)break;let l=await hd(c);if(!l)break;if(s.push(l.toString()),Ze.setDefaultCACertificates([...i,...s]),await mo(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 mo(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){Ps();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(Es(s)&&await As(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var _s=t=>new Promise(e=>setTimeout(e,t));function wd(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function bd(){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 go(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=bd(),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&&wd(l.status,u)){await _s(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await _s(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 Us(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",Os=new Map;async function kd(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Os.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 Os.set(o,l.id),l.id}async function Ls(t,e,r,n=hr){let o=await kd(t,e,r,n);await go(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 Ds(t,e,r){return await(await go(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Bs(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await go(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}var Ns=new Map;async function Gs(t,e){let r=Ns.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 Ns.set(e,i.id),i.id}async function Ms(t,e,r,n,o,i=hr){let s=await Gs(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 Fs(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 Hs="attachments(id,name,url,size,mimeType)",$d="links(direction,linkType(name),issues(idReadable))",Ks=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Hs},${$d}`,xd=`id,text,created,author(login),${Hs}`;function Ws(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 qs(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 an(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=${Ks}&$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=>Vs(c,r))}async function cn(t,e,r=hr){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Ks}`,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 Vs(await o.json(),r)}async function Ys(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${xd}&$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=Ws(s.attachments);return c&&(a.attachments=c),a})}function vd(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 Vs(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=Ws(t.attachments);a&&(s.attachments=a);let c=vd(t.links);return c&&(s.links=c),s}async function Js(t,e){let r=await Sd(t,e);return r.length>0?r:Rd(t,e)}async function Sd(t,e){let r=await Gs(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:zs(s.bundle)});return i}async function Rd(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:zs(s.projectCustomField?.bundle)});return i}function zs(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function ve(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Xs(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:ve(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:ve(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:ve(c)}),o.push({kind:"github",present:!0,ok:!1,detail:ve(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:ve(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:ve(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:ve(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:ve(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 en(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(d){n.push({name:`repo:${u.name}`,ok:!1,detail:ve(d)})}let l=e?.contextRepo;if(l?.host==="github")try{await en(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){n.push({name:"context-repo",ok:!1,detail:ve(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await en(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:ve(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 ho(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 ho(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://${mt}:${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 yo(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 Qs(t,e=process.env){return yo(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>yr(t,e),e)}function Zs(t,e=process.env){return yo(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>wr(t,e),e)}function ea(t,e=process.env){return yo(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${mt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>br(t,e),e)}function ta(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=on();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 ra(t,e,r,n){let o;try{o=JSON.parse(sn(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,Qs(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,Zs(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,ea(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 ho(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 Cd,readFileSync as Td,statSync as na}from"node:fs";var oa=2*1024*1024;function Id(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function ia(t,e){let r=He(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!Cd(r)||!na(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=na(r);if(n>oa)throw new Error(`file too large: ${e} is ${n} bytes (limit ${oa})`);let o=Td(r);return Id(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{existsSync as jd,readFileSync as Pd,writeFileSync as Ed}from"node:fs";import{join as Ad}from"node:path";import{parseDocument as _d}from"yaml";async function sa(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=yi(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=Ad(t,o);if(!jd(s))throw new Error(`${o} not found in context repo (${t})`);let a=_d(Pd(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);Ed(s,a.toString()),n.push(o)}return{files:n}}import{existsSync as wo,readFileSync as bo,writeFileSync as Od}from"node:fs";import{join as ln}from"node:path";import{parseDocument as ko}from"yaml";async function aa(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||e.backlogScope!==void 0){let i=ln(t,"project.yaml");if(!wo(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=ko(bo(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),e.backlogScope!==void 0&&(e.backlogScope==="personal"?s.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?s.setIn(["youtrack","backlog_scope"],"shared"):s.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=ln(t,"regimen.yaml");if(!wo(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=ko(bo(i,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&s.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;s.setIn(["youtrack","writes","enabled"],a.enabled===!0),s.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),s.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),s.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:s.toString()})}if(r.length===0)return{files:[]};for(let i of r)Od(ln(t,i.path),i.content);return{files:r.map(i=>i.path)}}function un(t){if(!t)return"Stage";try{let e=ln(t,"project.yaml");if(!wo(e))return"Stage";let n=ko(bo(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}import{existsSync as ca,readFileSync as Nd,readdirSync as Ud}from"node:fs";function Ld(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Md(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Dd(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Gd(Bd(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 pn(t,e,r){if(r.length===0)return;let n=Ld(t,e,r),o=r.map(i=>i.issue.key);await _t(t,n,`sync(${o.join(", ")}): task data`)}function Dd(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(`
446
- `)}function Bd(t,e,r){let n=new Map,o=He(t,`tasks/${e}/comments.jsonl`);if(ca(o))for(let i of Nd(o,"utf-8").split(`
447
- `)){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=Mr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Gd(t){return t.map(e=>JSON.stringify(e)).join(`
440
+ `}function Xp(t){return`codepipe/context-migration-v${t}`}function Qp(t){let e=gi(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 \`${Ie}\` 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(`
441
+ `)}async function fs(t,e,r,n){let o=uo(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Zr(t,e);if(!i.outdated)return i;let s=Xp(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 Zp(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=He(c),p=await l.findOpenPrByBranch?.(c,s)??null;if(p)return n.info(`[ctx] migration PR already open: ${p.url}`),{...i,migrationPrUrl:p.url};let d=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Qp(i)});return n.info(`[ctx] migration PR opened: ${d.url}`),{...i,migrationPrUrl:d.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 Zp(t,e,r,n,o,i,s){let a=uo(t),c=Vp(tn(Jp(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},p={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},d=new Map(Ot(l,p).map(w=>[w.path,w.content])),u=0;for(let w of n.missingPaths){if(w===Ie)continue;let b=d.get(w);if(b==null){s.warn(`[ctx] migration: no template for ${w} \u2014 skipped`);continue}let k=tn(c,w);us(k)||(Yp(zp(k),{recursive:!0}),ds(k,b),u++)}ds(tn(c,Ie),Br(n.currentVersion)),u++;let g=tn(c,lr);us(g)&&(ps(g,{force:!0}),u++);let f=uo(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${u} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),ps(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as ed,readFileSync as td,writeFileSync as rd}from"node:fs";import{homedir as nd}from"node:os";import{join as ms}from"node:path";import{parseDocument as od}from"yaml";function id(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 sd(t,e){let r=od(t);return r.set("repos",e.map(id)),r.toString()}function ad(t,e){let r=[ms(nd(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(ms(e,"project.yaml")),r}function fr(t,e,r){let n=[],o=[];for(let i of ad(t,r))if(ed(i))try{let s=td(i,"utf-8"),a=sd(s,e);a!==s&&(rd(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 cd}from"node:os";import{existsSync as ld,mkdirSync as ud}from"node:fs";import{join as po}from"node:path";import{simpleGit as ys}from"simple-git";var gs=t=>console.log(t);function hs(t){gs=t}function mr(t,e="info"){gs(t,e)}function xe(t,e,r){let n=r??po(cd(),".codepipe","repos");return po(n,t,e)}async function rn(t,e,r={}){let n=xe(t,e.name,r.baseDir),o=r.cloneUrlOverride??fo(e);if(!ld(po(n,".git"))){ud(n,{recursive:!0});let a=ys();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}
442
+ ${l.trim()}`)}}let i=ys(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
443
+ ${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 ws=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function nn(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([...ws,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function bs(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 ks(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:p,force:d}=r,u=await bs(t,i,()=>nn(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));d&&await t.raw(["branch","-D",a]).catch(()=>{});let g=`origin/${c}`;if(await gr(t,g)||(g=`origin/${p??c}`),(await t.revparse([g])).trim()===s)await t.raw(["branch","-f",a,u]),await t.checkout(a);else{await t.checkout(["-B",a,g]);try{await t.raw([...ws,"cherry-pick",u])}catch(k){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let h=k instanceof Error?k.message:String(k);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
444
+ ${h.trim()}`)}}let w=(await t.revparse(["HEAD"])).trim(),b=d?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(b),await t.push([n,"--delete",o]).catch(()=>{}),{commit:w}}async function $s(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,p=await bs(t,i,()=>nn(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,p]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:p,pushed:l}}async function xs(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 fo(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{createCipheriv as pd,createDecipheriv as dd,createHash as fd,createPrivateKey as md,createPublicKey as mo,diffieHellman as vs,generateKeyPairSync as Ss,hkdfSync as Rs,randomBytes as gd}from"node:crypto";var Cs=Buffer.from("devpipe-sealedbox-v1","utf-8");function on(){let{publicKey:t,privateKey:e}=Ss("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ce(t){let e=Buffer.from(t,"base64");return(fd("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Ke(t,e){let r=mo({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Ss("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=vs({privateKey:o,publicKey:r}),c=Buffer.from(Rs("sha256",a,Buffer.concat([i,s]),Cs,32)),l=gd(12),p=pd("aes-256-gcm",c,l),d=typeof e=="string"?Buffer.from(e,"utf-8"):e,u=Buffer.concat([p.update(d),p.final()]),g=p.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:g.toString("base64"),ct:u.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function sn(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=md({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=mo({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=mo(n).export({type:"spki",format:"der"}),a=vs({privateKey:n,publicKey:o}),c=Buffer.from(Rs("sha256",a,Buffer.concat([i,s]),Cs,32)),l=dd("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 hd(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 Ts(t,e,r,n){let o=hd(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=Yr(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=Ke(a.publicKey,i)}catch(p){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${p instanceof Error?p.message:String(p)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}import{X509Certificate as Ps}from"node:crypto";import{readFileSync as yd}from"node:fs";import Ze from"node:tls";var Es=typeof Ze.getCACertificates=="function"&&typeof Ze.setDefaultCACertificates=="function",Is=!1,js=new Map,As=t=>console.warn(t);function wd(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function _s(t=As){if(Is)return;Is=!0;let e=L("EXTRA_CA_FILE");if(!(!e||!Es))try{let r=wd(yd(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 Os(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 bd(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
445
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function kd(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 Ps(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function go(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 $d(t){try{let e=await fetch(t);return e.ok?new Ps(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ns(t,e=443,r=As){let n=`${t}:${e}`,o=js.get(n);if(o)return o;let i=xd(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return js.set(n,i),i}async function xd(t,e,r){if(!Es)return!1;let n=8e3;if(await go(t,e,n))return!0;let o=await kd(t,e,n),i=Ze.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=bd(o);if(!c)break;let l=await $d(c);if(!l)break;if(s.push(l.toString()),Ze.setDefaultCACertificates([...i,...s]),await go(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 go(t,e,n)}function _e(){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){_s();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(Os(s)&&await Ns(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var Us=t=>new Promise(e=>setTimeout(e,t));function vd(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Sd(){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 ho(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Sd(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await ye(t,r,n)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(l){if(l.ok)return l;let p=await l.text();if(c<o&&vd(l.status,p)){await Us(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<o){await Us(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 Bs(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",Ds=new Map;async function Rd(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Ds.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(p=>p.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(p=>p.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return Ds.set(o,l.id),l.id}async function Ms(t,e,r,n=hr){let o=await Rd(t,e,r,n);await ho(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 Gs(t,e,r){return await(await ho(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Fs(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await ho(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}var Ls=new Map;async function Hs(t,e){let r=Ls.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 Ls.set(e,i.id),i.id}async function Ks(t,e,r,n,o,i=hr){let s=await Hs(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 Ws(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 qs="attachments(id,name,url,size,mimeType)",Cd="links(direction,linkType(name),issues(idReadable))",Ys=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${qs},${Cd}`,Td=`id,text,created,author(login),${qs}`;function Vs(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 Js(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 an(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=${Ys}&$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=>Xs(c,r))}async function cn(t,e,r=hr){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Ys}`,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 Xs(await o.json(),r)}async function zs(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Td}&$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=Vs(s.attachments);return c&&(a.attachments=c),a})}function Id(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 Xs(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=Vs(t.attachments);a&&(s.attachments=a);let c=Id(t.links);return c&&(s.links=c),s}async function Qs(t,e){let r=await jd(t,e);return r.length>0?r:Pd(t,e)}async function jd(t,e){let r=await Hs(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:Zs(s.bundle)});return i}async function Pd(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:Zs(s.projectCustomField?.bundle)});return i}function Zs(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function ve(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function ea(t,e){let r=D(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:ve(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:ve(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:ve(c)}),o.push({kind:"github",present:!0,ok:!1,detail:ve(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:ve(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:ve(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:ve(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:ve(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 p of e?.repos??[])if(p.host==="github")try{await en(c,p.owner,p.repoName),n.push({name:`repo:${p.name}`,ok:!0})}catch(d){n.push({name:`repo:${p.name}`,ok:!1,detail:ve(d)})}let l=e?.contextRepo;if(l?.host==="github")try{await en(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(p){n.push({name:"context-repo",ok:!1,detail:ve(p)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await en(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:ve(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 yo(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 yo(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://${mt}:${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 wo(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 ta(t,e=process.env){return wo(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>yr(t,e),e)}function ra(t,e=process.env){return wo(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>wr(t,e),e)}function na(t,e=process.env){return wo(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${mt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>br(t,e),e)}function oa(t){let e=D(t);if(!e)return null;if(!e.sealKey){let r=on();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},Y(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ce(e.sealKey.publicKey)}}async function ia(t,e,r,n){let o;try{o=JSON.parse(sn(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=D(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,ta(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,ra(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,na(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 yo(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){Y(t),e()}import{existsSync as Ed,readFileSync as Ad,statSync as sa}from"node:fs";var aa=2*1024*1024;function _d(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function ca(t,e){let r=Fe(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!Ed(r)||!sa(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=sa(r);if(n>aa)throw new Error(`file too large: ${e} is ${n} bytes (limit ${aa})`);let o=Ad(r);return _d(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{existsSync as Od,readFileSync as Nd,writeFileSync as Ud}from"node:fs";import{join as Dd}from"node:path";import{parseDocument as Ld}from"yaml";async function la(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=bi(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=Dd(t,o);if(!Od(s))throw new Error(`${o} not found in context repo (${t})`);let a=Ld(Nd(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);Ud(s,a.toString()),n.push(o)}return{files:n}}import{existsSync as Bd,readFileSync as Md,writeFileSync as Gd}from"node:fs";import{join as Fd}from"node:path";import{isMap as ua,parseDocument as Hd}from"yaml";async function pa(t,e){let r=e.repoName?.trim(),n=e.defaultBranch?.trim();if(!r)throw new Error("repoName must be a non-empty string");if(!n||!ki(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=Fd(t,"project.yaml");if(!Bd(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Hd(Md(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>ua(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!ua(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),Gd(o,i.toString()),{repoName:r,defaultBranch:n}}import{existsSync as bo,readFileSync as ko,writeFileSync as Kd}from"node:fs";import{join as ln}from"node:path";import{parseDocument as $o}from"yaml";async function da(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||e.backlogScope!==void 0){let i=ln(t,"project.yaml");if(!bo(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=$o(ko(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),e.backlogScope!==void 0&&(e.backlogScope==="personal"?s.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?s.setIn(["youtrack","backlog_scope"],"shared"):s.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=ln(t,"regimen.yaml");if(!bo(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=$o(ko(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)Kd(ln(t,i.path),i.content);return{files:r.map(i=>i.path)}}function un(t){if(!t)return"Stage";try{let e=ln(t,"project.yaml");if(!bo(e))return"Stage";let n=$o(ko(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}import{existsSync as fa,readFileSync as Wd,readdirSync as qd}from"node:fs";function Yd(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Xd(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Vd(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:zd(Jd(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 pn(t,e,r){if(r.length===0)return;let n=Yd(t,e,r),o=r.map(i=>i.issue.key);await _t(t,n,`sync(${o.join(", ")}): task data`)}function Vd(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(`
446
+ `)}function Jd(t,e,r){let n=new Map,o=Fe(t,`tasks/${e}/comments.jsonl`);if(fa(o))for(let i of Wd(o,"utf-8").split(`
447
+ `)){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 zd(t){return t.map(e=>JSON.stringify(e)).join(`
448
448
  `)+(t.length>0?`
449
- `:"")}function Md(t,e,r){let n=[],o=He(t,`tasks/${e}/attachments`);if(ca(o))for(let i of Ud(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var dn=new Map;async function $o(t,e){let n=(dn.get(t)??Promise.resolve()).catch(()=>{}).then(e);dn.set(t,n);try{return await n}finally{dn.get(t)===n&&dn.delete(t)}}async function la(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 $o(`${i}/${r.name}`,async()=>{let s=await rn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{commit:c}=await ys(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 re({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 $o(`${i}/${r.name}`,async()=>{let s=await rn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{commit:c,pushed:l}=await ws(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return re({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return q("no repo spec");let i=Ke(r),s=await i.createPullRequest(r,e);return re({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return q("no repo spec");let i=Ke(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return re({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return q("no repo spec");let i=Ke(r);return await i.closePR(r,e.prNumber,e.comment),re({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return $o(`${i}/${r.name}`,async()=>{let s=await rn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{mergedSha:c}=await bs(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return re({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return re({stub:!0});case"tracker_status":{let i=Oe();return i?t.trackerIssueId?(await Ls(i,t.trackerIssueId,e.newStatus,un(t.contextDir)),re({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 Ds(i,t.trackerIssueId,e.body);return re({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 Ms(i,e.projectKey,e.title,e.body,e.targetStatus,un(t.contextDir));return re({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 Fs(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 re({applied:s})}case"set_project_setting":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await sa(t.contextDir,e.edits);return re({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=un(t.contextDir);await Bs(i,e.issueKey,{...e.title!==void 0?{summary:e.title}:{},...e.body!==void 0?{description:e.body}:{}});let a=await cn(i,e.issueKey,s);return a&&await pn(t.contextDir,e.projectId,[{issue:a,comments:[],attachments:[]}]),re({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await aa(t.contextDir,e);return re({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),re({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 re({outdated:i.outdated,templateVersion:i.templateVersion})}case"read_context_file":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=ia(t.contextDir,e.path);return re({path:e.path,...i})}default:return q(`unsupported action type: ${e.type}`)}}catch(i){return q(i instanceof Error?i.message:String(i))}}function re(t){return{status:"done",result:t}}function q(t){return{status:"failed",error:t}}import{existsSync as Ca,readFileSync as Ta}from"node:fs";import{join as Ia}from"node:path";import{homedir as Fd}from"node:os";import{existsSync as Hd,mkdirSync as Kd,readFileSync as Wd,writeFileSync as qd}from"node:fs";import{dirname as Yd,join as Vd}from"node:path";function xo(){return L("FARM_PINS")??Vd(Fd(),".codepipe","farm-pins.json")}function ua(){let t=xo();if(!Hd(t))return{};try{return JSON.parse(Wd(t,"utf-8"))}catch{return{}}}function Jd(t){let e=xo();Kd(Yd(e),{recursive:!0}),qd(e,JSON.stringify(t,null,2)+`
450
- `,{mode:384})}function zd(t){return ua()[t]}function fn(t,e){let r=ua();r[t]=e,Jd(r)}function mn(t,e){let r=ae(e),n=zd(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 ${xo()}.`);return r}import Xd from"ws";function gn(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Xd(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 pa(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 hn(t,e,r,n){return Se(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function da(t,e,r,n){return Se(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function fa(t,e,r,n){return Se(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function ma(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 yn(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 ga(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 ha(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 ya(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 wa(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 ba(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 ka(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function $a(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function xa(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 $r(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function vo(t,e,r,n){await Se(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Sa(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Ra(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 ja(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)");mn(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=Ia(r,"project.yaml"),g=Ia(r,"regimen.yaml");Ca(p)&&Ca(g)?c={projectYaml:Ta(p,"utf-8"),regimenYaml:Ta(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=We(e.farmPublicKey,JSON.stringify(l));fn(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let d=await hn(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return d.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...d.daemonStatus?{daemonStatus:d.daemonStatus}:{}}:o(d.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 Zd,mkdirSync as ef,readFileSync as tf,writeFileSync as rf}from"node:fs";import{dirname as nf,join as of}from"node:path";function So(){return L("RUNNER_PINS")??of(Qd(),".codepipe","runner-pins.json")}function Pa(){let t=So();if(!Zd(t))return{};try{return JSON.parse(tf(t,"utf-8"))}catch{return{}}}function sf(t){let e=So();ef(nf(e),{recursive:!0}),rf(e,JSON.stringify(t,null,2)+`
451
- `,{mode:384})}function af(t){return Pa()[t]}function Ro(t,e){let r=Pa();r[t]=e,sf(r)}function Ea(t,e){let r=ae(e),n=af(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 ${So()}.`);return r}var _a=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Aa(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:_a(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 cf={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:_a(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)=>Aa(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Aa(t,e,r,"remove-token")},Oa={api:cf,fetchProject:M,provisionOnRunner:da,teardownOnRunner:fa};async function Na(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)");Ea(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 Ua(t,e,r,n=Oa){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 Na(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=We(e.runnerPublicKey,JSON.stringify(l));Ro(e.runnerId,e.fingerprint),r.info(`[ghr] ${c.length} registration token(s) sealed for runner host ${e.runnerName} \u2014 handing off`);let d=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:d.ok,...d.runners?{runners:d.runners}:{},...d.error?{error:d.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function La(t,e,r,n=Oa){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 Na(t,e,n),a=[];for(let d of s)try{a.push({owner:d.owner,repo:d.repoName,removeToken:await n.api.mintRemoveToken(i,d.owner,d.repoName)})}catch(p){r.warn(`[ghr] remove-token for ${d.owner}/${d.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`),a.push({owner:d.owner,repo:d.repoName})}let c={projectId:t.projectId,runners:a},l=We(e.runnerPublicKey,JSON.stringify(c));Ro(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 wn=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=Ke(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 yt){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=Ke(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=lf(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function lf(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var bn=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 x=e.stageField?{stageField:e.stageField}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{};if((e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn){let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[]])],[m,T]=await Promise.all([v.length>0?an(r,{projectKey:e.projectKey,columns:v,...x,...S}):Promise.resolve([]),an(r,{projectKey:e.projectKey,columns:[e.backlogColumn],...x})]),k=new Map;for(let R of[...m,...T])k.set(R.id,R);o=[...k.values()]}else{let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await an(r,{projectKey:e.projectKey,columns:v,...x,...S})}}catch(x){this.log.warn(`[yt-sync] listIssues failed: ${x instanceof Error?x.message:String(x)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let x of o){if(s.add(x.id),a.has(x.status))continue;let S=await Ba(r,x.id,e.sinceMs,this.log);S&&i.set(x.id,S)}let c=[];for(let x of e.offBoardIssueIds){if(s.has(x))continue;let S=await Ba(r,x,e.sinceMs,this.log);if(S&&S.length>0&&i.set(x,S),e.requireAssignee||S&&S.length>0){let N=await df(r,x,e.stageField,this.log);if(N)c.push(N);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(x=>!a.has(x.status)),{attachmentsByIssue:u,attachmentKeys:d}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let p=[...l,...c].map(x=>({issue:x,comments:i.get(x.id)??[],attachments:u.get(x.id)??[]}));try{await pn(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let x of d)this.shippedAttachments.add(x)}catch(x){let S=x instanceof Error?x.message:String(x);this.abandonTick(`context task sync failed: ${S}`);return}let g=this.options.isSelfComment??(()=>!1),f=[],y=[];for(let[x,S]of i){let N=S.filter(v=>!g(v.id));if(N.length===0)continue;f.push({issueId:x,comments:N.map(uf)});let I=N.flatMap(v=>{let m=Mr(v.body);return m?[{commentId:v.id,author:v.author,name:m.name,args:m.args,createdAt:v.createdAt}]:[]});I.length>0&&y.push({issueId:x,commands:I})}let w={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Da),commentsBatch:f,...y.length>0?{commandsBatch:y}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Da)}:{},observedAtMs:n};this.send(w);let b=f.reduce((x,S)=>x+S.comments.length,0),h=y.reduce((x,S)=>x+S.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${b} commands=${h} (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 d=`${s.id}:${u.id}`;if(this.shippedAttachments.has(d))continue;let p;try{p=await qs(n,u.url)}catch(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let g=pf(u.name);l.has(g)&&(g=`${u.id}-${g}`),l.add(g),c.push({name:g,contentBase64:p.toString("base64")}),i.push(d)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Da(t){let{description:e,...r}=t;return r}function uf(t){let{body:e,...r}=t;return r}function pf(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 df(t,e,r,n){try{return await cn(t,e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Ba(t,e,r,n){try{return await Ys(t,e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Co="npm i -g @code-partner/codepipe@latest";function kn(t,e={}){let r=e.log??{info:f=>console.log(f),warn:f=>console.warn(f)};r.info(`codepipe-cli v${me} (protocol ${Ie})`);let n=f=>e.onEvent?.(f),o=e.workspace;o?.contextDir&&Vi(o.contextDir,r);let i=Ga("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Ga("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let f=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(f)&&f>0?f*1e3:6e5})(),c=!1,l=!1,u=new Set,d=new Set,p=g();function g(){let f=gn(t.hubUrl,t.cliToken),y=null,w=new wn(i,m=>{f.readyState===f.OPEN&&f.send(JSON.stringify(m))},r),b=new bn(s,m=>{f.readyState===f.OPEN&&f.send(JSON.stringify(m))},r,{contextDir:o?.contextDir??null,isSelfComment:m=>d.has(m)}),h=null,x=async()=>{try{let m;try{let R=await M(t.hubUrl,t.cliToken,t.projectId);m={repos:R.repos,contextRepo:R.contextRepo}}catch(R){r.warn(`[readiness] could not fetch project summary for push checks: ${R instanceof Error?R.message:String(R)}`)}let T=await Xs(t.projectId,m);if(f.readyState!==f.OPEN)return;let k={type:"cli_readiness",projectId:t.projectId,ready:T.ready,checks:T.checks,creds:T.creds,checkedAt:T.checkedAt};if(f.send(JSON.stringify(k)),T.ready)r.info("[readiness] ready");else{let R=T.checks.filter(P=>!P.ok).map(P=>`${P.name}(${P.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${R.join(", ")}`)}}catch(m){r.warn(`[readiness] check failed: ${m instanceof Error?m.message:String(m)}`)}},S=()=>{x(),h=setInterval(()=>void x(),a),typeof h.unref=="function"&&h.unref()},N=()=>{h&&(clearInterval(h),h=null)},I=o?.contextDir?new Xr(o.contextDir,t.projectId,m=>{f.readyState===f.OPEN&&f.send(JSON.stringify(m))},r):null,v=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 k=await us(m,t.projectId,T,r);return f.readyState===f.OPEN&&f.send(JSON.stringify(k)),k};return f.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let m=Ki(t.projectId),T=L("ORIGIN")==="farm"?"farm":"local",k=L("FARM_ID"),R=t.accountEmail??m.email,P;try{let j=ta(t.projectId);j&&(P=j.publicKey,r.info(`[cred-channel] key fingerprint: ${j.fingerprint}`))}catch(j){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${j instanceof Error?j.message:String(j)}`)}let $={type:"register",projectId:t.projectId,platformVersion:me,protocolVersion:Ie,accountId:m.accountId,accountLabel:m.label,origin:T,inFlightActionIds:[...u],...R?{accountEmail:R}:{},...T==="farm"&&k?{farmId:k}:{},...P?{sealPublicKey:P}:{}};f.send(JSON.stringify($))}),f.on("message",async m=>{let T=m.toString("utf-8");if(T==="pong"||T==="ping")return;let k;try{k=JSON.parse(T)}catch{return}if(!k||typeof k!="object")return;let R=k.type;if(R==="registered"){let $=k;if($.ok){if(r.info(`[ws] registered for project ${$.projectId}`),n({kind:"registered",projectId:$.projectId??t.projectId}),w.start(),I?.start(),S(),To(t,o,r),o?.contextDir)try{let j=Zr(o.contextDir,t.projectId);f.readyState===f.OPEN&&f.send(JSON.stringify(j)),j.outdated&&(r.warn(`[ctx] context format outdated: v${j.templateVersion} \u2192 v${j.currentVersion}`+(j.missingPaths.length>0?` (missing: ${j.missingPaths.join(", ")})`:"")),l||(l=!0,v().catch(()=>{})))}catch(j){r.warn(`[ctx] context-format detect failed (non-fatal): ${j instanceof Error?j.message:String(j)}`)}}else r.warn(`[ws] register rejected: ${$.reason??"unknown"}`),n({kind:"register_rejected",reason:$.reason??"unknown"}),c=!0,f.close();return}if(R==="hello"){let $=k;y=Dr($.protocolVersion);let j=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${j}`),y||(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: ${Co}`),n({kind:"incompatible",hubVersion:typeof $.platformVersion=="string"?$.platformVersion:null,hubProtocol:typeof $.protocolVersion=="number"?$.protocolVersion:null,updateCommand:Co}));return}if(R==="tracking_targets"){w.setTargets(k.targets);return}if(R==="youtrack_sync_request"){b.setRequest(k);return}if(R==="youtrack_force_sync"){b.forceSync();return}if(R==="sync_local"){await yf(k,o,f,r);return}if(R==="provision_repo"){let $=k;r.info(`[repo] provision_repo: ${$.repo.name} (${$.repo.host}:${$.repo.owner}/${$.repo.repoName})`),await gf(t,o,$.repo,r),await To(t,o,r);return}if(R==="remove_repo"){let $=k;r.info(`[repo] remove_repo: ${$.repoName}${$.purge?" (purge)":""}`),await To(t,o,r),$.purge&&hf(t,o,$.repoName,r);return}if(R==="context_write"){await wf(k,o,f,r);return}if(R==="adr_promote"){await bf(k,o,f,r);return}if(R==="cred_update"){let $=k,j=U(t.projectId),D=j?.sealKey?await ra(t.projectId,$.kind,$.sealed,j.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},K={type:"cred_update_result",updateId:$.updateId,projectId:t.projectId,ok:D.ok,...D.detail?{detail:D.detail}:{}};f.readyState===f.OPEN&&f.send(JSON.stringify(K)),D.ok?(r.info(`[cred] ${$.kind} replaced${D.detail?` \u2014 ${D.detail}`:""}`),x()):r.warn(`[cred] ${$.kind} replacement rejected: ${D.detail??"unknown"}`);return}if(R==="move_to_farm"){let $=k;r.info(`[farm-move] request to move ${t.projectId} onto farm ${$.farmName} (${$.farmId})`);let j=await ja(t,$,o?.contextDir,r);f.readyState===f.OPEN&&f.send(JSON.stringify(j)),j.ok?r.info(`[farm-move] done \u2014 farm daemon ${j.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${j.error??"unknown error"}`);return}if(R==="gh_runner_setup"){let $=k;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${$.runnerName} (${$.runnerId})`);let j=await Ua(t,$,r);f.readyState===f.OPEN&&f.send(JSON.stringify(j)),j.ok?r.info(`[ghr] runners connected on ${$.runnerName}`):r.warn(`[ghr] setup failed: ${j.error??"see per-repo statuses"}`);return}if(R==="gh_runner_teardown"){let $=k;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${$.runnerName} (${$.runnerId})`);let j=await La(t,$,r);f.readyState===f.OPEN&&f.send(JSON.stringify(j)),j.ok?r.info(`[ghr] runners disconnected from ${$.runnerName}`):r.warn(`[ghr] teardown failed: ${j.error??"unknown error"}`);return}if(R==="tracker_fields_request"){let $=k,j={type:"tracker_fields_result",requestId:$.requestId,projectId:t.projectId,ok:!1},D=Oe();if(!D)j.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{j.fields=await Js(D,$.projectKey),j.ok=!0}catch(K){j.error=K instanceof Error?K.message:String(K)}f.readyState===f.OPEN&&f.send(JSON.stringify(j)),j.ok||r.warn(`[yt-fields] listing failed: ${j.error??"unknown"}`);return}if(R==="sandbox_keys"){let $=U(t.projectId);if(!$){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let j=Tt(t.projectId),D=Ss(k,$,j,r);for(let K of D)f.readyState===f.OPEN&&f.send(JSON.stringify(K));return}if(R!=="dispatch_action")return;let P=k;if(y===!1){let $=`refused: HUB protocol incompatible with CLI v${me} (protocol ${Ie})`;f.send(JSON.stringify({type:"action_result",actionId:P.actionId,status:"failed",error:$})),r.warn(`[exec] ${P.actionId} (${P.action.type}) \u2192 REFUSED: ${$}`),r.warn(`[exec] update the CLI to clear this: ${Co}`),n({kind:"action",actionId:P.actionId,actionType:P.action.type,ok:!1,error:$});return}u.add(P.actionId);try{let $=await la({action:P.action,repo:P.repo,trackerIssueId:P.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:I?()=>I.reportNow():void 0,refreshContextStatus:o?.contextDir?v:void 0}).catch(K=>({status:"failed",error:K instanceof Error?K.message:String(K)}));P.action.type==="tracker_comment"&&$.status==="done"&&"result"in $&&typeof $.result?.commentId=="string"&&d.add($.result.commentId),f.send(JSON.stringify({type:"action_result",actionId:P.actionId,...$}));let j=$.status!=="failed",D=!j&&"error"in $?$.error:void 0;j?r.info(`[exec] ${P.actionId} (${P.action.type}) \u2192 done`):r.warn(`[exec] ${P.actionId} (${P.action.type}) \u2192 FAILED: ${D??"?"}`),n({kind:"action",actionId:P.actionId,actionType:P.action.type,ok:j,...D?{error:D}:{}})}finally{u.delete(P.actionId)}}),f.on("close",(m,T)=>{let k=T?.toString("utf-8")??"";if(r.info(`[ws] closed code=${m}${k?` reason=${k}`:""}`),w.stop(),b.stop(),I?.stop(),N(),k==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:m}),!c&&setTimeout(()=>{p=g()},2e3)}),f.on("error",m=>r.warn(`[ws] error: ${m.message}`)),f}return{stop(){c=!0,p.close()}}}async function To(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 gf(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?xr(e.root,o):xe(t.projectId,r.name);if(Ma(xr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await mf().clone(po(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 hf(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?xr(e.root,o):xe(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Ma(xr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{ff(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 yf(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=xr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Wi(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 wf(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 bf(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=t.source??"task",s=await ts(e.contextDir,t.taskKey,t.slugs,void 0,i);if(n.info(`[adr] adr_promote ${t.id}: promoted ${s.promoted.length}, skipped ${s.skipped.length}`+(s.promoted.length>0?` (${s.promoted.join(", ")})`:"")),s.missing.length>0){let a=l=>i==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${s.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);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 Ga(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Va,mkdirSync as Ja}from"node:fs";import{dirname as za}from"node:path";import{simpleGit as Ut}from"simple-git";import{execFileSync as kf}from"node:child_process";import{mkdtempSync as $f,mkdirSync as xf,readFileSync as Fa,rmSync as vf,writeFileSync as Sf}from"node:fs";import{tmpdir as Rf}from"node:os";import{dirname as Cf,join as Ha}from"node:path";function Ka(t="codepipe-context"){let e=$f(Ha(Rf(),"codepipe-ssh-")),r=Ha(e,"id_ed25519");try{return kf("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Fa(r,"utf-8"),publicKey:Fa(`${r}.pub`,"utf-8").trim()}}finally{vf(e,{recursive:!0,force:!0})}}async function Wa(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 qa(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 Ya(t,e){xf(Cf(t),{recursive:!0});let r=e.endsWith(`
449
+ `:"")}function Xd(t,e,r){let n=[],o=Fe(t,`tasks/${e}/attachments`);if(fa(o))for(let i of qd(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var dn=new Map;async function xo(t,e){let n=(dn.get(t)??Promise.resolve()).catch(()=>{}).then(e);dn.set(t,n);try{return await n}finally{dn.get(t)===n&&dn.delete(t)}}async function ma(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 K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return xo(`${i}/${r.name}`,async()=>{let s=await rn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{commit:c}=await ks(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return Z({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return xo(`${i}/${r.name}`,async()=>{let s=await rn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{commit:c,pushed:l}=await $s(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return Z({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return K("no repo spec");let i=He(r),s=await i.createPullRequest(r,e);return Z({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return K("no repo spec");let i=He(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return Z({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return K("no repo spec");let i=He(r);return await i.closePR(r,e.prNumber,e.comment),Z({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return xo(`${i}/${r.name}`,async()=>{let s=await rn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{mergedSha:c}=await xs(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return Z({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return Z({stub:!0});case"tracker_status":{let i=_e();return i?t.trackerIssueId?(await Ms(i,t.trackerIssueId,e.newStatus,un(t.contextDir)),Z({issueId:t.trackerIssueId,newStatus:e.newStatus})):K("no tracker_issue_id provided"):K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=_e();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return K("no tracker_issue_id provided");let s=await Gs(i,t.trackerIssueId,e.body);return Z({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=_e();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return K("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Ks(i,e.projectKey,e.title,e.body,e.targetStatus,un(t.contextDir));return Z({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=_e();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Ws(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return K(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return Z({applied:s})}case"set_project_setting":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await la(t.contextDir,e.edits);return Z({files:i.files})}case"tracker_edit":{let i=_e();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.contextDir)return K("no context repo clone on this CLI");let s=un(t.contextDir);await Fs(i,e.issueKey,{...e.title!==void 0?{summary:e.title}:{},...e.body!==void 0?{description:e.body}:{}});let a=await cn(i,e.issueKey,s);return a&&await pn(t.contextDir,e.projectId,[{issue:a,comments:[],attachments:[]}]),Z({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await da(t.contextDir,e);return Z({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await pa(t.contextDir,e);return Z({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),Z({reported:!0})):K("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return K("no context repo clone on this CLI");let i=await t.refreshContextStatus();return Z({outdated:i.outdated,templateVersion:i.templateVersion})}case"read_context_file":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=ca(t.contextDir,e.path);return Z({path:e.path,...i})}default:return K(`unsupported action type: ${e.type}`)}}catch(i){return K(i instanceof Error?i.message:String(i))}}function Z(t){return{status:"done",result:t}}function K(t){return{status:"failed",error:t}}import{existsSync as Ea,readFileSync as Aa}from"node:fs";import{join as _a}from"node:path";import{homedir as Qd}from"node:os";import{existsSync as Zd,mkdirSync as ef,readFileSync as tf,writeFileSync as rf}from"node:fs";import{dirname as nf,join as of}from"node:path";function vo(){return L("FARM_PINS")??of(Qd(),".codepipe","farm-pins.json")}function ga(){let t=vo();if(!Zd(t))return{};try{return JSON.parse(tf(t,"utf-8"))}catch{return{}}}function sf(t){let e=vo();ef(nf(e),{recursive:!0}),rf(e,JSON.stringify(t,null,2)+`
450
+ `,{mode:384})}function af(t){return ga()[t]}function fn(t,e){let r=ga();r[t]=e,sf(r)}function mn(t,e){let r=ce(e),n=af(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 ${vo()}.`);return r}import cf from"ws";function gn(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new cf(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 ha(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 hn(t,e,r,n){return Se(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function ya(t,e,r,n){return Se(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function wa(t,e,r,n){return Se(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function ba(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 yn(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 ka(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 $a(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 xa(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 va(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 Sa(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 Ra(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Ca(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function Ta(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function Ia(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function $r(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function So(t,e,r,n){await Se(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function ja(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Pa(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 F(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 Oa(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=ce(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");mn(e.farmId,e.farmPublicKey);let s=D(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await F(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=_a(r,"project.yaml"),g=_a(r,"regimen.yaml");Ea(u)&&Ea(g)?c={projectYaml:Aa(u,"utf-8"),regimenYaml:Aa(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}:{}},p=Ke(e.farmPublicKey,JSON.stringify(l));fn(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let d=await hn(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:p});return d.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...d.daemonStatus?{daemonStatus:d.daemonStatus}:{}}:o(d.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}import{homedir as lf}from"node:os";import{existsSync as uf,mkdirSync as pf,readFileSync as df,writeFileSync as ff}from"node:fs";import{dirname as mf,join as gf}from"node:path";function Ro(){return L("RUNNER_PINS")??gf(lf(),".codepipe","runner-pins.json")}function Na(){let t=Ro();if(!uf(t))return{};try{return JSON.parse(df(t,"utf-8"))}catch{return{}}}function hf(t){let e=Ro();pf(mf(e),{recursive:!0}),ff(e,JSON.stringify(t,null,2)+`
451
+ `,{mode:384})}function yf(t){return Na()[t]}function Co(t,e){let r=Na();r[t]=e,hf(r)}function Ua(t,e){let r=ce(e),n=yf(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 ${Ro()}.`);return r}var La=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Da(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:La(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 wf={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:La(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)=>Da(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Da(t,e,r,"remove-token")},Ba={api:wf,fetchProject:F,provisionOnRunner:ya,teardownOnRunner:wa};async function Ma(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(ce(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Ua(e.runnerId,e.runnerPublicKey);let i=D(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 Ga(t,e,r,n=Ba){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 Ma(t,e,n),a=[];for(let u of s)await n.api.repoHasAdmin(i,u.owner,u.repoName)||a.push(`${u.owner}/${u.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 u of s)c.push({owner:u.owner,repo:u.repoName,regToken:await n.api.mintRegistrationToken(i,u.owner,u.repoName)});let l={projectId:t.projectId,runners:c},p=Ke(e.runnerPublicKey,JSON.stringify(l));Co(e.runnerId,e.fingerprint),r.info(`[ghr] ${c.length} registration token(s) sealed for runner host ${e.runnerName} \u2014 handing off`);let d=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:p});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:d.ok,...d.runners?{runners:d.runners}:{},...d.error?{error:d.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function Fa(t,e,r,n=Ba){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 Ma(t,e,n),a=[];for(let d of s)try{a.push({owner:d.owner,repo:d.repoName,removeToken:await n.api.mintRemoveToken(i,d.owner,d.repoName)})}catch(u){r.warn(`[ghr] remove-token for ${d.owner}/${d.repoName} failed (${u instanceof Error?u.message:u}) \u2014 the runner host will force-remove`),a.push({owner:d.owner,repo:d.repoName})}let c={projectId:t.projectId,runners:a},l=Ke(e.runnerPublicKey,JSON.stringify(c));Co(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle sealed for runner host ${e.runnerName} \u2014 handing off`);let p=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:p.ok,...p.error?{error:p.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var wn=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=He(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 yt){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=He(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=bf(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function bf(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var bn=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=_e();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 $=e.stageField?{stageField:e.stageField}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{};if((e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn){let E=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[]])],[j,R]=await Promise.all([E.length>0?an(r,{projectKey:e.projectKey,columns:E,...$,...S}):Promise.resolve([]),an(r,{projectKey:e.projectKey,columns:[e.backlogColumn],...$})]),m=new Map;for(let C of[...j,...R])m.set(C.id,C);o=[...m.values()]}else{let E=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await an(r,{projectKey:e.projectKey,columns:E,...$,...S})}}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 S=await Ka(r,$.id,e.sinceMs,this.log);S&&i.set($.id,S)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let S=await Ka(r,$,e.sinceMs,this.log);if(S&&S.length>0&&i.set($,S),e.requireAssignee||S&&S.length>0){let U=await xf(r,$,e.stageField,this.log);if(U)c.push(U);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter($=>!a.has($.status)),{attachmentsByIssue:p,attachmentKeys:d}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let u=[...l,...c].map($=>({issue:$,comments:i.get($.id)??[],attachments:p.get($.id)??[]}));try{await pn(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let $ of d)this.shippedAttachments.add($)}catch($){let S=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${S}`);return}let g=this.options.isSelfComment??(()=>!1),f=[],w=[];for(let[$,S]of i){let U=S.filter(E=>!g(E.id));if(U.length===0)continue;f.push({issueId:$,comments:U.map(kf)});let I=U.flatMap(E=>{let j=Gr(E.body);return j?[{commentId:E.id,author:E.author,name:j.name,args:j.args,createdAt:E.createdAt}]:[]});I.length>0&&w.push({issueId:$,commands:I})}let b={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Ha),commentsBatch:f,...w.length>0?{commandsBatch:w}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Ha)}:{},observedAtMs:n};this.send(b);let k=f.reduce(($,S)=>$+S.comments.length,0),h=w.reduce(($,S)=>$+S.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${k} commands=${h} (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 p of r.get(s.id)??[])a.push(...p.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let p of a){let d=`${s.id}:${p.id}`;if(this.shippedAttachments.has(d))continue;let u;try{u=await Js(n,p.url)}catch(f){this.log.warn(`[yt-sync] attachment ${p.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let g=$f(p.name);l.has(g)&&(g=`${p.id}-${g}`),l.add(g),c.push({name:g,contentBase64:u.toString("base64")}),i.push(d)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Ha(t){let{description:e,...r}=t;return r}function kf(t){let{body:e,...r}=t;return r}function $f(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 xf(t,e,r,n){try{return await cn(t,e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Ka(t,e,r,n){try{return await zs(t,e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var To="npm i -g @code-partner/codepipe@latest";function kn(t,e={}){let r=e.log??{info:f=>console.log(f),warn:f=>console.warn(f)};r.info(`codepipe-cli v${me} (protocol ${Te})`);let n=f=>e.onEvent?.(f),o=e.workspace;o?.contextDir&&Xi(o.contextDir,r);let i=Wa("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Wa("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let f=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(f)&&f>0?f*1e3:6e5})(),c=!1,l=!1,p=new Set,d=new Set,u=g();function g(){let f=gn(t.hubUrl,t.cliToken),w=null,b=new wn(i,j=>{f.readyState===f.OPEN&&f.send(JSON.stringify(j))},r),k=new bn(s,j=>{f.readyState===f.OPEN&&f.send(JSON.stringify(j))},r,{contextDir:o?.contextDir??null,isSelfComment:j=>d.has(j)}),h=null,$=async()=>{try{let j;try{let C=await F(t.hubUrl,t.cliToken,t.projectId);j={repos:C.repos,contextRepo:C.contextRepo}}catch(C){r.warn(`[readiness] could not fetch project summary for push checks: ${C instanceof Error?C.message:String(C)}`)}let R=await ea(t.projectId,j);if(f.readyState!==f.OPEN)return;let m={type:"cli_readiness",projectId:t.projectId,ready:R.ready,checks:R.checks,creds:R.creds,checkedAt:R.checkedAt};if(f.send(JSON.stringify(m)),R.ready)r.info("[readiness] ready");else{let C=R.checks.filter(v=>!v.ok).map(v=>`${v.name}(${v.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${C.join(", ")}`)}}catch(j){r.warn(`[readiness] check failed: ${j instanceof Error?j.message:String(j)}`)}},S=()=>{$(),h=setInterval(()=>void $(),a),typeof h.unref=="function"&&h.unref()},U=()=>{h&&(clearInterval(h),h=null)},I=o?.contextDir?new Xr(o.contextDir,t.projectId,j=>{f.readyState===f.OPEN&&f.send(JSON.stringify(j))},r):null,E=async()=>{let j=o?.contextDir;if(!j)throw new Error("no context repo clone on this CLI");let R;try{R=(await F(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let m=await fs(j,t.projectId,R,r);return f.readyState===f.OPEN&&f.send(JSON.stringify(m)),m};return f.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let j=Yi(t.projectId),R=L("ORIGIN")==="farm"?"farm":"local",m=L("FARM_ID"),C=t.accountEmail??j.email,v;try{let x=oa(t.projectId);x&&(v=x.publicKey,r.info(`[cred-channel] key fingerprint: ${x.fingerprint}`))}catch(x){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${x instanceof Error?x.message:String(x)}`)}let y={type:"register",projectId:t.projectId,platformVersion:me,protocolVersion:Te,accountId:j.accountId,accountLabel:j.label,origin:R,inFlightActionIds:[...p],...C?{accountEmail:C}:{},...R==="farm"&&m?{farmId:m}:{},...v?{sealPublicKey:v}:{}};f.send(JSON.stringify(y))}),f.on("message",async j=>{let R=j.toString("utf-8");if(R==="pong"||R==="ping")return;let m;try{m=JSON.parse(R)}catch{return}if(!m||typeof m!="object")return;let C=m.type;if(C==="registered"){let y=m;if(y.ok){if(r.info(`[ws] registered for project ${y.projectId}`),n({kind:"registered",projectId:y.projectId??t.projectId}),b.start(),I?.start(),S(),Io(t,o,r),o?.contextDir)try{let x=Zr(o.contextDir,t.projectId);f.readyState===f.OPEN&&f.send(JSON.stringify(x)),x.outdated&&(r.warn(`[ctx] context format outdated: v${x.templateVersion} \u2192 v${x.currentVersion}`+(x.missingPaths.length>0?` (missing: ${x.missingPaths.join(", ")})`:"")),l||(l=!0,E().catch(()=>{})))}catch(x){r.warn(`[ctx] context-format detect failed (non-fatal): ${x instanceof Error?x.message:String(x)}`)}}else r.warn(`[ws] register rejected: ${y.reason??"unknown"}`),n({kind:"register_rejected",reason:y.reason??"unknown"}),c=!0,f.close();return}if(C==="hello"){let y=m;w=Lr(y.protocolVersion);let x=w?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${y.platformVersion} (protocol ${y.protocolVersion}) \u2014 ${x}`),w||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${me}, protocol ${Te}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${To}`),n({kind:"incompatible",hubVersion:typeof y.platformVersion=="string"?y.platformVersion:null,hubProtocol:typeof y.protocolVersion=="number"?y.protocolVersion:null,updateCommand:To}));return}if(C==="tracking_targets"){b.setTargets(m.targets);return}if(C==="youtrack_sync_request"){k.setRequest(m);return}if(C==="youtrack_force_sync"){k.forceSync();return}if(C==="sync_local"){await Tf(m,o,f,r);return}if(C==="provision_repo"){let y=m;r.info(`[repo] provision_repo: ${y.repo.name} (${y.repo.host}:${y.repo.owner}/${y.repo.repoName})`),await Rf(t,o,y.repo,r),await Io(t,o,r);return}if(C==="remove_repo"){let y=m;r.info(`[repo] remove_repo: ${y.repoName}${y.purge?" (purge)":""}`),await Io(t,o,r),y.purge&&Cf(t,o,y.repoName,r);return}if(C==="context_write"){await If(m,o,f,r);return}if(C==="adr_promote"){await jf(m,o,f,r);return}if(C==="cred_update"){let y=m,x=D(t.projectId),_=x?.sealKey?await ia(t.projectId,y.kind,y.sealed,x.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},z={type:"cred_update_result",updateId:y.updateId,projectId:t.projectId,ok:_.ok,..._.detail?{detail:_.detail}:{}};f.readyState===f.OPEN&&f.send(JSON.stringify(z)),_.ok?(r.info(`[cred] ${y.kind} replaced${_.detail?` \u2014 ${_.detail}`:""}`),$()):r.warn(`[cred] ${y.kind} replacement rejected: ${_.detail??"unknown"}`);return}if(C==="move_to_farm"){let y=m;r.info(`[farm-move] request to move ${t.projectId} onto farm ${y.farmName} (${y.farmId})`);let x=await Oa(t,y,o?.contextDir,r);f.readyState===f.OPEN&&f.send(JSON.stringify(x)),x.ok?r.info(`[farm-move] done \u2014 farm daemon ${x.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${x.error??"unknown error"}`);return}if(C==="gh_runner_setup"){let y=m;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${y.runnerName} (${y.runnerId})`);let x=await Ga(t,y,r);f.readyState===f.OPEN&&f.send(JSON.stringify(x)),x.ok?r.info(`[ghr] runners connected on ${y.runnerName}`):r.warn(`[ghr] setup failed: ${x.error??"see per-repo statuses"}`);return}if(C==="gh_runner_teardown"){let y=m;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${y.runnerName} (${y.runnerId})`);let x=await Fa(t,y,r);f.readyState===f.OPEN&&f.send(JSON.stringify(x)),x.ok?r.info(`[ghr] runners disconnected from ${y.runnerName}`):r.warn(`[ghr] teardown failed: ${x.error??"unknown error"}`);return}if(C==="tracker_fields_request"){let y=m,x={type:"tracker_fields_result",requestId:y.requestId,projectId:t.projectId,ok:!1},_=_e();if(!_)x.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{x.fields=await Qs(_,y.projectKey),x.ok=!0}catch(z){x.error=z instanceof Error?z.message:String(z)}f.readyState===f.OPEN&&f.send(JSON.stringify(x)),x.ok||r.warn(`[yt-fields] listing failed: ${x.error??"unknown"}`);return}if(C==="sandbox_keys"){let y=D(t.projectId);if(!y){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let x=Tt(t.projectId),_=Ts(m,y,x,r);for(let z of _)f.readyState===f.OPEN&&f.send(JSON.stringify(z));return}if(C!=="dispatch_action")return;let v=m;if(w===!1){let y=`refused: HUB protocol incompatible with CLI v${me} (protocol ${Te})`;f.send(JSON.stringify({type:"action_result",actionId:v.actionId,status:"failed",error:y})),r.warn(`[exec] ${v.actionId} (${v.action.type}) \u2192 REFUSED: ${y}`),r.warn(`[exec] update the CLI to clear this: ${To}`),n({kind:"action",actionId:v.actionId,actionType:v.action.type,ok:!1,error:y});return}p.add(v.actionId);try{let y=await ma({action:v.action,repo:v.repo,trackerIssueId:v.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:I?()=>I.reportNow():void 0,refreshContextStatus:o?.contextDir?E:void 0}).catch(z=>({status:"failed",error:z instanceof Error?z.message:String(z)}));v.action.type==="tracker_comment"&&y.status==="done"&&"result"in y&&typeof y.result?.commentId=="string"&&d.add(y.result.commentId),f.send(JSON.stringify({type:"action_result",actionId:v.actionId,...y}));let x=y.status!=="failed",_=!x&&"error"in y?y.error:void 0;x?r.info(`[exec] ${v.actionId} (${v.action.type}) \u2192 done`):r.warn(`[exec] ${v.actionId} (${v.action.type}) \u2192 FAILED: ${_??"?"}`),n({kind:"action",actionId:v.actionId,actionType:v.action.type,ok:x,..._?{error:_}:{}})}finally{p.delete(v.actionId)}}),f.on("close",(j,R)=>{let m=R?.toString("utf-8")??"";if(r.info(`[ws] closed code=${j}${m?` reason=${m}`:""}`),b.stop(),k.stop(),I?.stop(),U(),m==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:j}),!c&&setTimeout(()=>{u=g()},2e3)}),f.on("error",j=>r.warn(`[ws] error: ${j.message}`)),f}return{stop(){c=!0,u.close()}}}async function Io(t,e,r){try{let n=await F(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 Rf(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?xr(e.root,o):xe(t.projectId,r.name);if(qa(xr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await Sf().clone(fo(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 Cf(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?xr(e.root,o):xe(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!qa(xr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{vf(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 Tf(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=xr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Vi(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 If(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 jf(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=t.source??"task",s=await os(e.contextDir,t.taskKey,t.slugs,void 0,i);if(n.info(`[adr] adr_promote ${t.id}: promoted ${s.promoted.length}, skipped ${s.skipped.length}`+(s.promoted.length>0?` (${s.promoted.join(", ")})`:"")),s.missing.length>0){let a=l=>i==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${s.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);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 Wa(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Za,mkdirSync as ec}from"node:fs";import{dirname as tc}from"node:path";import{simpleGit as Ut}from"simple-git";import{execFileSync as Pf}from"node:child_process";import{mkdtempSync as Ef,mkdirSync as Af,readFileSync as Ya,rmSync as _f,writeFileSync as Of}from"node:fs";import{tmpdir as Nf}from"node:os";import{dirname as Uf,join as Va}from"node:path";function Ja(t="codepipe-context"){let e=Ef(Va(Nf(),"codepipe-ssh-")),r=Va(e,"id_ed25519");try{return Pf("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Ya(r,"utf-8"),publicKey:Ya(`${r}.pub`,"utf-8").trim()}}finally{_f(e,{recursive:!0,force:!0})}}async function za(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 Xa(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){Af(Uf(t),{recursive:!0});let r=e.endsWith(`
452
452
  `)?e:e+`
453
- `;return Sf(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Tf(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 If(t,e){return e?.contextWrite?.token?{user:Fr(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:mt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}var $n=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}};async function Xa(t,e){let r=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),n=e.initialDelayMs??5e3,o=e.maxDelayMs??6e4;for(;;)try{return await t()}catch(i){if(!(i instanceof $n))throw i;e.log.warn(`[ctx] ${i.message} \u2014 retrying in ${Math.round(n/1e3)}s (the HUB may be deploying)`),await r(n),n=Math.min(n*2,o)}}async function xn(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await M(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new $n(c)}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=If(Rt(s.cloneUrl),r);if(a){let c=await jf({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 Pf({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 jf(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Tf(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(Va(`${r}/.git`)){let l=Ut(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=eo(r);await l.reset(["--hard",`origin/${s}`]),to(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Ja(za(r),{recursive:!0}),await Ut().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Qa(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 Pf(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Ya(i,n),a=qa(e.cloneUrl),c=e.branch;try{if(Va(`${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=eo(r);await l.reset(["--hard",`origin/${c}`]),to(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Ja(za(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 Qa(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 Qa(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 Za(t={profile:void 0}){let{cfg:e,profile:r}=qr(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(Io(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Jr("CLI_LOG",i,o);if(s.enabled){let p=new jt(s);zr(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=Kr(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(Io(),".codepipe",r?vr("profiles",r,"context"):"context");if(await vo(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Xa(()=>xn({cfg:e,secrets:n,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),{log:{warn:g=>console.warn(g)}}),a||await vo(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(Io(),".codepipe",r?vr("profiles",r,"context-config"):"context-config");Qr(a.contextDir,g,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=kn(e,{...a?{workspace:a}:{},onEvent:p=>{p.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function d(p){u||(u=!0,console.log(`
454
- [${p}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>d("SIGINT")),process.on("SIGTERM",()=>d("SIGTERM")),await new Promise(()=>{})}import{hostname as Df}from"node:os";import{spawnSync as Ef}from"node:child_process";function Af(){try{return Ef("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function ec(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Af(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Lt}from"node:os";import{mkdirSync as _f,readFileSync as tc,writeFileSync as Of,existsSync as jo}from"node:fs";import{dirname as Nf,join as rt}from"node:path";jo(".env")&&process.loadEnvFile(".env");function Uf(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Re(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 rc(){return rt(Lt(),".devpipe-sandbox","config.json")}function vn(){gt(rt(Lt(),".devpipe"),rt(Lt(),".codepipe")),L("SANDBOX_CONFIG")||gt(rt(Lt(),".devpipe-sandbox"),rt(Lt(),".codepipe-sandbox"))}function ie(t){let e=Re(t),r=null;return jo(e)?r=JSON.parse(tc(e,"utf-8")):!t&&!L("SANDBOX_CONFIG")&&jo(rc())&&(r=JSON.parse(tc(rc(),"utf-8"))),r?(r.planningLane=Uf(),r):null}function nc(t,e){let r=Re(e);_f(Nf(r),{recursive:!0}),Of(r,JSON.stringify(t,null,2)+`
455
- `,{mode:384})}import Lf 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 Lf(e)}};async function wt(t){vn();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 ${Re(t.profile)}.`),process.exit(1));let r=t.name??Df(),n=ec({projects:t.projects??[],llm:t.llm??null}),o=new Dt(t.hub.replace(/\/$/,"")),i=on(),s=ae(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});nc({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 ${Re(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 Pm,readFileSync as Lo,readdirSync as Em,writeFileSync as Am}from"node:fs";import{dirname as _m,join as Tr,resolve as Om}from"node:path";import{spawn as Kf}from"node:child_process";import{existsSync as Wf}from"node:fs";import{spawn as Bf}from"node:child_process";var oc=16e3,ic=5e3,sc=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Gf="\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 Po(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Mf(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 Ff(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 Eo(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
456
- `}async function ac(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new qe;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 d=c.message;for(let p of d?.content??[]){let g=p.type;if(g==="text"){let f=String(p.text??"").trim();f&&o({ts:l,kind:"text",author:"agent",text:Po(f,oc)})}else if(g==="tool_use"){let f=String(p.name??""),y=p.input?.file_path??p.input?.path,w=Mf(y,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:f,...w?{file:w}:{}})}}return}if(u==="user"){let d=c.message;for(let p of d?.content??[])if(p.type==="tool_result"){let g=p.is_error===!0,f=g?Po(Ff(p.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:g,...f?{text:f}:{}})}return}if(u==="result"){s=c;let d=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...d?{text:d}:{}});return}if(u==="system"){let d=String(c.subtype??"").trim();d&&o({ts:l,kind:"system",author:"agent",text:d})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let u=Bf(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let d=!1,p=!1,g=null,f=()=>{d=!0,u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),ic)};e.signal?.addEventListener("abort",f,{once:!0});let y=null,w=()=>{y&&clearTimeout(y),y=setTimeout(()=>{p=!0,console.warn(`[claude:chat] idle for ${sc}ms \u2014 ending session`),u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),ic)},sc)},b=()=>{g&&clearTimeout(g),y&&clearTimeout(y),e.signal?.removeEventListener("abort",f)},h=!0,x=I=>{if(!(!h||u.stdin.destroyed))try{u.stdin.write(I)}catch{}};x(Eo(e.prompt)),w(),(async()=>{try{for await(let I of e.interactive.inbox){if(d||!h)break;if(w(),I.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:Po(I.text,oc)}),x(Eo(I.text));else{x(Eo(Gf)),h=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let S="",N=I=>{let v;try{v=JSON.parse(I)}catch{return}a(v)};u.stdout.on("data",I=>{i.push(I),w(),S+=I;let v;for(;(v=S.indexOf(`
457
- `))!==-1;){let m=S.slice(0,v).trim();S=S.slice(v+1),m&&N(m)}}),u.stderr.on("data",I=>{i.push(I);for(let v of I.split(`
458
- `)){let m=v.trim();m&&console.warn(`[claude:chat:stderr] ${m}`)}}),u.on("error",I=>{b(),l(I)}),u.on("close",I=>{if(b(),d){l(new qe);return}if(p){l(new Error("chat session ended: idle for too long without a reply"));return}S.trim()&&N(S.trim()),console.log(`[claude:chat] exit code=${I}`),c({artifactPaths:[],log:i.join(""),usage:Hf(s)})})})}function Hf(t){let e=dt();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 Bt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},qe=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},qf=5e3,Sr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return ac(this.binary,e);if(e.signal?.aborted)throw new qe;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let y=zf(f.rate_limit_info);y&&(!l||y.utilization>l.utilization)&&(l=y);return}if(f.type==="assistant"){let y=f.message;typeof y?.model=="string"&&(c=y.model);let w=y?.usage;w&&(a+=1,s.input+=ce(w.input_tokens),s.output+=ce(w.output_tokens),s.cacheRead+=ce(w.cache_read_input_tokens),s.cacheCreate+=ce(w.cache_creation_input_tokens))}}},d=e.role,p=e.onActivity,g=f=>{if(p)for(let y of Qf(f,e.workspaceDir))try{p(y)}catch{}};return p?.({ts:Date.now(),kind:"start",text:`${d} job started`}),console.log(`[claude] spawn ${this.binary} role=${d}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,y)=>{let w=Kf(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});w.stdout.setEncoding("utf-8"),w.stderr.setEncoding("utf-8");let b=!1,h=null,x=()=>{b=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${d}`),w.kill("SIGTERM"),h=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),w.kill("SIGKILL")},qf)};e.signal?.addEventListener("abort",x,{once:!0});let S=()=>{h&&clearTimeout(h),e.signal?.removeEventListener("abort",x)},N="";w.stdout.on("data",I=>{n.push(I),N+=I;let v;for(;(v=N.indexOf(`
459
- `))!==-1;){let m=N.slice(0,v).trim();if(N=N.slice(v+1),m){let T=cc(m);u(T),T&&g(T)}}}),w.stderr.on("data",I=>{n.push(I),o.push(I);for(let v of I.split(`
460
- `)){let m=v.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),w.on("error",I=>{S(),y(I)}),w.on("close",I=>{if(S(),b){y(new qe);return}if(N.trim()){let m=cc(N.trim());u(m),m&&g(m)}let v=i?.is_error===!0;if(I!==0||v){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,T=typeof i?.subtype=="string"?i.subtype:void 0,k=typeof i?.result=="string"?i.result:void 0;y(new Bt(Yf(I,i,o.join("")),{code:I,apiErrorStatus:m,subtype:T,resultText:k,retryAfterMs:Vf(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:Xf(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("/")&&Wf(n))}};function cc(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=Jf(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=uc(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 Yf(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(`
453
+ `;return Of(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Df(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 Lf(t,e){return e?.contextWrite?.token?{user:Fr(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:mt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}var $n=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}};async function rc(t,e){let r=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),n=e.initialDelayMs??5e3,o=e.maxDelayMs??6e4;for(;;)try{return await t()}catch(i){if(!(i instanceof $n))throw i;e.log.warn(`[ctx] ${i.message} \u2014 retrying in ${Math.round(n/1e3)}s (the HUB may be deploying)`),await r(n),n=Math.min(n*2,o)}}async function xn(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await F(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new $n(c)}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=Lf(Rt(s.cloneUrl),r);if(a){let c=await Bf({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 Mf({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 Bf(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Df(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(Za(`${r}/.git`)){let l=Ut(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let p=to(r);await l.reset(["--hard",`origin/${s}`]),ro(r,p),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else ec(tc(r),{recursive:!0}),await Ut().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await nc(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 Mf(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Qa(i,n),a=Xa(e.cloneUrl),c=e.branch;try{if(Za(`${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 p=to(r);await l.reset(["--hard",`origin/${c}`]),ro(r,p),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ec(tc(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 nc(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 nc(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 oc(t={profile:void 0}){let{cfg:e,profile:r}=qr(t.profile),n=D(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(jo(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Jr("CLI_LOG",i,o);if(s.enabled){let u=new jt(s);zr(u),console.log(`[log] file logging \u2192 ${u.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=Kr(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let u=vr(jo(),".codepipe",r?vr("profiles",r,"context"):"context");if(await So(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await rc(()=>xn({cfg:e,secrets:n,contextDir:u,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),{log:{warn:g=>console.warn(g)}}),a||await So(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(jo(),".codepipe",r?vr("profiles",r,"context-config"):"context-config");Qr(a.contextDir,g,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=kn(e,{...a?{workspace:a}:{},onEvent:u=>{u.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),p=!1;function d(u){p||(p=!0,console.log(`
454
+ [${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>d("SIGINT")),process.on("SIGTERM",()=>d("SIGTERM")),await new Promise(()=>{})}import{hostname as Vf}from"node:os";import{spawnSync as Gf}from"node:child_process";function Ff(){try{return Gf("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function ic(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 Dt}from"node:os";import{mkdirSync as Hf,readFileSync as sc,writeFileSync as Kf,existsSync as Po}from"node:fs";import{dirname as Wf,join as rt}from"node:path";Po(".env")&&process.loadEnvFile(".env");function qf(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Re(t){let e=L("SANDBOX_CONFIG");if(e)return e;let r=rt(Dt(),".codepipe","worker");return t?rt(r,"profiles",t,"config.json"):rt(r,"config.json")}function ac(){return rt(Dt(),".devpipe-sandbox","config.json")}function vn(){gt(rt(Dt(),".devpipe"),rt(Dt(),".codepipe")),L("SANDBOX_CONFIG")||gt(rt(Dt(),".devpipe-sandbox"),rt(Dt(),".codepipe-sandbox"))}function se(t){let e=Re(t),r=null;return Po(e)?r=JSON.parse(sc(e,"utf-8")):!t&&!L("SANDBOX_CONFIG")&&Po(ac())&&(r=JSON.parse(sc(ac(),"utf-8"))),r?(r.planningLane=qf(),r):null}function cc(t,e){let r=Re(e);Hf(Wf(r),{recursive:!0}),Kf(r,JSON.stringify(t,null,2)+`
455
+ `,{mode:384})}import Yf from"ws";var Lt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let 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 Yf(e)}};async function wt(t){vn();let e=se(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Re(t.profile)}.`),process.exit(1));let r=t.name??Vf(),n=ic({projects:t.projects??[],llm:t.llm??null}),o=new Lt(t.hub.replace(/\/$/,"")),i=on(),s=ce(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});cc({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 ${Re(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 Mm,readFileSync as Lo,readdirSync as Gm,writeFileSync as Fm}from"node:fs";import{homedir as Hm}from"node:os";import{dirname as Km,join as Wt}from"node:path";import{spawn as em}from"node:child_process";import{existsSync as tm}from"node:fs";import{spawn as Jf}from"node:child_process";var lc=16e3,uc=5e3,pc=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),zf="\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 Eo(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Xf(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 Qf(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 Ao(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
456
+ `}async function dc(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new We;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(),p=c.type;if(p==="assistant"){let d=c.message;for(let u of d?.content??[]){let g=u.type;if(g==="text"){let f=String(u.text??"").trim();f&&o({ts:l,kind:"text",author:"agent",text:Eo(f,lc)})}else if(g==="tool_use"){let f=String(u.name??""),w=u.input?.file_path??u.input?.path,b=Xf(w,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:f,...b?{file:b}:{}})}}return}if(p==="user"){let d=c.message;for(let u of d?.content??[])if(u.type==="tool_result"){let g=u.is_error===!0,f=g?Eo(Qf(u.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:g,...f?{text:f}:{}})}return}if(p==="result"){s=c;let d=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(c.subtype??"").trim();d&&o({ts:l,kind:"system",author:"agent",text:d})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let p=Jf(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,u=!1,g=null,f=()=>{d=!0,p.kill("SIGTERM"),g=setTimeout(()=>p.kill("SIGKILL"),uc)};e.signal?.addEventListener("abort",f,{once:!0});let w=null,b=()=>{w&&clearTimeout(w),w=setTimeout(()=>{u=!0,console.warn(`[claude:chat] idle for ${pc}ms \u2014 ending session`),p.kill("SIGTERM"),g=setTimeout(()=>p.kill("SIGKILL"),uc)},pc)},k=()=>{g&&clearTimeout(g),w&&clearTimeout(w),e.signal?.removeEventListener("abort",f)},h=!0,$=I=>{if(!(!h||p.stdin.destroyed))try{p.stdin.write(I)}catch{}};$(Ao(e.prompt)),b(),(async()=>{try{for await(let I of e.interactive.inbox){if(d||!h)break;if(b(),I.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:Eo(I.text,lc)}),$(Ao(I.text));else{$(Ao(zf)),h=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let S="",U=I=>{let E;try{E=JSON.parse(I)}catch{return}a(E)};p.stdout.on("data",I=>{i.push(I),b(),S+=I;let E;for(;(E=S.indexOf(`
457
+ `))!==-1;){let j=S.slice(0,E).trim();S=S.slice(E+1),j&&U(j)}}),p.stderr.on("data",I=>{i.push(I);for(let E of I.split(`
458
+ `)){let j=E.trim();j&&console.warn(`[claude:chat:stderr] ${j}`)}}),p.on("error",I=>{k(),l(I)}),p.on("close",I=>{if(k(),d){l(new We);return}if(u){l(new Error("chat session ended: idle for too long without a reply"));return}S.trim()&&U(S.trim()),console.log(`[claude:chat] exit code=${I}`),c({artifactPaths:[],log:i.join(""),usage:Zf(s)})})})}function Zf(t){let e=dt();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 Bt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},We=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},rm=5e3,Sr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return dc(this.binary,e);if(e.signal?.aborted)throw new We;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,p=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let w=sm(f.rate_limit_info);w&&(!l||w.utilization>l.utilization)&&(l=w);return}if(f.type==="assistant"){let w=f.message;typeof w?.model=="string"&&(c=w.model);let b=w?.usage;b&&(a+=1,s.input+=le(b.input_tokens),s.output+=le(b.output_tokens),s.cacheRead+=le(b.cache_read_input_tokens),s.cacheCreate+=le(b.cache_creation_input_tokens))}}},d=e.role,u=e.onActivity,g=f=>{if(u)for(let w of cm(f,e.workspaceDir))try{u(w)}catch{}};return u?.({ts:Date.now(),kind:"start",text:`${d} job started`}),console.log(`[claude] spawn ${this.binary} role=${d}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,w)=>{let b=em(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});b.stdout.setEncoding("utf-8"),b.stderr.setEncoding("utf-8");let k=!1,h=null,$=()=>{k=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${d}`),b.kill("SIGTERM"),h=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),b.kill("SIGKILL")},rm)};e.signal?.addEventListener("abort",$,{once:!0});let S=()=>{h&&clearTimeout(h),e.signal?.removeEventListener("abort",$)},U="";b.stdout.on("data",I=>{n.push(I),U+=I;let E;for(;(E=U.indexOf(`
459
+ `))!==-1;){let j=U.slice(0,E).trim();if(U=U.slice(E+1),j){let R=fc(j);p(R),R&&g(R)}}}),b.stderr.on("data",I=>{n.push(I),o.push(I);for(let E of I.split(`
460
+ `)){let j=E.trim();j&&console.warn(`[claude:stderr] ${j}`)}}),b.on("error",I=>{S(),w(I)}),b.on("close",I=>{if(S(),k){w(new We);return}if(U.trim()){let j=fc(U.trim());p(j),j&&g(j)}let E=i?.is_error===!0;if(I!==0||E){let j=typeof i?.api_error_status=="number"?i.api_error_status:void 0,R=typeof i?.subtype=="string"?i.subtype:void 0,m=typeof i?.result=="string"?i.result:void 0;w(new Bt(nm(I,i,o.join("")),{code:I,apiErrorStatus:j,subtype:R,resultText:m,retryAfterMs:om(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:am(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("/")&&tm(n))}};function fc(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=im(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=gc(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 nm(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(`
461
461
  `).slice(-5).join(`
462
- `),500)),n.join(" \u2014 ")}function Vf(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 uc(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Jf(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 zf(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 Xf(t,e,r,n){let o=dt(),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 lc=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,lc)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,d=Zf(u,e);i.push({ts:r,kind:"tool",tool:c,...d?{file:d}:{}})}}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(uc(s.content),lc):"";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 Zf(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 em,writeFileSync as Gt}from"node:fs";import{dirname as tm,join as Mt}from"node:path";function pc(t,e,r){let n=Mt(t,e);em(tm(n),{recursive:!0}),Gt(n,r)}var Rr=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=rm(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"),nm(n,o,i,a)),s.push("SOLUTION.md"),Gt(Mt(e.workspaceDir,"QUESTIONS.md"),om(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;pc(e.workspaceDir,"changes/sample.patch",im(n,o,a)),s.push("changes/sample.patch"),pc(e.workspaceDir,"diff-summary.md",sm(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})
463
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:dt()}}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 qe;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}
462
+ `),500)),n.join(" \u2014 ")}function om(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 gc(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function im(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 le(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function sm(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=le(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:le(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 am(t,e,r,n){let o=dt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=le(i.input_tokens),o.outputTokens=le(i.output_tokens),o.cacheReadInputTokens=le(i.cache_read_input_tokens),o.cacheCreationInputTokens=le(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=le(t?.total_cost_usd),o.numTurns=t&&le(t.num_turns)>0?le(t.num_turns):r,o.durationMs=le(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}var mc=200;function cm(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,mc)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,p=l?.file_path??l?.path??l?.notebook_path,d=lm(p,e);i.push({ts:r,kind:"tool",tool:c,...d?{file:d}:{}})}}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(gc(s.content),mc):"";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 lm(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 um,writeFileSync as Mt}from"node:fs";import{dirname as pm,join as Gt}from"node:path";function hc(t,e,r){let n=Gt(t,e);um(pm(n),{recursive:!0}),Mt(n,r)}var Rr=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=dm(n,o,i);Mt(Gt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Mt(Gt(e.workspaceDir,"SOLUTION.md"),fm(n,o,i,a)),s.push("SOLUTION.md"),Mt(Gt(e.workspaceDir,"QUESTIONS.md"),mm(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;hc(e.workspaceDir,"changes/sample.patch",gm(n,o,a)),s.push("changes/sample.patch"),hc(e.workspaceDir,"diff-summary.md",hm(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Mt(Gt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
463
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:dt()}}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 We;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 Mt(Gt(e.workspaceDir,"DRAFT.md"),`${o}
464
464
 
465
465
  \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).
466
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:dt()}}};function rm(t,e,r){return`# ${t} \u2014 Estimate
466
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:dt()}}};function dm(t,e,r){return`# ${t} \u2014 Estimate
467
467
 
468
468
  **Title:** ${e}
469
469
 
@@ -484,7 +484,7 @@ production-grade estimates.)
484
484
  ${r.split(`
485
485
  `).slice(0,8).join(`
486
486
  `).trim()||"(empty)"}
487
- `}function nm(t,e,r,n){let o=n?`
487
+ `}function fm(t,e,r,n){let o=n?`
488
488
  ## Reviewer rework instruction
489
489
 
490
490
  > ${n.split(`
@@ -513,10 +513,10 @@ TBD (mock runner does not yet inspect project code).
513
513
  ${r.split(`
514
514
  `).slice(0,8).join(`
515
515
  `).trim()||"(empty)"}
516
- `}function om(t){return`# ${t} \u2014 Open questions
516
+ `}function mm(t){return`# ${t} \u2014 Open questions
517
517
 
518
518
  (none \u2014 mock runner did not surface ambiguities.)
519
- `}function im(t,e,r){let n=r?` (rework: ${r.split(`
519
+ `}function gm(t,e,r){let n=r?` (rework: ${r.split(`
520
520
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
521
521
  index 0000000..1111111 100644
522
522
  --- a/CHANGELOG.md
@@ -527,7 +527,7 @@ index 0000000..1111111 100644
527
527
  +- mock-runner placeholder change for slice 5 testing.
528
528
  +
529
529
  # Changelog
530
- `}function sm(t,e,r){return`# ${t} \u2014 Diff summary
530
+ `}function hm(t,e,r){return`# ${t} \u2014 Diff summary
531
531
 
532
532
  **Title:** ${e}
533
533
  ${r?`
@@ -538,98 +538,98 @@ ${r?`
538
538
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
539
539
 
540
540
  (Mock-runner output. Replace with claude-headless for production patches.)
541
- `}function dc(t){switch(t){case"mock":return new Rr;case"claude-headless":return new Sr;default:return null}}function gc(t=process.env){return{maxAttempts:Sn(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Sn(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Sn(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Sn(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var am=new Set([429,500,502,503,529]),fc=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,cm=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,lm=new Set(["error_max_turns"]);function um(t){if(t instanceof Bt){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return cm.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&lm.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:am.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:fc.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 fc.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var mc=/(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 hc(t){if(t instanceof Bt){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&mc.test(n)}let e=t instanceof Error?t.message:String(t);return mc.test(e)}function pm(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 yc(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=um(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=pm(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 Sn(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as dm,rmSync as fm,writeFileSync as wc}from"node:fs";import{tmpdir as mm}from"node:os";import{join as Ao}from"node:path";function Rn(t){return`[url "https://${t}/"]
541
+ `}function yc(t){switch(t){case"mock":return new Rr;case"claude-headless":return new Sr;default:return null}}function kc(t=process.env){return{maxAttempts:Sn(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Sn(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Sn(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Sn(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var ym=new Set([429,500,502,503,529]),wc=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,wm=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,bm=new Set(["error_max_turns"]);function km(t){if(t instanceof Bt){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return wm.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&bm.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:ym.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:wc.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 wc.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var bc=/(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 $c(t){if(t instanceof Bt){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&bc.test(n)}let e=t instanceof Error?t.message:String(t);return bc.test(e)}function $m(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 xc(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=km(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let p=$m(s,r.policy,c.retryAfterMs);if(Date.now()+p>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 ${p}ms`),await r.onBeforeRetry(),await n(p)}}function Sn(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as xm,rmSync as vm,writeFileSync as vc}from"node:fs";import{tmpdir as Sm}from"node:os";import{join as _o}from"node:path";function Rn(t){return`[url "https://${t}/"]
542
542
  insteadOf = git@${t}:
543
543
  insteadOf = ssh://git@${t}/
544
- `}var gm=Rn("github.com"),hm=Rn("bitbucket.org"),ym=Rn("gitlab.com");function bc(t,e){if(t.length===0)return null;let r=dm(Ao(mm(),"devpipe-gitcreds-")),n=Ao(r,"credentials"),o=Ao(r,"gitconfig");return wc(n,t.join(`
544
+ `}var Rm=Rn("github.com"),Cm=Rn("bitbucket.org"),Tm=Rn("gitlab.com");function Sc(t,e){if(t.length===0)return null;let r=xm(_o(Sm(),"devpipe-gitcreds-")),n=_o(r,"credentials"),o=_o(r,"gitconfig");return vc(n,t.join(`
545
545
  `)+`
546
- `,{mode:384}),wc(o,`[credential]
546
+ `,{mode:384}),vc(o,`[credential]
547
547
  helper = store --file=${n}
548
- `+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{fm(r,{recursive:!0,force:!0})}catch{}}}}function _o(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(gm)),t.bitbucket?.apiToken&&(e.push(`https://${mt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(hm)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(ym)),bc(e,r)}function kc(t,e){if(t.contextWrite?.token){let r=Rt(e)??"github.com",n=Fr(r);return bc([`https://${n}:${t.contextWrite.token}@${r}`],[Rn(r)])}return _o(t)}import{spawn as xc}from"node:child_process";import{existsSync as Cn,mkdirSync as Tn,readFileSync as wm,rmSync as Oo,symlinkSync as bm}from"node:fs";import{homedir as km}from"node:os";import{dirname as In,join as kt}from"node:path";function vc(){return kt(km(),".codepipe-sandbox","repos")}var Ft=new Map;function Sc(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 $c(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)}function $m(t){let e=t instanceof Error?t.message:String(t);return/invalid index-pack output/i.test(e)||/index-pack failed/i.test(e)||/fetch-pack/i.test(e)||/objects[\/\\]pack/i.test(e)||/(loose object .* is corrupt|corrupt loose object|object file .* is empty)/i.test(e)||/did not send all necessary objects/i.test(e)||/(bad object|bad tree object|unable to read (tree|sha1))/i.test(e)||/not a git repository/i.test(e)||/unable to read .*(pack|object)/i.test(e)}async function Rc(t,e,r,n,o){let i=async c=>{await Y(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await Y(t,["reset","--hard",`origin/${c}`],o),await Y(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!$c(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Cn(t)&&Oo(t,{recursive:!0,force:!0}),Tn(In(t),{recursive:!0});try{return await Y(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!$c(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Cn(t)&&Oo(t,{recursive:!0,force:!0}),Tn(In(t),{recursive:!0}),await Y(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Cn(kt(t,".git")))try{return await s()}catch(c){if(!$m(c))throw c;let l=c instanceof Error?c.message:String(c);console.warn(`[git] cache at ${t} looks corrupt (${l}) \u2014 discarding and re-cloning`)}return a()}async function Cc(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 Tc(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 Ic(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 Rt(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 jc(t,e){return oe(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Pc(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 Ec(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=f=>oe(s,["rev-parse","-q","--verify",`${f}^{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(y=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(y)}`)}),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(),d=(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",d],l)}catch(f){p=f instanceof Error?f.message:String(f)}let g=(await oe(s,["diff","--name-only","--diff-filter=U"])).split(`
549
- `).map(f=>f.trim()).filter(f=>f.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 No(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(`
550
- `).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=xc("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}):
551
- ${s.join("").trim()||"(no stderr)"}`))})})}function oe(t,e,r){return new Promise((n,o)=>{let i=xc("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}):
552
- ${a.join("").trim()||"(no stderr)"}`))})})}function Ac(t,e){Cn(t)&&Oo(t,{recursive:!0,force:!0}),Tn(In(t),{recursive:!0}),bm(e,t,"dir")}async function _c(t,e,r){await Y(t,["worktree","prune"]).catch(()=>{}),Tn(In(r),{recursive:!0}),await Y(t,["worktree","add","--detach",r,`origin/${e}`])}async function Oc(t,e,r,n="worktree",o){return r.length===0?[]:Sc(e,async()=>{let i=[];for(let s of r){let a=kt(vc(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await Rc(a,s.cloneUrl,s.ref,s.defaultBranch,o)}catch(d){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let l=(await oe(a,["rev-parse","HEAD"])).trim(),u=kt(t,"code",s.name);n==="direct"?(Ac(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await _c(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 Nc(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=r;return Sc(e,async()=>{let s=kt(vc(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await Rc(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=kt(t,"context");n==="direct"?(Ac(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await _c(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 Uc(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(`
553
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=wm(kt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as xm}from"node:fs";import{join as vm}from"node:path";var Uo=8*1024,Wt=class extends Error{},Cr="meta/build-result.json";function Lc(t){let e=vm(t,Cr),r;try{r=xm(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 d=u,p=typeof d.name=="string"?d.name:null,g=typeof d.exitCode=="number"?d.exitCode:null;if(p===null||g===null)return[];let f={name:p,exitCode:g};return typeof d.durationMs=="number"&&(f.durationMs=d.durationMs),[f]}),c=typeof o.logTail=="string"?Sm(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(d=>d.exitCode!==0);u&&(l.failedStep=u.name)}return l}function Sm(t){let e=Buffer.from(t,"utf-8");return e.length<=Uo?t:`\u2026 [${e.length-Uo} bytes elided] \u2026
554
- `+e.subarray(e.length-Uo).toString("utf-8")}import{lstatSync as Rm,mkdtempSync as Cm,readFileSync as Tm,readdirSync as Bc,rmSync as Dc}from"node:fs";import{tmpdir as Im}from"node:os";import{join as jn,relative as jm}from"node:path";var Gc=new Set(["code","context"]);function Mc(t){let e=Cm(jn(Im(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Dc(e,{recursive:!0,force:!0}),listFiles:()=>Fc(e,e),readFile:r=>Tm(jn(e,r),"utf-8"),clean:()=>{for(let r of Bc(e))Gc.has(r)||Dc(jn(e,r),{recursive:!0,force:!0})}}}function Fc(t,e){let r=[];for(let n of Bc(e)){let o=jn(e,n),i=Rm(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Gc.has(n))continue;r.push(...Fc(t,o))}else r.push(jm(t,o))}return r}var Pn=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Nm=new Set(["implement","resolve-conflict"]);function Um(t){let e=Buffer.from(t,"utf-8");if(e.length<=Pn)return t;let r=Math.floor(Pn/4),n=Pn-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}
548
+ `+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{vm(r,{recursive:!0,force:!0})}catch{}}}}function Oo(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Rm)),t.bitbucket?.apiToken&&(e.push(`https://${mt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Cm)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Tm)),Sc(e,r)}function Rc(t,e){if(t.contextWrite?.token){let r=Rt(e)??"github.com",n=Fr(r);return Sc([`https://${n}:${t.contextWrite.token}@${r}`],[Rn(r)])}return Oo(t)}import{spawn as Tc}from"node:child_process";import{existsSync as Cn,mkdirSync as Tn,readFileSync as Im,rmSync as No,symlinkSync as jm}from"node:fs";import{homedir as Pm}from"node:os";import{dirname as In,join as kt}from"node:path";function Ic(){return kt(Pm(),".codepipe-sandbox","repos")}var Ft=new Map;function jc(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 Cc(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)}function Em(t){let e=t instanceof Error?t.message:String(t);return/invalid index-pack output/i.test(e)||/index-pack failed/i.test(e)||/fetch-pack/i.test(e)||/objects[\/\\]pack/i.test(e)||/(loose object .* is corrupt|corrupt loose object|object file .* is empty)/i.test(e)||/did not send all necessary objects/i.test(e)||/(bad object|bad tree object|unable to read (tree|sha1))/i.test(e)||/not a git repository/i.test(e)||/unable to read .*(pack|object)/i.test(e)}async function Pc(t,e,r,n,o){let i=async c=>{await q(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await q(t,["reset","--hard",`origin/${c}`],o),await q(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!Cc(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Cn(t)&&No(t,{recursive:!0,force:!0}),Tn(In(t),{recursive:!0});try{return await q(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Cc(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Cn(t)&&No(t,{recursive:!0,force:!0}),Tn(In(t),{recursive:!0}),await q(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Cn(kt(t,".git")))try{return await s()}catch(c){if(!Em(c))throw c;let l=c instanceof Error?c.message:String(c);console.warn(`[git] cache at ${t} looks corrupt (${l}) \u2014 discarding and re-cloning`)}return a()}async function Ec(t){await q(t.workspacePath,["reset","--hard",t.baseSha]),await q(t.workspacePath,["clean","-fdx"])}var Ht="CodePipe Agent",Kt="codepipe@codepartner.ee";async function Ac(t,e){let r=t.workspacePath;await q(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 _c(t,e,r,n,o){try{await q(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Rt(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 Oc(t,e){return oe(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Nc(t,e,r,n,o){await q(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await q(t.workspacePath,["checkout","--force",r])}async function Uc(t,e,r,n,o,i){let s=t.workspacePath;await q(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=f=>oe(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await oe(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await q(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(w=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(w)}`)}),await c(n)||await q(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},p=(await oe(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),d=(await oe(s,["commit-tree",p,"-p",n,"-m","delivery"],l)).trim();await q(s,["cherry-pick","--quit"],l).catch(()=>{});let u=null;try{await q(s,["cherry-pick","--no-commit",d],l)}catch(f){u=f instanceof Error?f.message:String(f)}let g=(await oe(s,["diff","--name-only","--diff-filter=U"])).split(`
549
+ `).map(f=>f.trim()).filter(f=>f.length>0);if(u&&g.length===0)throw await q(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${u}`);return g}async function Uo(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 q(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 q(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await q(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(`
550
+ `).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 q(t,e,r){return new Promise((n,o)=>{let i=Tc("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}):
551
+ ${s.join("").trim()||"(no stderr)"}`))})})}function oe(t,e,r){return new Promise((n,o)=>{let i=Tc("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}):
552
+ ${a.join("").trim()||"(no stderr)"}`))})})}function Dc(t,e){Cn(t)&&No(t,{recursive:!0,force:!0}),Tn(In(t),{recursive:!0}),jm(e,t,"dir")}async function Lc(t,e,r){await q(t,["worktree","prune"]).catch(()=>{}),Tn(In(r),{recursive:!0}),await q(t,["worktree","add","--detach",r,`origin/${e}`])}async function Bc(t,e,r,n="worktree",o){return r.length===0?[]:jc(e,async()=>{let i=[];for(let s of r){let a=kt(Ic(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await Pc(a,s.cloneUrl,s.ref,s.defaultBranch,o)}catch(d){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let l=(await oe(a,["rev-parse","HEAD"])).trim(),p=kt(t,"code",s.name);n==="direct"?(Dc(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${l.slice(0,10)}`)):(await Lc(a,c,p),console.log(`[git] code: worktree ${p} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:p,cachePath:a,ref:c,baseSha:l})}return i})}async function Mc(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=r;return jc(e,async()=>{let s=kt(Ic(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await Pc(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=kt(t,"context");n==="direct"?(Dc(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await Lc(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 Gc(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await q(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(`
553
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Im(kt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as Am}from"node:fs";import{join as _m}from"node:path";var Do=8*1024,ot=class extends Error{},Cr="meta/build-result.json";function Fc(t){let e=_m(t,Cr),r;try{r=Am(e,"utf-8")}catch{throw new ot(`BUILD produced no ${Cr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(p){throw new ot(`${Cr} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!n||typeof n!="object")throw new ot(`${Cr} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new ot(`${Cr}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(p=>{if(!p||typeof p!="object")return[];let d=p,u=typeof d.name=="string"?d.name:null,g=typeof d.exitCode=="number"?d.exitCode:null;if(u===null||g===null)return[];let f={name:u,exitCode:g};return typeof d.durationMs=="number"&&(f.durationMs=d.durationMs),[f]}),c=typeof o.logTail=="string"?Om(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let p=a.find(d=>d.exitCode!==0);p&&(l.failedStep=p.name)}return l}function Om(t){let e=Buffer.from(t,"utf-8");return e.length<=Do?t:`\u2026 [${e.length-Do} bytes elided] \u2026
554
+ `+e.subarray(e.length-Do).toString("utf-8")}import{lstatSync as Nm,mkdtempSync as Um,readFileSync as Dm,readdirSync as Kc,rmSync as Hc}from"node:fs";import{tmpdir as Lm}from"node:os";import{join as jn,relative as Bm}from"node:path";var Wc=new Set(["code","context"]);function qc(t){let e=Um(jn(Lm(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Hc(e,{recursive:!0,force:!0}),listFiles:()=>Yc(e,e),readFile:r=>Dm(jn(e,r),"utf-8"),clean:()=>{for(let r of Kc(e))Wc.has(r)||Hc(jn(e,r),{recursive:!0,force:!0})}}}function Yc(t,e){let r=[];for(let n of Kc(e)){let o=jn(e,n),i=Nm(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Wc.has(n))continue;r.push(...Yc(t,o))}else r.push(Bm(t,o))}return r}var Pn=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Wm=new Set(["implement","resolve-conflict"]);function qm(t){let e=Buffer.from(t,"utf-8");if(e.length<=Pn)return t;let r=Math.floor(Pn/4),n=Pn-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}
555
555
 
556
556
  \u2026 [${s} bytes elided \u2014 log capped at ${Pn} bytes for upload] \u2026
557
557
 
558
- ${i}`}function Lm(){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 Ir(t={}){vn();let e=ie(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=Jr("SANDBOX_LOG","sandbox",Om("./logs"));if(n.enabled){let v=new jt(n);zr(v),console.log(`[log] file logging \u2192 ${v.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=dc(e.llm);console.log(`llm backend: ${o?o.name():"(none \u2014 will not claim agent jobs)"}`);let i=gc();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new Dt(e.hubUrl,e.token),a=!1,c=new AbortController,l=new Map,u=null,d=null,p=!1,g=()=>{let v=s.openControlSocket();return u=v,v.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:me,protocolVersion:Ie};v.send(JSON.stringify(m))}),v.on("message",m=>{let T=m.toString("utf-8"),k=null;try{let R=JSON.parse(T);R&&typeof R=="object"&&(k=R)}catch{}if(k&&k.type==="hello"){let R=k;d=Dr(R.protocolVersion);let P=d?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${R.platformVersion} (protocol ${R.protocolVersion}) \u2014 ${P}`),d&&(p=!1);return}if(k&&k.type==="pause_job"){let R=typeof k.jobId=="string"?k.jobId:"",P=R?l.get(R):void 0;P?(console.warn(`[ws] pause_job ${R} \u2014 aborting agent`),P.paused=!0,P.abort.abort()):console.log(`[ws] pause_job ${R} \u2014 not a running job, ignoring`),R&&v.send(JSON.stringify({type:"job_paused",jobId:R}));return}if(k&&(k.type==="chat_user_message"||k.type==="chat_finalize")){let R=typeof k.jobId=="string"?k.jobId:"",P=R?l.get(R):void 0;if(P?.chatInbox)if(k.type==="chat_user_message"){let $=typeof k.text=="string"?k.text:"";$.trim()&&P.chatInbox.push({kind:"user",text:$})}else P.chatInbox.finalize();else console.log(`[ws] ${String(k.type)} ${R} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${T}`)}),v.on("close",(m,T)=>{console.log(`[ws] closed code=${m} reason=${T?.toString()||""}`),u===v&&(u=null),!a&&setTimeout(g,2e3)}),v.on("error",m=>console.warn(`[ws] error: ${m.message}`)),v},f=g(),y=async v=>{for(;!a;){if(d===!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,v);if(m.status===204)continue;if(m.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,a=!0;break}if(!m.ok){console.warn(`[claim:${v}] ${m.status} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3));continue}let T=await m.json();await w(s,T)}catch(m){if(c.signal.aborted)break;let T=m instanceof Error?m.message:String(m);console.warn(`[claim:${v}] error: ${T} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3))}}};async function w(v,m){let T={abort:new AbortController,paused:!1};m.role==="chat"&&(T.chatInbox=Lm()),l.set(m.jobId,T);let k=!1,R=null,P=null,$=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),j=async()=>{try{await v.heartbeat(m.jobId)==="claim_lost"&&(k=!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}`)}};j();let D=setInterval(()=>{j()},$),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(h(m.prompt," \u2502 "));let Ce=[],lt=null,E=400,de=25,Ye=500,Ue=()=>{if(lt&&(clearTimeout(lt),lt=null),Ce.length===0)return;let F=Ce.splice(0,Ce.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{}},Bn=F=>{Ce.push(F),Ce.length>Ye&&Ce.shift(),Ce.length>=de?Ue():lt||(lt=setTimeout(Ue,E))},ut=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,te=new Set,Gn=null;try{if(!o){k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:K,finishedAt:new Date().toISOString()});return}let F=Mc(m.jobId);console.log(`[job] ${m.jobId} workspace=${F.dir}`);let ke=b(m,r);R=ke.gitCreds,P=ke.contextGitCreds;let Le=R?.env,oi=ke.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ke.claudeOauthToken}:void 0,De=[],ir=null,Mn=null;try{let _="worktree";De=await Oc(F.dir,m.projectId,m.projectRepos,_,Le);let O=await Nc(F.dir,m.projectId,m.contextRepo,_,Le);Mn=O,ir=O?.workspacePath??null}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} materialize failed: ${O}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${O}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let ii=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 B of m.deliveries){let H=De.find(fe=>fe.name===B.name);if(H){if(m.role==="implement"&&B.baseSha&&B.baseSha!==H.baseSha){let fe=await Ec(H,B.deliveryRef,B.deliverySha,B.baseSha,_,Le);console.log(`[job] ${m.jobId} ${H.name}: base moved ${B.baseSha.slice(0,10)} \u2192 ${H.baseSha.slice(0,10)} \u2014 re-applied delivery ${B.deliverySha.slice(0,10)} (${fe.length} conflicted file(s))`),fe.length>0&&O.push(`- **${H.name}**:`,...fe.map(sr=>` - \`${sr}\``));continue}await Pc(H,B.deliveryRef,B.deliverySha,_,Le),console.log(`[job] ${m.jobId} ${H.name}: checked out delivery ${B.deliverySha.slice(0,10)} for ${m.role}`)}}return O},Fn=[];if(m.role==="build"||m.role==="implement")try{Fn=await ii()}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} delivery checkout failed: ${O}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${O}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let Hn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},si="";if(m.role==="resolve-conflict"){if(!De.some(_=>Hn[_.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} ${_}`),k||await v.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 B=Hn[O.name];if(!B)continue;let H=await No(O,B,Le);console.log(`[job] ${m.jobId} ${O.name}: merged ${B} 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)`)}si=`
558
+ ${i}`}function Ym(){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={}){vn();let e=se(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=t.profile?`sandbox-${t.profile}`:"sandbox",o=Wt(Hm(),".codepipe","logs"),i=Jr("SANDBOX_LOG",n,o);if(i.enabled){let R=new jt(i);zr(R),console.log(`[log] file logging \u2192 ${R.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe-sandbox v${me} (protocol ${Te})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let s=yc(e.llm);console.log(`llm backend: ${s?s.name():"(none \u2014 will not claim agent jobs)"}`);let a=kc();console.log(`llm retry: maxAttempts=${a.maxAttempts} backoff=${a.baseDelayMs}\u2013${a.maxDelayMs}ms budget=${a.totalBudgetMs}ms`);let c=new Lt(e.hubUrl,e.token),l=!1,p=new AbortController,d=new Map,u=null,g=null,f=!1,w=()=>{let R=c.openControlSocket();return u=R,R.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:me,protocolVersion:Te};R.send(JSON.stringify(m))}),R.on("message",m=>{let C=m.toString("utf-8"),v=null;try{let y=JSON.parse(C);y&&typeof y=="object"&&(v=y)}catch{}if(v&&v.type==="hello"){let y=v;g=Lr(y.protocolVersion);let x=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${y.platformVersion} (protocol ${y.protocolVersion}) \u2014 ${x}`),g&&(f=!1);return}if(v&&v.type==="pause_job"){let y=typeof v.jobId=="string"?v.jobId:"",x=y?d.get(y):void 0;x?(console.warn(`[ws] pause_job ${y} \u2014 aborting agent`),x.paused=!0,x.abort.abort()):console.log(`[ws] pause_job ${y} \u2014 not a running job, ignoring`),y&&R.send(JSON.stringify({type:"job_paused",jobId:y}));return}if(v&&(v.type==="chat_user_message"||v.type==="chat_finalize")){let y=typeof v.jobId=="string"?v.jobId:"",x=y?d.get(y):void 0;if(x?.chatInbox)if(v.type==="chat_user_message"){let _=typeof v.text=="string"?v.text:"";_.trim()&&x.chatInbox.push({kind:"user",text:_})}else x.chatInbox.finalize();else console.log(`[ws] ${String(v.type)} ${y} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${C}`)}),R.on("close",(m,C)=>{console.log(`[ws] closed code=${m} reason=${C?.toString()||""}`),u===R&&(u=null),!l&&setTimeout(w,2e3)}),R.on("error",m=>console.warn(`[ws] error: ${m.message}`)),R},b=w(),k=async R=>{for(;!l;){if(g===!1){f||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${me}, protocol ${Te}) \u2014 not claiming jobs until versions align.`),f=!0),await new Promise(m=>setTimeout(m,5e3));continue}try{let m=await c.claim(p.signal,R);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,l=!0;break}if(!m.ok){console.warn(`[claim:${R}] ${m.status} \u2014 backoff 5s`),await new Promise(v=>setTimeout(v,5e3));continue}let C=await m.json();await h(c,C)}catch(m){if(p.signal.aborted)break;let C=m instanceof Error?m.message:String(m);console.warn(`[claim:${R}] error: ${C} \u2014 backoff 5s`),await new Promise(v=>setTimeout(v,5e3))}}};async function h(R,m){let C={abort:new AbortController,paused:!1};m.role==="chat"&&(C.chatInbox=Ym()),d.set(m.jobId,C);let v=!1,y=null,x=null,_=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),z=async()=>{try{await R.heartbeat(m.jobId)==="claim_lost"&&(v=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(H){let ke=H instanceof Error?H.message:String(H);console.warn(`[job] ${m.jobId} heartbeat error: ${ke}`)}};z();let Dr=setInterval(()=>{z()},_),Ne=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(S(m.prompt," \u2502 "));let P=[],ne=null,qe=400,ut=25,Bn=500,Ye=()=>{if(ne&&(clearTimeout(ne),ne=null),P.length===0)return;let H=P.splice(0,P.length),ke=u;if(!ke||ke.readyState!==ke.OPEN)return;let Ue={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:H};try{ke.send(JSON.stringify(Ue))}catch{}},ie=H=>{P.push(H),P.length>Bn&&P.shift(),P.length>=ut?Ye():ne||(ne=setTimeout(Ye,qe))},ii=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,Mn=new Set,Gn=null;try{if(!s){v||await R.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:Ne,finishedAt:new Date().toISOString()});return}let H=qc(m.jobId);console.log(`[job] ${m.jobId} workspace=${H.dir}`);let ke=$(m,r);y=ke.gitCreds,x=ke.contextGitCreds;let Ue=y?.env,si=ke.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ke.claudeOauthToken}:void 0,De=[],ir=null,Fn=null;try{let O="worktree";De=await Bc(H.dir,m.projectId,m.projectRepos,O,Ue);let N=await Mc(H.dir,m.projectId,m.contextRepo,O,Ue);Fn=N,ir=N?.workspacePath??null}catch(O){let N=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} materialize failed: ${N}`),v||await R.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${N}`},startedAt:Ne,finishedAt:new Date().toISOString()}),H.dispose();return}let ai=async()=>{if(!m.deliveries||m.deliveries.length===0)return[];let O=m.contextRepo?.cloneUrl;if(!O||!Ue)throw new Error(O?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let N=[];for(let M of m.deliveries){let B=De.find(fe=>fe.name===M.name);if(B){if(m.role==="implement"&&M.baseSha&&M.baseSha!==B.baseSha){let fe=await Uc(B,M.deliveryRef,M.deliverySha,M.baseSha,O,Ue);console.log(`[job] ${m.jobId} ${B.name}: base moved ${M.baseSha.slice(0,10)} \u2192 ${B.baseSha.slice(0,10)} \u2014 re-applied delivery ${M.deliverySha.slice(0,10)} (${fe.length} conflicted file(s))`),fe.length>0&&N.push(`- **${B.name}**:`,...fe.map(sr=>` - \`${sr}\``));continue}await Nc(B,M.deliveryRef,M.deliverySha,O,Ue),console.log(`[job] ${m.jobId} ${B.name}: checked out delivery ${M.deliverySha.slice(0,10)} for ${m.role}`)}}return N},Hn=[];if(m.role==="build"||m.role==="implement")try{Hn=await ai()}catch(O){let N=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} delivery checkout failed: ${N}`),v||await R.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${N}`},startedAt:Ne,finishedAt:new Date().toISOString()}),H.dispose();return}let Kn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},ci="";if(m.role==="resolve-conflict"){if(!De.some(O=>Kn[O.name])){let O="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} ${O}`),v||await R.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:Ne,finishedAt:new Date().toISOString()}),H.dispose();return}try{let O=[];for(let N of De){let M=Kn[N.name];if(!M)continue;let B=await Uo(N,M,Ue);console.log(`[job] ${m.jobId} ${N.name}: merged ${M} into ${N.ref} \u2014 ${B.length} conflicted file(s)`),B.length>0?O.push(`- **${N.name}**:`,...B.map(fe=>` - \`${fe}\``)):O.push(`- **${N.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}ci=`
559
559
 
560
560
  ## Conflicts to resolve
561
561
 
562
- `+(_.length>0?_.join(`
562
+ `+(O.length>0?O.join(`
563
563
  `):"(no task branches to merge)")+`
564
- `}catch(_){let O=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} conflict merge failed: ${O}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${O}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}}let gu=Fn.length>0?`
564
+ `}catch(O){let N=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} conflict merge failed: ${N}`),v||await R.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${N}`},startedAt:Ne,finishedAt:new Date().toISOString()}),H.dispose();return}}let ku=Hn.length>0?`
565
565
 
566
566
  ## Base branch moved \u2014 conflicts to resolve
567
567
 
568
568
  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:
569
569
 
570
- `+Fn.join(`
570
+ `+Hn.join(`
571
571
  `)+`
572
- `:"",hu=S(x(m.prompt,De,ir),ir,m.taskId)+si+gu,Kn=[...De.map(_=>_.workspacePath),...ir?[ir]:[]];Kn.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${Kn.join(", ")}`),ut&&(Gn=setInterval(()=>{let O=u;if(!O||O.readyState!==O.OPEN)return;let B;try{B=Em(Tr(F.dir,"drafts")).filter(H=>H.endsWith(".json")).sort()}catch{return}for(let H of B){if(te.has(H))continue;if(te.size>=wi)break;let fe;try{let le=JSON.parse(Lo(Tr(F.dir,"drafts",H),"utf-8")),pt=typeof le.localRef=="string"?le.localRef:"",G=typeof le.title=="string"?le.title:"",z=typeof le.body=="string"?le.body:"";if(!pt||!G)continue;fe={localRef:pt,title:G,body:z,...le.isEpic===!0?{isEpic:!0}:{},...Array.isArray(le.links)?{links:le.links}:{}}}catch{continue}te.add(H);let sr={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:ut,child:fe};try{O.send(JSON.stringify(sr))}catch{}}},1500));try{let _={workspaceDir:F.dir,role:m.role,prompt:hu,addDirs:Kn,metadata:m.metadata??{},...m.model?{model:m.model}:{},...oi?{env:oi}:{},signal:T.abort.signal,onActivity:Bn},O=T.chatInbox?await o.run({..._,interactive:{inbox:T.chatInbox.iterable}}):await yc(o,_,{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{F.clean();for(let G of De)try{await Cc(G);let z=Hn[G.name];m.role==="resolve-conflict"&&z&&await No(G,z,Le)}catch(z){let ar=z instanceof Error?z.message:String(z);console.warn(`[job] ${m.jobId} worktree reset failed (${G.name}): ${ar}`)}try{await ii()}catch(G){let z=G instanceof Error?G.message:String(G);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${z}`)}},aborted:()=>k||T.paused}),B=[];if(Nm.has(m.role)&&De.length>0){let G=m.metadata??{},z=typeof G.commitMessage=="string"?G.commitMessage:`${m.taskId}: changes`,ar=m.contextRepo?.cloneUrl,ai=P?.env;if(!ar||!ai)throw new Error("delivery requested but "+(ar?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let yu=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let Be of De){let cr=await Tc(Be,z);if(!cr){console.log(`[job] ${m.jobId} ${Be.name}: no changes \u2014 no delivery`);continue}let Wn=`codepipe/deliveries/${yu}/${m.jobId}/${Be.name}`;await Ic(Be,cr,Wn,ar,ai),B.push({name:Be.name,deliveryRef:Wn,deliverySha:cr,baseSha:Be.baseSha}),console.log(`[job] ${m.jobId} ${Be.name}: delivered ${cr.slice(0,10)} \u2192 ${Wn}`);let ci=await jc(Be,cr);if(ci.trim().length>0){let wu=Tr("display",`${Be.name}.diff`),li=Tr(F.dir,wu);Pm(_m(li),{recursive:!0}),Am(li,ci)}}}if(m.role==="resolve-conflict"&&B.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=Lc(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(Mn)try{let G=m.role==="index"?["adr/SOURCES.md"]:m.role==="backfill"?["adr"]:[],z=await Uc(Mn,G);z.length>0&&(le=z,console.log(`[job] ${m.jobId} captured ${z.length} knowledge file(s) for Context Repo`))}catch(G){let z=G instanceof Error?G.message:String(G);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${z}`)}let pt={jobId:m.jobId,status:"succeeded",artifacts:sr.map(G=>({path:G,contentBase64:Lo(`${F.dir}/${G}`).toString("base64")})),...le?{contextWrites:le}:{},...B.length>0?{deliveries:B}:{},log:Um(O.log),startedAt:K,finishedAt:new Date().toISOString(),usage:O.usage,...O.rateLimit?{rateLimit:O.rateLimit}:{},...H?{build:H}:{}};if(k||T.paused)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${T.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await v.submitResult(pt),console.log(`[job] ${m.jobId} done \u2014 uploaded ${pt.artifacts.length} artifact(s):`);for(let G of pt.artifacts){let z=Buffer.from(G.contentBase64,"base64").length;console.log(` \xB7 ${G.path} (${z} bytes)`)}pt.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(k)console.warn(`[job] ${m.jobId} failed after claim lost (${O}) \u2014 skipping result upload`);else{let B=hc(_);console.warn(B?`[job] ${m.jobId} failed: ${O} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${O}`),await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:K,finishedAt:new Date().toISOString(),...B?{authError:!0}:{}})}}finally{F.dispose()}}finally{clearInterval(D),Gn&&clearInterval(Gn),Ue(),T.chatInbox?.close(),l.delete(m.jobId),R?.cleanup(),P?.cleanup()}}function b(v,m){if(!v.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${v.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let T;try{T=JSON.parse(sn(m,v.credBundle).toString("utf-8"))}catch($){return console.warn(`[job] ${v.jobId} failed to open credBundle: ${$ instanceof Error?$.message:String($)}`),{gitCreds:null,contextGitCreds:null}}let k=_o(T);k&&console.log(`[job] ${v.jobId} cred bundle opened \u2014 git creds configured`);let R=kc(T,v.contextRepo.cloneUrl),P={gitCreds:k,contextGitCreds:R};return T.claudeOauthToken&&(P.claudeOauthToken=T.claudeOauthToken),P}function h(v,m){return v.split(`
573
- `).map(T=>m+T).join(`
574
- `)}function x(v,m,T){let k=m[0]?.workspacePath??"";return v.replace(/\{\{codeDir\}\}/g,k).replace(/\{\{codeRoot\}\}/g,k?k.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,T??"")}function S(v,m,T){let k=v,R=T.includes("::")?"":T.split(":",2)[1]??"",P=$=>{if(!m||!R)return"";try{return Lo(Tr(m,"tasks",R,$),"utf-8").trim()}catch{return""}};if(k.includes("{{solutionMd}}")){let $=P("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";k=k.replace(/\{\{solutionMd\}\}/g,()=>$)}if(k.includes("{{taskDescription}}")){let $=P("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";k=k.replace(/\{\{taskDescription\}\}/g,()=>$)}return k}let N=v=>{if(a)return;a=!0,console.log(`
575
- [${v}] shutting down`),c.abort();let m=[...l.keys()];for(let R of l.values())R.abort.abort();let T=new AbortController,k=setTimeout(()=>T.abort(),3e3);(async()=>(await Promise.all(m.map(async R=>{try{await s.releaseJob(R,`sandbox ${v}`,T.signal),console.log(`[${v}] released job ${R}`)}catch(P){let $=P instanceof Error?P.message:String(P);console.warn(`[${v}] release failed: ${$} (sweeper will reclaim)`)}})),clearTimeout(k),f.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM"));let I=[y("implementation")];e.planningLane!==!1?I.push(y("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(I)}async function Hc(t={profile:void 0}){let e=he(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=gn(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 d=JSON.parse(u);d.type==="registered"?(a=!!d.ok,clearTimeout(c),r.send("ping")):d.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of 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 mg}from"node:child_process";import{existsSync as Jt,mkdirSync as pl,readFileSync as dl,readdirSync as gg,writeFileSync as fl}from"node:fs";import{join as $t,resolve as ml}from"node:path";import{setTimeout as Mo}from"node:timers/promises";import{cancel as hg,confirm as zt,intro as gl,isCancel as An,log as C,outro as Fo,password as Xt,select as st,spinner as hl,text as Z}from"@clack/prompts";import{simpleGit as On}from"simple-git";async function Yt(t,e,r){return e.host==="github"?Bm(t,e,r):e.host==="gitlab"?qm(t,e,r):Vm(t,e,r)}async function Kc(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 Wc(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 qc(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 Yc(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 Wc(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 qc(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 Yc(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 Dm="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(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?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 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 Gm(n,e,r),i=await Fm(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 Hm(n,o.owner,o.name,a.path,i)||await Km(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 Gm(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 Wc(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Mm(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 Mm(t,e){let{status:r,data:n}=await it(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Fm(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 Hm(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 Km(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 Wm="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(Wm+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 qm(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 qc(n,e)} (attach joins an existing Context Repo and never creates one)`);let d=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(d.data?.username!==e.owner){let f=await ot(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);p.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await 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 d=1;;d++){let g=(await ot(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${d}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of g)l.add(f.path);if(g.length<100)break}let u=c.filter(d=>!l.has(d.path)).map(d=>({action:"create",file_path:d.path,content:d.content}));return u.length>0?await 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 Ym="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(Ym+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 Vm(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 Yc(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let d=await qt(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(d.status===404||!d.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=d.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let d of c)(await qt(n,"GET",`${o}/src/${encodeURIComponent(a)}/${d.path}?format=meta`)).status===404&&l.push(d);if(l.length>0){let d=new URLSearchParams;d.set("message","chore(codepipe): scaffold context repo files"),d.set("branch",a);for(let g of l)d.set(g.path,g.content);if((await qt(n,"POST",`${o}/src`,{form:d})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(d=>d.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Jm={"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=Jm[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 zm}from"node:crypto";import{existsSync as Vc,mkdirSync as Xm,readFileSync as Jc,readdirSync as Qm,rmSync as En,writeFileSync as Zm}from"node:fs";import{homedir as eg}from"node:os";import{dirname as tg,join as Do}from"node:path";var rg=24*60*60*1e3;function zc(){return Do(eg(),".codepipe","init-drafts")}function Bo(t){let e=zm("sha256").update(t).digest("hex").slice(0,16);return Do(zc(),`${e}.json`)}function Xc(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=rg)}function Qc(t){let e=Bo(t);if(!Vc(e))return null;try{let r=JSON.parse(Jc(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Xc(r.savedAt)?(En(e,{force:!0}),null):r}catch{return null}}function Go(t){En(Bo(t),{force:!0})}function Zc(){let t=zc();if(Vc(t))for(let e of Qm(t)){let r=Do(t,e);try{let n=JSON.parse(Jc(r,"utf-8"));Xc(n.savedAt)&&En(r,{force:!0})}catch{En(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(){Go(this.cwd)}persist(){let e=Bo(this.cwd);Xm(tg(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Zm(e,JSON.stringify(r,null,2)+`
576
- `,{mode:384})}};function el(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"}}function tl(){return{message:"Reconstruct architecture decisions from the existing code first? (deep one-off analysis \u2014 proposes decision drafts you review before they become canonical)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes \u2014 analyse and propose decision drafts"},{value:"skip",label:"Skip"}],initialValue:"yes"}}async function rl(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 ng}from"node:fs";import{join as og}from"node:path";import{simpleGit as ig}from"simple-git";var sg=3,ag=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,cg=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"]);function lg(t){let e=t.split("/");return e[e.length-1]??t}function nl(t){if(t.filter(r=>!ag.test(lg(r))).length>sg)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(cg.has(n))return!0}return!1}async function ug(t){try{let r=(await ig(t).raw(["ls-files"])).split(`
577
- `).map(n=>n.trim()).filter(Boolean);return nl(r)}catch{return!1}}async function pg(t,e){if(t.host!=="github")return!1;let r=e.github?.token;if(!r)return!1;let n=t.defaultBranch??"main";try{let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.repoName}/contents/?ref=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status!==200)return!1;let i=await o.json();return Array.isArray(i)?nl(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function ol(t,e){for(let r of t)try{let n=e.localRoot!=null?og(e.localRoot,r.mountAs??r.name):null;if(n&&ng(n)?await ug(n):await pg(r,e.tokens))return!0}catch{}return!1}import{existsSync as il}from"node:fs";import{join as sl}from"node:path";import{simpleGit as al}from"simple-git";var dg={info:t=>console.log(t),warn:t=>console.warn(t)};async function jr(t,e,r={}){let n=r.log??dg,o=[];for(let i of e){let s=sl(t,i.mountAs),a=xi(i);if(!il(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 al().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let d=u instanceof Error?u.message:String(u);n.warn(`clone failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}continue}if(!il(sl(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=al(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!fg(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 d=u instanceof Error?u.message:String(u);n.warn(`fetch failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}}return o}function fg(t,e){return cl(t)===cl(e)}function cl(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function ll(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 jr(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 ul=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function J(t){hg(t),process.exit(1)}function be(t){return An(t)&&J("aborted"),t}function W(t){return An(t)&&J("aborted"),typeof t=="string"?t:""}async function yl(t={}){gl("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Zc();let r=Qc(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}))?(C.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Vt(e,r),o=!0):(Go(e),n=new Vt(e)):n=new Vt(e);let i=t.force===!0?null:await Ko(e),s=await n.ask("target",async()=>be(await st({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?C.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||bl(e,t.force===!0));let c=await n.ask("hubUrl",async()=>W(await Z({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:d}=await n.ask("bootstrap",()=>Zt(c,l)),p=null;s==="farm"&&(p=await yg(c,u));let g=a?bg(a.parsed.repoName):"",f=await n.ask("projectId",async()=>W(await Z({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:E=>ft.test(E.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>W(await Z({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()),w=await n.ask("automationLevel",async()=>be(await st({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),b=await n.ask("youtrack",()=>Cl()),h=await n.ask("youtrackProjectKey",async()=>W(await Z({message:"YouTrack project key",placeholder:"DEV",validate:E=>E.trim().length>0?void 0:"required"})).trim()),x=await n.ask("youtrackWrites",async()=>be(await zt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),S=n.get("tokens")??{},N=()=>n.set("tokens",S),I=await n.ask("repos",()=>vg(S,l,a,{onCred:N,initial:n.get("reposPartial")??[],onProgress:E=>n.set("reposPartial",E)}));n.delete("reposPartial");let v=await Sg(await n.ask("contextRepo",()=>vl(f,I,S,l)),f,I,S,l,N,E=>n.set("contextRepo",E)),{spec:m,mode:T}=v;C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let k=await n.ask("assigneeLogin",async()=>W(await Z({message:"your YouTrack login (the assignee value)",...b.login?{initialValue:b.login}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),R=await n.ask("claudeToken",()=>Eg(s==="farm")),P={projectId:f,name:y,automationLevel:w,repos:I,youtrackProjectKey:h};C.step(`${T==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let $;try{$=await Yt(P,m,{...Sl(S),youtrackWrites:x,trackerUrl:b.url,mode:T,log:{info:E=>C.message(E),warn:E=>C.warn(E)}})}catch(E){J(`Context Repo provisioning failed: ${E instanceof Error?E.message:String(E)}`)}P.contextRepo=$,C.success(`Context Repo ready: ${$.owner}/${$.name}@${$.branch}`),C.step(`registering project on ${c}\u2026`);let j;try{j=await tt(c,u,P)}catch(E){if(E instanceof A&&E.status===409){C.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{j=await M(c,u,f)}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 D=j.contextRepo??$;C.success(`project ${j.projectId} ready (${j.provisioningStatus})`);let K=await jg(D),Ce={url:b.url,token:b.token};if(s==="farm"){let E=p,de={...S,...K?{contextWrite:K}:{},...R?{claude:{oauthToken:R}}:{},youtrack:Ce},Ye=S.github?.token;if(D.host==="github"&&Ye)try{let te=Ka(`devpipe-${f}`);await Wa(D,Ye,te.publicKey,`devpipe-${f}`),de.contextSsh={privateKey:te.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(te){C.warn(`could not set up Context Repo SSH deploy key (${te instanceof Error?te.message:String(te)}); the farm will fall back to the token path.`)}let Ue={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:de,contextRepo:D,projectConfig:_e(P,x,b.url,k||void 0)},Bn=We(E.farm.publicKey,JSON.stringify(Ue));C.step(`handing project ${f} to farm ${E.farm.name}\u2026`);let ut;try{ut=await hn(c,u,E.farm.farmId,{projectId:f,sealedBundle:Bn})}catch(te){throw te instanceof A&&J(te.status===409?`farm ${E.farm.name} is offline \u2014 start it and re-run.`:te.status===504?`farm ${E.farm.name} did not respond in time.`:`HUB \u2192 ${te.status} ${te.message}`),te}ut.ok||J(`farm rejected provisioning: ${ut.error??"unknown error"}`),await Ho(c,u,f,D,Ye,j.repos,null,S),n.clear(),Fo(`done. project ${f} is now hosted on farm ${E.farm.name} (daemon ${ut.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Rl(S),await kl(e,D.cloneUrl,D.branch),xl(e),a&&await $g(e);{let E=$t(e,Pe);At(E);let de=_e(P,x,b.url,k||void 0),Ye=dr(E,de);Ye.length>0&&C.success(`local project config \u2192 .codepipe/{${Ye.join(", ")}}`),ht(f,de,{info:Ue=>C.message(Ue),warn:Ue=>C.warn(Ue)})}await $l(e,j.repos);let lt={hubUrl:c,cliToken:u,projectId:f,...S,...K?{contextWrite:K}:{},...R?{claude:{oauthToken:R}}:{},youtrack:Ce};V(lt),Fe({hubUrl:c,cliToken:u,projectId:f,accountEmail:d},f),C.success(`secrets \u2192 ${Ee(f)}`),await Ho(c,u,f,D,S.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,j.repos,e,S),n.clear(),Fo("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Ho(t,e,r,n,o,i=[],s=null,a={}){let c=await rl(n,o);if(!c){let d=!1;try{d=await ol(i,{localRoot:s,tokens:a})}catch{d=!1}if(d){let p=tl(),g=await st({message:p.message,options:p.options,initialValue:p.initialValue});if(!An(g)&&g===p.proceedValue)try{let{jobId:f}=await $r(t,e,r,{reindex:!1,backfill:!0});C.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){C.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}}}let l=el(c),u=await st({message:l.message,options:l.options,initialValue:l.initialValue});if(!(An(u)||u!==l.proceedValue))try{let{jobId:d}=await $r(t,e,r,{reindex:l.reindex});C.success(`indexing queued (job ${d}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(d){C.warn(`could not start indexing: ${d instanceof Error?d.message:String(d)}. You can retry later \u2014 registration is not affected.`)}}async function yg(t,e){let r;try{r=await pa(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 st({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=mn(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:
572
+ `:"",$u=I(U(m.prompt,De,ir),ir,m.taskId)+ci+ku,Wn=[...De.map(O=>O.workspacePath),...ir?[ir]:[]];Wn.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${Wn.join(", ")}`),ii&&(Gn=setInterval(()=>{let N=u;if(!N||N.readyState!==N.OPEN)return;let M;try{M=Gm(Wt(H.dir,"drafts")).filter(B=>B.endsWith(".json")).sort()}catch{return}for(let B of M){if(Mn.has(B))continue;if(Mn.size>=$i)break;let fe;try{let ue=JSON.parse(Lo(Wt(H.dir,"drafts",B),"utf-8")),pt=typeof ue.localRef=="string"?ue.localRef:"",G=typeof ue.title=="string"?ue.title:"",J=typeof ue.body=="string"?ue.body:"";if(!pt||!G)continue;fe={localRef:pt,title:G,body:J,...ue.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ue.links)?{links:ue.links}:{}}}catch{continue}Mn.add(B);let sr={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:ii,child:fe};try{N.send(JSON.stringify(sr))}catch{}}},1500));try{let O={workspaceDir:H.dir,role:m.role,prompt:$u,addDirs:Wn,metadata:m.metadata??{},...m.model?{model:m.model}:{},...si?{env:si}:{},signal:C.abort.signal,onActivity:ie},N=C.chatInbox?await s.run({...O,interactive:{inbox:C.chatInbox.iterable}}):await xc(s,O,{jobId:m.jobId,policy:a,onBeforeRetry:async()=>{H.clean();for(let G of De)try{await Ec(G);let J=Kn[G.name];m.role==="resolve-conflict"&&J&&await Uo(G,J,Ue)}catch(J){let ar=J instanceof Error?J.message:String(J);console.warn(`[job] ${m.jobId} worktree reset failed (${G.name}): ${ar}`)}try{await ai()}catch(G){let J=G instanceof Error?G.message:String(G);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${J}`)}},aborted:()=>v||C.paused}),M=[];if(Wm.has(m.role)&&De.length>0){let G=m.metadata??{},J=typeof G.commitMessage=="string"?G.commitMessage:`${m.taskId}: changes`,ar=m.contextRepo?.cloneUrl,li=x?.env;if(!ar||!li)throw new Error("delivery requested but "+(ar?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let xu=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let Le of De){let cr=await Ac(Le,J);if(!cr){console.log(`[job] ${m.jobId} ${Le.name}: no changes \u2014 no delivery`);continue}let qn=`codepipe/deliveries/${xu}/${m.jobId}/${Le.name}`;await _c(Le,cr,qn,ar,li),M.push({name:Le.name,deliveryRef:qn,deliverySha:cr,baseSha:Le.baseSha}),console.log(`[job] ${m.jobId} ${Le.name}: delivered ${cr.slice(0,10)} \u2192 ${qn}`);let ui=await Oc(Le,cr);if(ui.trim().length>0){let vu=Wt("display",`${Le.name}.diff`),pi=Wt(H.dir,vu);Mm(Km(pi),{recursive:!0}),Fm(pi,ui)}}}if(m.role==="resolve-conflict"&&M.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 B;m.role==="build"&&(B=Fc(H.dir),console.log(`[job] ${m.jobId} build verdict: ok=${B.ok}`+(B.failedStep?` failedStep=${B.failedStep}`:"")));let fe=N.artifactPaths.length>0?N.artifactPaths:H.listFiles(),sr=Array.from(new Set(fe)),ue;if(Fn)try{let G=m.role==="index"?["adr/SOURCES.md"]:m.role==="backfill"?["adr"]:[],J=await Gc(Fn,G);J.length>0&&(ue=J,console.log(`[job] ${m.jobId} captured ${J.length} knowledge file(s) for Context Repo`))}catch(G){let J=G instanceof Error?G.message:String(G);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${J}`)}let pt={jobId:m.jobId,status:"succeeded",artifacts:sr.map(G=>({path:G,contentBase64:Lo(`${H.dir}/${G}`).toString("base64")})),...ue?{contextWrites:ue}:{},...M.length>0?{deliveries:M}:{},log:qm(N.log),startedAt:Ne,finishedAt:new Date().toISOString(),usage:N.usage,...N.rateLimit?{rateLimit:N.rateLimit}:{},...B?{build:B}:{}};if(v||C.paused)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${C.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await R.submitResult(pt),console.log(`[job] ${m.jobId} done \u2014 uploaded ${pt.artifacts.length} artifact(s):`);for(let G of pt.artifacts){let J=Buffer.from(G.contentBase64,"base64").length;console.log(` \xB7 ${G.path} (${J} bytes)`)}pt.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(O){let N=O instanceof Error?O.message:String(O);if(C.paused)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(v)console.warn(`[job] ${m.jobId} failed after claim lost (${N}) \u2014 skipping result upload`);else{let M=$c(O),B=O instanceof ot;console.warn(M?`[job] ${m.jobId} failed: ${N} (Claude auth \u2014 token invalid/expired)`:B?`[job] ${m.jobId} failed: ${N} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${m.jobId} failed: ${N}`),await R.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:N},startedAt:Ne,finishedAt:new Date().toISOString(),...M?{authError:!0}:{},...B?{buildInconclusive:!0}:{}})}}finally{H.dispose()}}finally{clearInterval(Dr),Gn&&clearInterval(Gn),Ye(),C.chatInbox?.close(),d.delete(m.jobId),y?.cleanup(),x?.cleanup()}}function $(R,m){if(!R.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${R.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let C;try{C=JSON.parse(sn(m,R.credBundle).toString("utf-8"))}catch(_){return console.warn(`[job] ${R.jobId} failed to open credBundle: ${_ instanceof Error?_.message:String(_)}`),{gitCreds:null,contextGitCreds:null}}let v=Oo(C);v&&console.log(`[job] ${R.jobId} cred bundle opened \u2014 git creds configured`);let y=Rc(C,R.contextRepo.cloneUrl),x={gitCreds:v,contextGitCreds:y};return C.claudeOauthToken&&(x.claudeOauthToken=C.claudeOauthToken),x}function S(R,m){return R.split(`
573
+ `).map(C=>m+C).join(`
574
+ `)}function U(R,m,C){let v=m[0]?.workspacePath??"";return R.replace(/\{\{codeDir\}\}/g,v).replace(/\{\{codeRoot\}\}/g,v?v.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,C??"")}function I(R,m,C){let v=R,y=C.includes("::")?"":C.split(":",2)[1]??"",x=_=>{if(!m||!y)return"";try{return Lo(Wt(m,"tasks",y,_),"utf-8").trim()}catch{return""}};if(v.includes("{{solutionMd}}")){let _=x("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";v=v.replace(/\{\{solutionMd\}\}/g,()=>_)}if(v.includes("{{taskDescription}}")){let _=x("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";v=v.replace(/\{\{taskDescription\}\}/g,()=>_)}return v}let E=R=>{if(l)return;l=!0,console.log(`
575
+ [${R}] shutting down`),p.abort();let m=[...d.keys()];for(let y of d.values())y.abort.abort();let C=new AbortController,v=setTimeout(()=>C.abort(),3e3);(async()=>(await Promise.all(m.map(async y=>{try{await c.releaseJob(y,`sandbox ${R}`,C.signal),console.log(`[${R}] released job ${y}`)}catch(x){let _=x instanceof Error?x.message:String(x);console.warn(`[${R}] release failed: ${_} (sweeper will reclaim)`)}})),clearTimeout(v),b.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>E("SIGINT")),process.on("SIGTERM",()=>E("SIGTERM"));let j=[k("implementation")];e.planningLane!==!1?j.push(k("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(j)}async function Vc(t={profile:void 0}){let e=he(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=gn(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 p=l.toString("utf-8");if(s.push(`msg:${p}`),p!=="pong")try{let d=JSON.parse(p);d.type==="registered"?(a=!!d.ok,clearTimeout(c),r.send("ping")):d.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,p)=>{s.push(`close:${l}:${p?.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 F(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=se(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 Sg}from"node:child_process";import{existsSync as Jt,mkdirSync as hl,readFileSync as yl,readdirSync as Rg,writeFileSync as wl}from"node:fs";import{join as $t,resolve as bl}from"node:path";import{setTimeout as Fo}from"node:timers/promises";import{cancel as Cg,confirm as zt,intro as kl,isCancel as An,log as T,outro as Ho,password as Xt,select as at,spinner as $l,text as ee}from"@clack/prompts";import{simpleGit as On}from"simple-git";async function Yt(t,e,r){return e.host==="github"?Jm(t,e,r):e.host==="gitlab"?rg(t,e,r):og(t,e,r)}async function Jc(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 st(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await zc(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 it(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Xc(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 Qc(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 zc(t,e){let r=!1;try{r=(await st(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 Xc(t,e){let r=!1;try{r=(await it(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 Qc(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 Vm="https://api.github.com";async function st(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(Vm+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 Jm(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 zm(n,e,r),i=await Qm(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 Zm(n,o.owner,o.name,a.path,i)||await eg(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 zm(t,e,r){let n=await st(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 zc(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Xm(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 st(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 Xm(t,e){let{status:r,data:n}=await st(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Qm(t,e,r){let{data:n}=await st(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Zm(t,e,r,n,o){let{status:i,data:s}=await st(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function eg(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 st(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var tg="https://gitlab.com/api/v4";async function it(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(tg+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 rg(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 it(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 Xc(n,e)} (attach joins an existing Context Repo and never creates one)`);let d=await it(n,"GET","/user"),u={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(d.data?.username!==e.owner){let f=await it(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);u.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await it(n,"POST","/projects",u);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 d=1;;d++){let g=(await it(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${d}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of g)l.add(f.path);if(g.length<100)break}let p=c.filter(d=>!l.has(d.path)).map(d=>({action:"create",file_path:d.path,content:d.content}));return p.length>0?await it(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var ng="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(ng+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 og(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 Qc(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let d=await qt(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(d.status===404||!d.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=d.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let d of c)(await qt(n,"GET",`${o}/src/${encodeURIComponent(a)}/${d.path}?format=meta`)).status===404&&l.push(d);if(l.length>0){let d=new URLSearchParams;d.set("message","chore(codepipe): scaffold context repo files"),d.set("branch",a);for(let g of l)d.set(g.path,g.content);if((await qt(n,"POST",`${o}/src`,{form:d})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let p=i.links?.clone?.find(d=>d.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:p??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var ig={"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=ig[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 sg}from"node:crypto";import{existsSync as Zc,mkdirSync as ag,readFileSync as el,readdirSync as cg,rmSync as En,writeFileSync as lg}from"node:fs";import{homedir as ug}from"node:os";import{dirname as pg,join as Bo}from"node:path";var dg=24*60*60*1e3;function tl(){return Bo(ug(),".codepipe","init-drafts")}function Mo(t){let e=sg("sha256").update(t).digest("hex").slice(0,16);return Bo(tl(),`${e}.json`)}function rl(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=dg)}function nl(t){let e=Mo(t);if(!Zc(e))return null;try{let r=JSON.parse(el(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:rl(r.savedAt)?(En(e,{force:!0}),null):r}catch{return null}}function Go(t){En(Mo(t),{force:!0})}function ol(){let t=tl();if(Zc(t))for(let e of cg(t)){let r=Bo(t,e);try{let n=JSON.parse(el(r,"utf-8"));rl(n.savedAt)&&En(r,{force:!0})}catch{En(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(){Go(this.cwd)}persist(){let e=Mo(this.cwd);ag(pg(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};lg(e,JSON.stringify(r,null,2)+`
576
+ `,{mode:384})}};function il(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"}}function sl(){return{message:"Reconstruct architecture decisions from the existing code first? (deep one-off analysis \u2014 proposes decision drafts you review before they become canonical)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes \u2014 analyse and propose decision drafts"},{value:"skip",label:"Skip"}],initialValue:"yes"}}async function al(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 fg}from"node:fs";import{join as mg}from"node:path";import{simpleGit as gg}from"simple-git";var hg=3,yg=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,wg=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"]);function bg(t){let e=t.split("/");return e[e.length-1]??t}function cl(t){if(t.filter(r=>!yg.test(bg(r))).length>hg)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(wg.has(n))return!0}return!1}async function kg(t){try{let r=(await gg(t).raw(["ls-files"])).split(`
577
+ `).map(n=>n.trim()).filter(Boolean);return cl(r)}catch{return!1}}async function $g(t,e){if(t.host!=="github")return!1;let r=e.github?.token;if(!r)return!1;let n=t.defaultBranch??"main";try{let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.repoName}/contents/?ref=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status!==200)return!1;let i=await o.json();return Array.isArray(i)?cl(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function ll(t,e){for(let r of t)try{let n=e.localRoot!=null?mg(e.localRoot,r.mountAs??r.name):null;if(n&&fg(n)?await kg(n):await $g(r,e.tokens))return!0}catch{}return!1}import{existsSync as ul}from"node:fs";import{join as pl}from"node:path";import{simpleGit as dl}from"simple-git";var xg={info:t=>console.log(t),warn:t=>console.warn(t)};async function Ir(t,e,r={}){let n=r.log??xg,o=[];for(let i of e){let s=pl(t,i.mountAs),a=Ri(i);if(!ul(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 dl().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(p){let d=p instanceof Error?p.message:String(p);n.warn(`clone failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}continue}if(!ul(pl(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=dl(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!vg(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(p){let d=p instanceof Error?p.message:String(p);n.warn(`fetch failed for ${i.mountAs}: ${d}`),o.push({mountAs:i.mountAs,status:"error",detail:d})}}return o}function vg(t,e){return fl(t)===fl(e)}function fl(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function ml(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 gl=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function V(t){Cg(t),process.exit(1)}function be(t){return An(t)&&V("aborted"),t}function W(t){return An(t)&&V("aborted"),typeof t=="string"?t:""}async function xl(t={}){kl("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();ol();let r=nl(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}))?(T.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Vt(e,r),o=!0):(Go(e),n=new Vt(e)):n=new Vt(e);let i=t.force===!0?null:await Wo(e),s=await n.ask("target",async()=>be(await at({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?T.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||Sl(e,t.force===!0));let c=await n.ask("hubUrl",async()=>W(await ee({message:"HUB URL",placeholder:Ce,initialValue:L("HUB_URL")??Ce,validate:P=>P.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Qt()),{cliToken:p,accountEmail:d}=await n.ask("bootstrap",()=>Zt(c,l)),u=null;s==="farm"&&(u=await Tg(c,p));let g=a?jg(a.parsed.repoName):"",f=await n.ask("projectId",async()=>W(await ee({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:P=>ft.test(P.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),w=await n.ask("projectName",async()=>W(await ee({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:P=>P.trim().length>0?void 0:"required"})).trim()),b=await n.ask("automationLevel",async()=>be(await at({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),k=await n.ask("youtrack",()=>El()),h=await n.ask("youtrackProjectKey",async()=>W(await ee({message:"YouTrack project key",placeholder:"DEV",validate:P=>P.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}))),S=n.get("tokens")??{},U=()=>n.set("tokens",S),I=await n.ask("repos",()=>_g(S,l,a,{onCred:U,initial:n.get("reposPartial")??[],onProgress:P=>n.set("reposPartial",P)}));n.delete("reposPartial");let E=await Og(await n.ask("contextRepo",()=>Il(f,I,S,l)),f,I,S,l,U,P=>n.set("contextRepo",P)),{spec:j,mode:R}=E;T.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let m=await n.ask("assigneeLogin",async()=>W(await ee({message:"your YouTrack login (the assignee value)",...k.login?{initialValue:k.login}:{},validate:P=>P.trim().length>0?void 0:"required"})).trim()),C=await n.ask("claudeToken",()=>Gg(s==="farm")),v={projectId:f,name:w,automationLevel:b,repos:I,youtrackProjectKey:h};T.step(`${R==="attach"?"attaching to":"provisioning"} Context Repo ${j.owner}/${j.name} (${j.host})\u2026`);let y;try{y=await Yt(v,j,{...jl(S),youtrackWrites:$,trackerUrl:k.url,mode:R,log:{info:P=>T.message(P),warn:P=>T.warn(P)}})}catch(P){V(`Context Repo provisioning failed: ${P instanceof Error?P.message:String(P)}`)}v.contextRepo=y,T.success(`Context Repo ready: ${y.owner}/${y.name}@${y.branch}`),T.step(`registering project on ${c}\u2026`);let x;try{x=await tt(c,p,v)}catch(P){if(P instanceof A&&P.status===409){T.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{x=await F(c,p,f)}catch(ne){throw ne instanceof A&&V(`HUB \u2192 ${ne.status} ${ne.message}`),ne}}else if(P instanceof A&&P.status===401)n.delete("cliToken"),V("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(P instanceof A)V(`HUB \u2192 ${P.status} ${P.message}`);else throw P}let _=x.contextRepo??y;T.success(`project ${x.projectId} ready (${x.provisioningStatus})`);let z=await Bg(_),Dr={url:k.url,token:k.token};if(s==="farm"){let P=u,ne={...S,...z?{contextWrite:z}:{},...C?{claude:{oauthToken:C}}:{},youtrack:Dr},qe=S.github?.token;if(_.host==="github"&&qe)try{let ie=Ja(`devpipe-${f}`);await za(_,qe,ie.publicKey,`devpipe-${f}`),ne.contextSsh={privateKey:ie.privateKey},T.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ie){T.warn(`could not set up Context Repo SSH deploy key (${ie instanceof Error?ie.message:String(ie)}); the farm will fall back to the token path.`)}let ut={projectId:f,config:{hubUrl:c,cliToken:p,projectId:f},secrets:ne,contextRepo:_,projectConfig:Ae(v,$,k.url,m||void 0)},Bn=Ke(P.farm.publicKey,JSON.stringify(ut));T.step(`handing project ${f} to farm ${P.farm.name}\u2026`);let Ye;try{Ye=await hn(c,p,P.farm.farmId,{projectId:f,sealedBundle:Bn})}catch(ie){throw ie instanceof A&&V(ie.status===409?`farm ${P.farm.name} is offline \u2014 start it and re-run.`:ie.status===504?`farm ${P.farm.name} did not respond in time.`:`HUB \u2192 ${ie.status} ${ie.message}`),ie}Ye.ok||V(`farm rejected provisioning: ${Ye.error??"unknown error"}`),await Ko(c,p,f,_,qe,x.repos,null,S),n.clear(),Ho(`done. project ${f} is now hosted on farm ${P.farm.name} (daemon ${Ye.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Pl(S),await Rl(e,_.cloneUrl,_.branch),Tl(e),a&&await Eg(e);{let P=$t(e,je);At(P);let ne=Ae(v,$,k.url,m||void 0),qe=dr(P,ne);qe.length>0&&T.success(`local project config \u2192 .codepipe/{${qe.join(", ")}}`),ht(f,ne,{info:ut=>T.message(ut),warn:ut=>T.warn(ut)})}await Cl(e,x.repos);let Ne={hubUrl:c,cliToken:p,projectId:f,...S,...z?{contextWrite:z}:{},...C?{claude:{oauthToken:C}}:{},youtrack:Dr};Y(Ne),Ge({hubUrl:c,cliToken:p,projectId:f,accountEmail:d},f),T.success(`secrets \u2192 ${Pe(f)}`),await Ko(c,p,f,_,S.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,x.repos,e,S),n.clear(),Ho("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Ko(t,e,r,n,o,i=[],s=null,a={}){let c=await al(n,o);if(!c){let d=!1;try{d=await ll(i,{localRoot:s,tokens:a})}catch{d=!1}if(d){let u=sl(),g=await at({message:u.message,options:u.options,initialValue:u.initialValue});if(!An(g)&&g===u.proceedValue)try{let{jobId:f}=await $r(t,e,r,{reindex:!1,backfill:!0});T.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){T.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}}}let l=il(c),p=await at({message:l.message,options:l.options,initialValue:l.initialValue});if(!(An(p)||p!==l.proceedValue))try{let{jobId:d}=await $r(t,e,r,{reindex:l.reindex});T.success(`indexing queued (job ${d}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(d){T.warn(`could not start indexing: ${d instanceof Error?d.message:String(d)}. You can retry later \u2014 registration is not affected.`)}}async function Tg(t,e){let r;try{r=await ha(t,e)}catch(c){throw c instanceof A&&V(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&V("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 at({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=mn(i.farmId,i.publicKey)}catch(c){V(c instanceof Error?c.message:String(c))}return be(await zt({message:`confirm farm ${i.name} cred-channel fingerprint:
578
578
  ${s}
579
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||J("farm fingerprint not confirmed \u2014 aborting."),fn(i.farmId,s),{farm:i,fingerprint:s}}async function wl(t){gl(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();bl(e,t.force===!0);let r=W(await Z({message:"HUB URL",initialValue:L("HUB_URL")??Te,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Qt(),{cliToken:o,accountEmail:i}=await Zt(r,n);C.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await M(r,o,t.projectId)}catch(d){throw d instanceof A&&J(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||J(`project ${t.projectId} has no Context Repo on HUB`);let a=await Cl(),c={},l=new Set(s.repos.map(d=>d.host));l.add(s.contextRepo.host);for(let d of l)await _n(d,c,d===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===d)?.owner,n);Rl(c),await kl(e,s.contextRepo.cloneUrl,s.contextRepo.branch),xl(e);{let d=$t(e,Pe);At(d);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),f=dr(d,g);f.length>0&&C.success(`local project config \u2192 .codepipe/{${f.join(", ")}} (defaults \u2014 review and adjust)`),ht(t.projectId,g,{info:y=>C.message(y),warn:y=>C.warn(y)})}await $l(e,s.repos);let u={hubUrl:r,cliToken:o,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};V(u),Fe({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),C.success(`secrets \u2192 ${Ee(t.projectId)}`),await Ho(r,o,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,c),Fo("done.")}function bl(t,e){if(!Jt(t)){pl(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=gg(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 Ko(t){if(!Jt($t(t,".git")))return null;try{let r=(await On(t).remote(["get-url","origin"])||"").toString().trim(),n=r?we(r):null;return n?{parsed:n,defaultBranch:await wg(t)}:null}catch{return null}}async function wg(t){let e=On(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 bg(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return ft.test(e)?e:""}function kg(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function $g(t){let e=$t(t,".gitignore"),r=Jt(e)?dl(e,"utf-8"):"";if(kg(r))return;if(!be(await zt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){C.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
579
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||V("farm fingerprint not confirmed \u2014 aborting."),fn(i.farmId,s),{farm:i,fingerprint:s}}async function vl(t){kl(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Sl(e,t.force===!0);let r=W(await ee({message:"HUB URL",initialValue:L("HUB_URL")??Ce,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Qt(),{cliToken:o,accountEmail:i}=await Zt(r,n);T.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await F(r,o,t.projectId)}catch(d){throw d instanceof A&&V(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||V(`project ${t.projectId} has no Context Repo on HUB`);let a=await El(),c={},l=new Set(s.repos.map(d=>d.host));l.add(s.contextRepo.host);for(let d of l)await _n(d,c,d===s.contextRepo.host?s.contextRepo.owner:s.repos.find(u=>u.host===d)?.owner,n);Pl(c),await Rl(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Tl(e);{let d=$t(e,je);At(d);let u={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=Ae(u,!0,a.url),f=dr(d,g);f.length>0&&T.success(`local project config \u2192 .codepipe/{${f.join(", ")}} (defaults \u2014 review and adjust)`),ht(t.projectId,g,{info:w=>T.message(w),warn:w=>T.warn(w)})}await Cl(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};Y(p),Ge({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),T.success(`secrets \u2192 ${Pe(t.projectId)}`),await Ko(r,o,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,c),Ho("done.")}function Sl(t,e){if(!Jt(t)){hl(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=Rg(t).filter(o=>!r.has(o));n.length!==0&&(e||V(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Wo(t){if(!Jt($t(t,".git")))return null;try{let r=(await On(t).remote(["get-url","origin"])||"").toString().trim(),n=r?we(r):null;return n?{parsed:n,defaultBranch:await Ig(t)}:null}catch{return null}}async function Ig(t){let e=On(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 jg(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return ft.test(e)?e:""}function Pg(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Eg(t){let e=$t(t,".gitignore"),r=Jt(e)?yl(e,"utf-8"):"";if(Pg(r))return;if(!be(await zt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){T.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
580
580
  `)?"":`
581
- `;fl(e,r+o+`
581
+ `;wl(e,r+o+`
582
582
  # codepipe workspace (added by \`codepipe init\`)
583
583
  .codepipe/
584
- `),C.success(`.codepipe/ added to ${ml(e)}`)}function xg(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=mg(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function Qt(){let t="";try{t=(await On().raw(["config","--global","user.email"])||"").trim()}catch{}return W(await Z({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){C.step(`connecting account ${e}`);let r;try{r=await ha(t,e)}catch(s){throw s instanceof kr&&J(`${e} is not authorized on this HUB yet.
584
+ `),T.success(`.codepipe/ added to ${bl(e)}`)}function Ag(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Sg(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function Qt(){let t="";try{t=(await On().raw(["config","--global","user.email"])||"").trim()}catch{}return W(await ee({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){T.step(`connecting account ${e}`);let r;try{r=await $a(t,e)}catch(s){throw s instanceof kr&&V(`${e} is not authorized on this HUB yet.
585
585
  Sign up at ${t} (registration form on the login screen),
586
586
  wait for the operator to approve it by email, then re-run
587
- \`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(xg(r.authorizeUrl),C.message(`a browser tab was opened to confirm this CLI:
587
+ \`codepipe init\` with the same email.`),s}r.accountCreated&&T.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&T.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Ag(r.authorizeUrl),T.message(`a browser tab was opened to confirm this CLI:
588
588
  ${r.authorizeUrl}
589
589
  `+(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
590
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&C.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),C.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await ya(t,r.requestId)}catch(a){C.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Mo(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&C.message(`connected as ${a} (the account confirmed in the browser).`),C.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&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,C.message(`email confirmed. waiting for the operator to approve your account\u2026
591
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Mo(5e3);continue}await Mo(2e3)}J("bootstrap timed out")}async function kl(t,e,r){let n=$t(t,Pe);if(Jt($t(n,".git"))){C.message(`${n} already cloned \u2014 skipping`);return}Jt(n)&&J(`${n} exists but is not a git repo \u2014 remove it and re-run`),pl(n,{recursive:!0}),C.step(`cloning Context Repo \u2192 ${n}`);try{await On().clone(e,n,["--branch",r]),C.success(`cloned ${e}`)}catch(o){J(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function $l(t,e){if(e.length===0)return;C.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 jr(t,r,{log:{info:o=>C.message(o),warn:o=>C.warn(o)}});for(let o of n)C.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function xl(t){let e=$t(t,Pe,".gitignore"),r="";if(Jt(e)&&(r=dl(e,"utf-8")),ul.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
590
+ otherwise use the emailed link the page offers.`))),r.approvalRequired&&T.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),T.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 xa(t,r.requestId)}catch(a){T.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Fo(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&T.message(`connected as ${a} (the account confirmed in the browser).`),T.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&V("the HUB rejected this account"),s.status==="expired"&&V("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,T.message(`email confirmed. waiting for the operator to approve your account\u2026
591
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Fo(5e3);continue}await Fo(2e3)}V("bootstrap timed out")}async function Rl(t,e,r){let n=$t(t,je);if(Jt($t(n,".git"))){T.message(`${n} already cloned \u2014 skipping`);return}Jt(n)&&V(`${n} exists but is not a git repo \u2014 remove it and re-run`),hl(n,{recursive:!0}),T.step(`cloning Context Repo \u2192 ${n}`);try{await On().clone(e,n,["--branch",r]),T.success(`cloned ${e}`)}catch(o){V(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function Cl(t,e){if(e.length===0)return;T.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=>T.message(o),warn:o=>T.warn(o)}});for(let o of n)T.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Tl(t){let e=$t(t,je,".gitignore"),r="";if(Jt(e)&&(r=yl(e,"utf-8")),gl.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
592
592
  `)||r.length===0?"":`
593
- `,i=ul.join(`
593
+ `,i=gl.join(`
594
594
  `)+`
595
- `;fl(e,r+o+(r?`
596
- `:"")+i),C.message(`appended runtime entries to ${ml(e)}`)}async function vg(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;C.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await _n(s.host,t,s.owner,e),i?.();let c=W(await Z({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 Z({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 Z({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);C.message(`${c.host}: ${c.owner}/${c.repoName}`),await _n(c.host,t,c.owner,e),i?.();let l=W(await Z({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 Z({message:"default branch (optional)",placeholder:"main"})).trim(),d=W(await Z({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),p={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(p.defaultBranch=u),d&&d!==l&&(p.mountAs=d),o.push(p),n.onProgress?.(o)}return o}async function vl(t,e,r,n){C.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=be(await st({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&C.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=W(await Z({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Me(t),validate:u=>{let d=(u??"").trim();if(!d)return"required";if(!we(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=we(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Rg(),l=W(await Z({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=W(await Z({message:"Context Repo name",placeholder:Me(t),initialValue:Me(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function Sl(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 Sg(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await _n(c.host,n,c.owner,o),i?.();let u=hl();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let d=await Kc(c,Sl(n),{explain:l==="attach"});if(d.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(d.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${d.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(d.detail,1);let p=be(await st({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(p==="abort"&&J("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await vl(e,r,n,o),s(a)}}async function Rg(){return be(await st({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Pr(t,e){let r=hl();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 Rl(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 _n(t,e,r,n){if(!e[t])if(t==="github"){let o=await Cg(r);o?e.github=o:C.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let o=await Tg(r,n);o?e.bitbucket=o:C.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let o=await Ig();o?e.gitlab=o:C.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Cg(t){for(;;){let e=W(await Xt({message:`GitHub PAT \u2014 blank to skip
595
+ `;wl(e,r+o+(r?`
596
+ `:"")+i),T.message(`appended runtime entries to ${bl(e)}`)}async function _g(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;T.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await _n(s.host,t,s.owner,e),i?.();let c=W(await ee({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:p=>p.trim().length>0?void 0:"required"})).trim(),l=W(await ee({message:"default branch",placeholder:a,initialValue:a,validate:p=>p.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 ee({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);T.message(`${c.host}: ${c.owner}/${c.repoName}`),await _n(c.host,t,c.owner,e),i?.();let l=W(await ee({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(),p=W(await ee({message:"default branch (optional)",placeholder:"main"})).trim(),d=W(await ee({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),u={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(u.defaultBranch=p),d&&d!==l&&(u.mountAs=d),o.push(u),n.onProgress?.(o)}return o}async function Il(t,e,r,n){T.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 at({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&T.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 ee({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Me(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!we(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=we(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Ng(),l=W(await ee({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=W(await ee({message:"Context Repo name",placeholder:Me(t),initialValue:Me(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:p}}return{spec:a,mode:o}}function jl(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 Og(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await _n(c.host,n,c.owner,o),i?.();let p=$l();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let d=await Jc(c,jl(n),{explain:l==="attach"});if(d.found===!0)return p.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(d.found==="unknown")return p.stop(`could not check ${c.owner}/${c.name} (${d.detail}) \u2014 continuing`,1),a;if(l==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(d.detail,1);let u=be(await at({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(u==="abort"&&V("aborted"),u==="create")return a={spec:c,mode:"create"},s(a),a;a=await Il(e,r,n,o),s(a)}}async function Ng(){return be(await at({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=$l();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 Pl(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 _n(t,e,r,n){if(!e[t])if(t==="github"){let o=await Ug(r);o?e.github=o:T.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let o=await Dg(r,n);o?e.bitbucket=o:T.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 Lg();o?e.gitlab=o:T.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
597
597
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
598
598
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
599
599
  if org: approve token in org Settings \u2192 Personal access tokens.
600
600
  (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
601
- set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Pr("GitHub",()=>ze(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Tg(t,e){for(C.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
601
+ 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};T.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Dg(t,e){for(T.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
602
602
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
603
603
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
604
604
  read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
605
605
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
606
- The token is shown ONCE \u2014 copy it right away.`);;){let r=W(await Z({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){C.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Pr("Bitbucket",()=>Xe(r,n,t)))return{email:r,apiToken:n};C.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Ig(){for(;;){let t=W(await Xt({message:`GitLab PAT \u2014 blank to skip
607
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Pr("GitLab",()=>Qe(t))){let e=await ss(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function jg(t){if(be(await zt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
606
+ The token is shown ONCE \u2014 copy it right away.`);;){let r=W(await ee({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){T.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};T.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Lg(){for(;;){let t=W(await Xt({message:`GitLab PAT \u2014 blank to skip
607
+ 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 ls(t);return e&&T.warn(e),{token:t}}T.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Bg(t){if(be(await zt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
608
608
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
609
609
  credential. A scoped token hardens setups where the SANDBOX runs outside
610
- your trusted network.`,initialValue:!1})))for(t.host==="github"?C.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
610
+ your trusted network.`,initialValue:!1})))for(t.host==="github"?T.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
611
611
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
612
- required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):C.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
613
- (${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 Pr("contextWrite",()=>Pg(r,t)))return{token:r};C.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Pg(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 Eg(t){if(Jn()?.claude?.oauthToken&&!t)return C.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";C.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t?`
614
- 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-")||C.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),r):(C.warn(t?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}async function Cl(){for(;;){let t=W(await Z({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 Pr("YouTrack",()=>et({baseUrl:t,token:e}))){let r=await Us({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Ag}from"node:fs";function ee(t){throw new Error(t)}function ne(t,e){return(typeof t!="string"||t.trim().length===0)&&ee(`config: '${e}' must be a non-empty string`),t.trim()}function Er(t,e){if(t==null)return;typeof t!="string"&&ee(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function _g(t){(!t||typeof t!="object")&&ee("config: expected a JSON object");let e=t,r=ne(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ee("config: 'hubUrl' must start with http(s)://");let n=ne(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ee("config: 'project' is required");let i=o,s=ne(i.id,"project.id");ft.test(s)||ee("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=ne(i.name,"project.name"),c=ne(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ee("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ee("config: 'project.repos' must be an array");let u=l.map((h,x)=>{(!h||typeof h!="object")&&ee(`config: project.repos[${x}] must be an object`);let S=h,N=ne(S.host,`project.repos[${x}].host`);N!=="github"&&N!=="bitbucket"&&N!=="gitlab"&&ee(`config: project.repos[${x}].host must be 'github', 'bitbucket' or 'gitlab'`);let I={name:ne(S.name,`project.repos[${x}].name`),host:N,owner:ne(S.owner,`project.repos[${x}].owner`),repoName:ne(S.repoName,`project.repos[${x}].repoName`)},v=Er(S.defaultBranch,`project.repos[${x}].defaultBranch`);v&&(I.defaultBranch=v);let m=Er(S.mountAs,`project.repos[${x}].mountAs`);return m&&(I.mountAs=m),I}),d=i.contextRepo;(!d||typeof d!="object")&&ee("config: 'project.contextRepo' is required");let p=d,g=Er(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&ee("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:g,owner:ne(p.owner,"project.contextRepo.owner"),name:Er(p.name,"project.contextRepo.name")??Me(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},w=Er(i.youtrackProjectKey,"project.youtrackProjectKey");w&&(y.project.youtrackProjectKey=w),i.index!==void 0&&(typeof i.index!="boolean"&&ee("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ee("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let b=e.secrets;if(b!==void 0){(typeof b!="object"||b===null)&&ee("config: 'secrets' must be an object");let h=b,x={};if(h.github){let S=h.github;x.github={token:ne(S.token,"secrets.github.token")}}if(h.bitbucket){let S=h.bitbucket;x.bitbucket={email:ne(S.email,"secrets.bitbucket.email"),apiToken:ne(S.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let S=h.gitlab;x.gitlab={token:ne(S.token,"secrets.gitlab.token")}}if(h.youtrack){let S=h.youtrack;x.youtrack={url:ne(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:ne(S.token,"secrets.youtrack.token")}}if(h.contextWrite){let S=h.contextWrite;x.contextWrite={token:ne(S.token,"secrets.contextWrite.token")}}y.secrets=x}return y}async function Og(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Ng(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 Tl(t){let e=!t.configPath||t.configPath==="-"?await Og():Ag(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){ee(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let n=_g(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 Ng(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){ee(`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)ee(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let d={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(V(d),Fe({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ee(s.id)}`),ht(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 $r(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 Il,intro as jl,isCancel as Pl,log as Wo,outro as Ug,password as El}from"@clack/prompts";async function Lg(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Al(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Lg(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){jl("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Wo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await El({message:"Claude OAuth token"});Pl(i)&&(Il("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Di({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Vr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=he(t.profile);if(!e){jl(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Wo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await El({message:"Claude OAuth token"});Pl(i)&&(Il("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}.`):(Wo.success("Claude OAuth token saved."),Ug("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Dg,confirm as Bg,intro as Gg,isCancel as _l,log as se,outro as Mg,select as Ol,text as at}from"@clack/prompts";function Nl(t){Dg(t),process.exit(1)}function er(t){return _l(t)&&Nl("aborted"),t}function Ar(t){return _l(t)&&Nl("aborted"),typeof t=="string"?t:""}async function Fg(t,e){let r=er(await Ol({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=Ar(await at({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=Ar(await at({message:"Context Repo name",placeholder:Me(t),initialValue:Me(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Ul(t={profile:void 0}){let e=he(t.profile);Gg(`codepipe project add \u2192 ${e.hubUrl}`);let r=er(await at({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>ft.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=er(await at({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),o=er(await Ol({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 at({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=er(await Bg({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=Ar(await at({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:b=>!b||!b.trim()||we(b)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!p)break;let g=we(p);se.message(`${g.host}: ${g.owner}/${g.repoName}`);let f=Ar(await at({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:b=>b.trim().length>0?void 0:"required"})).trim(),y=Ar(await at({message:"default branch (optional)",placeholder:"main"})).trim(),w={name:f,host:g.host,owner:g.owner,repoName:g.repoName};y&&(w.defaultBranch=y),a.push(w)}let c={projectId:r,name:n,automationLevel:o,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 d;try{d=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=d,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}`),ht(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}`),Mg("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 Hg,rmSync as Kg}from"node:fs";import{confirm as Wg,intro as qg,isCancel as Yg,log as ct,outro as Vg,spinner as Jg}from"@clack/prompts";function Ne(t){ct.error(t),process.exit(1)}var Ll=t=>t.trim().replace(/\/+$/,"");async function Dl(t){qg("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=Ll(r.hubUrl),o=r.projectId,i=Ll(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 b=Jg();b.start(`reading project ${o} from ${n}\u2026`);try{l=await M(n,r.cliToken,o),b.stop(`read project ${o} (${l.name})`)}catch(h){throw b.stop("could not read the source project",1),h instanceof A&&Ne(`source HUB ${n} \u2192 ${h.status} ${h.message}. The source HUB must be reachable with a valid token to move a project.`),h}}l.contextRepo||Ne(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=U(o),d=(t.account??r.accountEmail??await Qt()).trim().toLowerCase();if(ct.message(`move project '${o}'
612
+ required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):T.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
613
+ (${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};T.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(zn()?.claude?.oauthToken&&!t)return T.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`)."),"";T.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?`
614
+ 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-")||T.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):(T.warn(t?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}async function El(){for(;;){let t=W(await ee({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 Bs({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}T.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Fg}from"node:fs";function te(t){throw new Error(t)}function re(t,e){return(typeof t!="string"||t.trim().length===0)&&te(`config: '${e}' must be a non-empty string`),t.trim()}function Pr(t,e){if(t==null)return;typeof t!="string"&&te(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Hg(t){(!t||typeof t!="object")&&te("config: expected a JSON object");let e=t,r=re(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||te("config: 'hubUrl' must start with http(s)://");let n=re(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&te("config: 'project' is required");let i=o,s=re(i.id,"project.id");ft.test(s)||te("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"&&te("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||te("config: 'project.repos' must be an array");let p=l.map((h,$)=>{(!h||typeof h!="object")&&te(`config: project.repos[${$}] must be an object`);let S=h,U=re(S.host,`project.repos[${$}].host`);U!=="github"&&U!=="bitbucket"&&U!=="gitlab"&&te(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let I={name:re(S.name,`project.repos[${$}].name`),host:U,owner:re(S.owner,`project.repos[${$}].owner`),repoName:re(S.repoName,`project.repos[${$}].repoName`)},E=Pr(S.defaultBranch,`project.repos[${$}].defaultBranch`);E&&(I.defaultBranch=E);let j=Pr(S.mountAs,`project.repos[${$}].mountAs`);return j&&(I.mountAs=j),I}),d=i.contextRepo;(!d||typeof d!="object")&&te("config: 'project.contextRepo' is required");let u=d,g=Pr(u.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&te("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:g,owner:re(u.owner,"project.contextRepo.owner"),name:Pr(u.name,"project.contextRepo.name")??Me(s)},w={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:f}},b=Pr(i.youtrackProjectKey,"project.youtrackProjectKey");b&&(w.project.youtrackProjectKey=b),i.index!==void 0&&(typeof i.index!="boolean"&&te("config: 'project.index' must be a boolean"),w.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&te("config: 'project.youtrackWrites' must be a boolean"),w.project.youtrackWrites=i.youtrackWrites);let k=e.secrets;if(k!==void 0){(typeof k!="object"||k===null)&&te("config: 'secrets' must be an object");let h=k,$={};if(h.github){let S=h.github;$.github={token:re(S.token,"secrets.github.token")}}if(h.bitbucket){let S=h.bitbucket;$.bitbucket={email:re(S.email,"secrets.bitbucket.email"),apiToken:re(S.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let S=h.gitlab;$.gitlab={token:re(S.token,"secrets.gitlab.token")}}if(h.youtrack){let S=h.youtrack;$.youtrack={url:re(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:re(S.token,"secrets.youtrack.token")}}if(h.contextWrite){let S=h.contextWrite;$.contextWrite={token:re(S.token,"secrets.contextWrite.token")}}w.secrets=$}return w}async function Kg(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Wg(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 Al(t){let e=!t.configPath||t.configPath==="-"?await Kg():Fg(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){te(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=Hg(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 Wg(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:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){te(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let p;try{p=await tt(o,i,a)}catch(u){if(u instanceof A&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await F(o,i,s.id);else if(u instanceof A)te(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let d={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(Y(d),Ge({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Pe(s.id)}`),ht(s.id,Ae(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await $r(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${u}); runs once a SANDBOX claims it.`)}catch(u){console.warn(`could not enqueue index job: ${u instanceof Error?u.message:String(u)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as _l,intro as Ol,isCancel as Nl,log as qo,outro as qg,password as Ul}from"@clack/prompts";async function Yg(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Dl(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Yg(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Ol("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),qo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Ul({message:"Claude OAuth token"});Nl(i)&&(_l("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Gi({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Vr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=he(t.profile);if(!e){Ol(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),qo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Ul({message:"Claude OAuth token"});Nl(i)&&(_l("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=D(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},Y(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(qo.success("Claude OAuth token saved."),qg("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Vg,confirm as Jg,intro as zg,isCancel as Ll,log as ae,outro as Xg,select as Bl,text as ct}from"@clack/prompts";function Ml(t){Vg(t),process.exit(1)}function er(t){return Ll(t)&&Ml("aborted"),t}function Er(t){return Ll(t)&&Ml("aborted"),typeof t=="string"?t:""}async function Qg(t,e){let r=er(await Bl({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 ct({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 ct({message:"Context Repo name",placeholder:Me(t),initialValue:Me(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Gl(t={profile:void 0}){let e=he(t.profile);zg(`codepipe project add \u2192 ${e.hubUrl}`);let r=er(await ct({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>ft.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=er(await ct({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=er(await Bl({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 ct({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=er(await Jg({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=Er(await ct({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(!u)break;let g=we(u);ae.message(`${g.host}: ${g.owner}/${g.repoName}`);let f=Er(await ct({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(),w=Er(await ct({message:"default branch (optional)",placeholder:"main"})).trim(),b={name:f,host:g.host,owner:g.owner,repoName:g.repoName};w&&(b.defaultBranch=w),a.push(b)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Qg(r,a),p=D(e.projectId);ae.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let d;try{d=await Yt(c,l,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??It(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>ae.message(u),warn:u=>ae.warn(u)}})}catch(u){ae.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=d,ae.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await tt(e.hubUrl,e.cliToken,c);ae.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),ht(r,Ae(c,s,p?.youtrack?.url),{info:g=>ae.message(g),warn:g=>ae.warn(g)}),u.contextRepo&&(ae.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),ae.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&ae.error(` error: ${u.provisioningError}`),Xg("done")}catch(u){u instanceof A?(ae.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&ae.message(JSON.stringify(u.payload,null,2))):ae.error(u instanceof Error?u.message:String(u)),process.exit(1)}}import{existsSync as Zg,rmSync as eh}from"node:fs";import{confirm as th,intro as rh,isCancel as nh,log as lt,outro as oh,spinner as ih}from"@clack/prompts";function Oe(t){lt.error(t),process.exit(1)}var Fl=t=>t.trim().replace(/\/+$/,"");async function Hl(t){rh("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ge()?.spec.projectId??void 0;e||Oe("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=$e(e);r||Oe(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Fl(r.hubUrl),o=r.projectId,i=Fl(t.hub);i.startsWith("http")||Oe("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Oe(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let k=ih();k.start(`reading project ${o} from ${n}\u2026`);try{l=await F(n,r.cliToken,o),k.stop(`read project ${o} (${l.name})`)}catch(h){throw k.stop("could not read the source project",1),h instanceof A&&Oe(`source HUB ${n} \u2192 ${h.status} ${h.message}. The source HUB must be reachable with a valid token to move a project.`),h}}l.contextRepo||Oe(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let p=D(o),d=(t.account??r.accountEmail??await Qt()).trim().toLowerCase();if(lt.message(`move project '${o}'
615
615
  from : ${n} (profile ${e})
616
616
  to : ${i} (profile ${s}, project ${a}, account ${d})
617
617
  \u2022 the source registration on the old HUB is left intact (non-destructive)
618
618
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
619
- `+(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 b=await Wg({message:"Continue?",initialValue:!0});(Yg(b)||!b)&&Ne("aborted")}!c&&a===o&&ct.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,d),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:g,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};ct.step(`registering project on ${i}\u2026`);let y;try{y=await tt(i,p,f)}catch(b){if(b instanceof A&&b.status===409){ct.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{y=await M(i,p,a)}catch(h){throw h instanceof A&&Ne(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if(b instanceof A&&b.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(b instanceof A)Ne(`target HUB \u2192 ${b.status} ${b.message}`);else throw b}ct.success(`project ${y.projectId} ready on ${i} (${y.provisioningStatus})`),Fe({hubUrl:i,cliToken:p,projectId:a,accountEmail:g},s);let w={...u??{},hubUrl:i,cliToken:p,projectId:a};if(delete w.sandboxPins,V(w),ct.success(`profile '${s}' \u2192 ${Ee(a)}`),c){let b=Re(s);Hg(b)&&(Kg(b),ct.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}Vg(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as qo,rmSync as zg,statSync as Xg}from"node:fs";import{join as Nn,relative as Qg,resolve as Zg}from"node:path";import{cancel as eh,intro as Gl,isCancel as th,log as X,outro as Ml,text as xt}from"@clack/prompts";import{simpleGit as Fl}from"simple-git";function ue(t){eh(t),process.exit(1)}function vt(t){return th(t)&&ue("aborted"),typeof t=="string"?t:""}async function Bl(t){try{let e=await Fl(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function rh(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function nh(t,e){let r=U(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(rh(r,e)){X.message(`reusing existing ${e} credentials`);return}if(X.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=vt(await xt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=vt(await xt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=vt(await xt({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),X.success(`saved ${e} credentials`)}async function Hl(t){let e=he(t.profile);Gl(`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(h){ue(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await Bl(process.cwd());h?(o=process.cwd(),X.message(`using the current directory (${h})`)):o=vt(await xt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:x=>x.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(qo(o)&&Xg(o).isDirectory()){i=Zg(o);let h=await Bl(i);h||ue(`${i} is not a git repository (no origin remote)`);let x=we(h);x||ue(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=x,s=h,X.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=we(o);h||ue(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,X.message(`${a}: ${c}/${l}`)}let u=vt(await xt({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:h=>h.trim()?void 0:"required"})).trim();n.some(h=>h.name===u)&&ue(`a repo named "${u}" is already registered`);let d=vt(await xt({message:"default branch (optional)",placeholder:"main"})).trim(),p=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=Qg(r.root,i);p=h===""?".":h}let g=vt(await xt({message:"mount_as (directory relative to the workspace root)",placeholder:p,initialValue:p})).trim()||p;n.some(h=>(h.mountAs??h.name)===g)&&ue(`mount_as "${g}" is already used by another repo`),await nh(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:g,...d?{defaultBranch:d}:{}};if(!i){let h=r?Nn(r.root,g):xe(e.projectId,u);if(qo(Nn(h,".git")))X.message(`already cloned at ${h}`);else{X.info(`cloning ${s} \u2192 ${h} \u2026`);try{await Fl().clone(s,h),X.success(`cloned into ${h}`)}catch(x){ue(`clone failed: ${x instanceof Error?x.message.trim():String(x)}
620
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let y;try{y=await Sa(e.hubUrl,e.cliToken,e.projectId,f)}catch(h){h instanceof A&&ue(`HUB \u2192 ${h.status} ${h.message}`),ue(h instanceof Error?h.message:String(h))}let{updated:w,errors:b}=fr(e.projectId,y.repos,r?.contextDir);for(let h of w)X.message(`updated ${h}`);for(let h of b)X.warn(`could not update ${h.path}: ${h.error}`);X.success(`added "${u}" \u2014 project now has ${y.repos.length} repo(s)`),Ml("done")}async function Kl(t){let e=he(t.profile);Gl(`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 Ra(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)X.message(`updated ${a}`);for(let a of s)X.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")X.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Nn(r.root,n):xe(e.projectId,t.name);if(qo(Nn(a,".git")))try{zg(a,{recursive:!0,force:!0}),X.message(`deleted local clone ${a}`)}catch(c){X.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else X.message(`no local clone found to purge (${a})`)}X.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Ml("done")}async function Wl(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 oh}from"node:child_process";import{existsSync as ql}from"node:fs";import{homedir as ih,hostname as sh}from"node:os";import{join as Un}from"node:path";async function ah(t,e,r){let n=ie(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Re(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 ma(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 ${Re(e)} still holds its token.
621
- 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`),Li(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function ch(t,e,r){let n=ie(e)!==null;if(!await ah(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 yn(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:o,name:r.name??`${sh()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function lh(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=Yr(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 uh(t,e){let r=process.cwd(),n=Un(r,Pe);if(Kr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(ql(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 Ko(r);if(!$i(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 xn({cfg:t,secrets:s,contextDir:n,log:a}).catch(()=>null);if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=Un(ih(),".codepipe",e?Un("profiles",e,"context-config"):"context-config");if(Qr(c.contextDir,l,a),!ql(Un(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 Yl(t){let{cfg:e,profile:r}=qr(t.profile);await uh(e,r),await ch(e,r,t),lh(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,f)=>{let y=w=>b=>{for(let h of b.toString("utf-8").split(`
622
- `))h.length>0&&w.write(`${f} ${h}
623
- `)};g.stdout?.on("data",y(process.stdout)),g.stderr?.on("data",y(process.stderr))},i=(g,f)=>{let y=oh(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(y,g),y};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=g=>{if(!l){l=!0,console.log(`
624
- [up] ${g} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(g);setTimeout(()=>{for(let{name:f,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let d=c.map(({name:g,child:f})=>new Promise(y=>{f.on("exit",(w,b)=>y({name:g,code:w??(b?1:0)}))})),p=await Promise.race(d);l||(console.log(`[up] ${p.name} exited (code ${p.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(d),process.exit(p.code)}import{existsSync as iu,mkdirSync as gh,readFileSync as hh,writeFileSync as yh}from"node:fs";import{homedir as wh}from"node:os";import{dirname as bh,join as su}from"node:path";import*as rr from"node:readline";import{existsSync as Jo,readFileSync as ph,writeFileSync as dh}from"node:fs";import{join as Or}from"node:path";import{simpleGit as Vo}from"simple-git";var Vl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],fh="apply-queue.json";function Jl(t){return Or(t,fh)}function tr(t){let e=Jl(t);if(!Jo(e))return{};try{return JSON.parse(ph(e,"utf-8"))}catch{return{}}}function zl(t,e){dh(Jl(t),JSON.stringify(e,null,2)+`
625
- `)}async function Xl(t,e,r,n,o){let i;try{i=await ka(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(p){return{ok:!1,message:`claim failed: ${p instanceof Error?p.message:String(p)}`}}let s=[];for(let p of i.repos){let g=t.spec.repos.find(b=>b.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let f=Or(t.root,g.mountAs);if(!Jo(Or(f,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Vo(f).status()).isClean())return{ok:!1,message:`${g.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:p,spec:g,dir:f})}let a=[];for(let p of s){let g=Vo(p.dir),f=await mh(g),y=p.claimRepo;try{await g.fetch()}catch(h){return await Yo(a,o),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${_r(h)}`}}let w=`origin/${y.baseRef}`,b;try{b=await nn(g,{contextRepoCloneUrl:y.contextRepoCloneUrl,deliveryRef:y.deliveryRef,deliverySha:y.deliverySha,baseSha:y.baseSha,commitMessage:y.commitMessage})}catch(h){return await Yo(a,o),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${_r(h)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:f,branch:y.branchName,baseSha:w,deliveryCommit:b,startPoint:w})}let c=[];for(let p of a)try{if(n==="apply"){await p.git.checkout(["-B",p.branch,p.startPoint]),await p.git.raw([...Vl,"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([...Vl,"cherry-pick","--no-commit",p.deliveryCommit]),await p.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha})}catch(g){return await p.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Yo(a,o),{ok:!1,message:`apply failed in ${p.mountAs}: ${_r(g)} (rolled back all repos)`}}let l=tr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},zl(t.contextDir,l);let u=c.map(p=>p.mountAs).join(", "),d=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}
619
+ `+(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 th({message:"Continue?",initialValue:!0});(nh(k)||!k)&&Oe("aborted")}!c&&a===o&&lt.warn(`source and destination share the same project id, so they share one secrets file (${Pe(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:u,accountEmail:g}=await Zt(i,d),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:g,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};lt.step(`registering project on ${i}\u2026`);let w;try{w=await tt(i,u,f)}catch(k){if(k instanceof A&&k.status===409){lt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{w=await F(i,u,a)}catch(h){throw h instanceof A&&Oe(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if(k instanceof A&&k.status===403)Oe(`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)Oe(`target HUB \u2192 ${k.status} ${k.message}`);else throw k}lt.success(`project ${w.projectId} ready on ${i} (${w.provisioningStatus})`),Ge({hubUrl:i,cliToken:u,projectId:a,accountEmail:g},s);let b={...p??{},hubUrl:i,cliToken:u,projectId:a};if(delete b.sandboxPins,Y(b),lt.success(`profile '${s}' \u2192 ${Pe(a)}`),c){let k=Re(s);Zg(k)&&(eh(k),lt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}oh(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as Yo,rmSync as sh,statSync as ah}from"node:fs";import{join as Nn,relative as ch,resolve as lh}from"node:path";import{cancel as uh,intro as Wl,isCancel as ph,log as X,outro as ql,text as xt}from"@clack/prompts";import{simpleGit as Yl}from"simple-git";function pe(t){uh(t),process.exit(1)}function vt(t){return ph(t)&&pe("aborted"),typeof t=="string"?t:""}async function Kl(t){try{let e=await Yl(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function dh(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function fh(t,e){let r=D(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(dh(r,e)){X.message(`reusing existing ${e} credentials`);return}if(X.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=vt(await xt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=vt(await xt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=vt(await xt({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}}Y(r),X.success(`saved ${e} credentials`)}async function Vl(t){let e=he(t.profile);Wl(`codepipe repo add \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{n=(await F(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){pe(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await Kl(process.cwd());h?(o=process.cwd(),X.message(`using the current directory (${h})`)):o=vt(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(Yo(o)&&ah(o).isDirectory()){i=lh(o);let h=await Kl(i);h||pe(`${i} is not a git repository (no origin remote)`);let $=we(h);$||pe(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=h,X.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=we(o);h||pe(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,X.message(`${a}: ${c}/${l}`)}let p=vt(await xt({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:h=>h.trim()?void 0:"required"})).trim();n.some(h=>h.name===p)&&pe(`a repo named "${p}" is already registered`);let d=vt(await xt({message:"default branch (optional)",placeholder:"main"})).trim(),u=p;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=ch(r.root,i);u=h===""?".":h}let g=vt(await xt({message:"mount_as (directory relative to the workspace root)",placeholder:u,initialValue:u})).trim()||u;n.some(h=>(h.mountAs??h.name)===g)&&pe(`mount_as "${g}" is already used by another repo`),await fh(e,a);let f={name:p,host:a,owner:c,repoName:l,mountAs:g,...d?{defaultBranch:d}:{}};if(!i){let h=r?Nn(r.root,g):xe(e.projectId,p);if(Yo(Nn(h,".git")))X.message(`already cloned at ${h}`);else{X.info(`cloning ${s} \u2192 ${h} \u2026`);try{await Yl().clone(s,h),X.success(`cloned into ${h}`)}catch($){pe(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
620
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let w;try{w=await ja(e.hubUrl,e.cliToken,e.projectId,f)}catch(h){h instanceof A&&pe(`HUB \u2192 ${h.status} ${h.message}`),pe(h instanceof Error?h.message:String(h))}let{updated:b,errors:k}=fr(e.projectId,w.repos,r?.contextDir);for(let h of b)X.message(`updated ${h}`);for(let h of k)X.warn(`could not update ${h.path}: ${h.error}`);X.success(`added "${p}" \u2014 project now has ${w.repos.length} repo(s)`),ql("done")}async function Jl(t){let e=he(t.profile);Wl(`codepipe repo remove \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{let c=(await F(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 Pa(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof A&&(a.status===404&&pe(`no repo named "${t.name}" in this project`),pe(`HUB \u2192 ${a.status} ${a.message}`)),pe(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=fr(e.projectId,o.repos,r?.contextDir);for(let a of i)X.message(`updated ${a}`);for(let a of s)X.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")X.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Nn(r.root,n):xe(e.projectId,t.name);if(Yo(Nn(a,".git")))try{sh(a,{recursive:!0,force:!0}),X.message(`deleted local clone ${a}`)}catch(c){X.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else X.message(`no local clone found to purge (${a})`)}X.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),ql("done")}async function zl(t){let e=he(t.profile),r;try{r=(await F(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 mh}from"node:child_process";import{existsSync as Xl}from"node:fs";import{homedir as gh,hostname as hh}from"node:os";import{join as Un}from"node:path";async function yh(t,e,r){let n=se(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Re(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 ba(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 ${Re(e)} still holds its token.
621
+ 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`),Mi(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function wh(t,e,r){let n=se(e)!==null;if(!await yh(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 yn(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:o,name:r.name??`${hh()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function bh(t,e){let r=se(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=ce(r.sealPublicKey);if(!D(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Yr(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 kh(t,e){let r=process.cwd(),n=Un(r,je);if(Kr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Xl(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 F(t.hubUrl,t.cliToken,t.projectId)}catch(p){console.warn(`[up] could not fetch the project summary (${p instanceof Error?p.message:String(p)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Wo(r);if(!Si(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=D(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await xn({cfg:t,secrets:s,contextDir:n,log:a}).catch(()=>null);if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=Un(gh(),".codepipe",e?Un("profiles",e,"context-config"):"context-config");if(Qr(c.contextDir,l,a),!Xl(Un(c.contextDir,"project.yaml"))){At(c.contextDir);let p={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};dr(c.contextDir,Ae(p,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function Ql(t){let{cfg:e,profile:r}=qr(t.profile);await kh(e,r),await wh(e,r,t),bh(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,f)=>{let w=b=>k=>{for(let h of k.toString("utf-8").split(`
622
+ `))h.length>0&&b.write(`${f} ${h}
623
+ `)};g.stdout?.on("data",w(process.stdout)),g.stderr?.on("data",w(process.stderr))},i=(g,f)=>{let w=mh(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(w,g),w};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,p=g=>{if(!l){l=!0,console.log(`
624
+ [up] ${g} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(g);setTimeout(()=>{for(let{name:f,child:w}of c)w.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),w.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM"));let d=c.map(({name:g,child:f})=>new Promise(w=>{f.on("exit",(b,k)=>w({name:g,code:b??(k?1:0)}))})),u=await Promise.race(d);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),p("SIGTERM")),await Promise.all(d),process.exit(u.code)}import{existsSync as uu,mkdirSync as Rh,readFileSync as Ch,writeFileSync as Th}from"node:fs";import{homedir as Ih}from"node:os";import{dirname as jh,join as pu}from"node:path";import*as rr from"node:readline";import{existsSync as zo,readFileSync as $h,writeFileSync as xh}from"node:fs";import{join as _r}from"node:path";import{simpleGit as Jo}from"simple-git";var Zl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],vh="apply-queue.json";function eu(t){return _r(t,vh)}function tr(t){let e=eu(t);if(!zo(e))return{};try{return JSON.parse($h(e,"utf-8"))}catch{return{}}}function tu(t,e){xh(eu(t),JSON.stringify(e,null,2)+`
625
+ `)}async function ru(t,e,r,n,o){let i;try{i=await Ra(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(u){return{ok:!1,message:`claim failed: ${u instanceof Error?u.message:String(u)}`}}let s=[];for(let u of i.repos){let g=t.spec.repos.find(k=>k.name===u.repoName);if(!g)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let f=_r(t.root,g.mountAs);if(!zo(_r(f,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Jo(f).status()).isClean())return{ok:!1,message:`${g.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:u,spec:g,dir:f})}let a=[];for(let u of s){let g=Jo(u.dir),f=await Sh(g),w=u.claimRepo;try{await g.fetch()}catch(h){return await Vo(a,o),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${Ar(h)}`}}let b=`origin/${w.baseRef}`,k;try{k=await nn(g,{contextRepoCloneUrl:w.contextRepoCloneUrl,deliveryRef:w.deliveryRef,deliverySha:w.deliverySha,baseSha:w.baseSha,commitMessage:w.commitMessage})}catch(h){return await Vo(a,o),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${Ar(h)}`}}a.push({git:g,dir:u.dir,mountAs:u.spec.mountAs,originalRef:f,branch:w.branchName,baseSha:b,deliveryCommit:k,startPoint:b})}let c=[];for(let u of a)try{if(n==="apply"){await u.git.checkout(["-B",u.branch,u.startPoint]),await u.git.raw([...Zl,"cherry-pick",u.deliveryCommit]);let g=(await u.git.revparse(["HEAD"])).trim();c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha,appliedSha:g})}else await u.git.checkout(["--detach",u.startPoint]),await u.git.raw([...Zl,"cherry-pick","--no-commit",u.deliveryCommit]),await u.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha})}catch(g){return await u.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Vo(a,o),{ok:!1,message:`apply failed in ${u.mountAs}: ${Ar(g)} (rolled back all repos)`}}let l=tr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},tu(t.contextDir,l);let p=c.map(u=>u.mountAs).join(", "),d=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 ${p}
626
626
  ${d}
627
- or: /abort ${r} --reason "..."`}}function zo(t,e){let r=tr(t);r[e]&&(delete r[e],zl(t,r))}async function Yo(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${_r(n)} \u2014 check manually`)}}async function Ql(t,e,r){let o=tr(t.contextDir)[e];if(o){for(let i of o.repos){let s=Or(t.root,i.mountAs);if(!Jo(Or(s,".git")))continue;let a=Vo(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}: ${_r(u)} \u2014 check manually`)}}zo(t.contextDir,e)}}async function mh(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function _r(t){return t instanceof Error?t.message.trim():String(t)}var Ln=su(wh(),".codepipe","history"),Zl=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],au=500,eu=40;async function cu(){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(`
627
+ or: /abort ${r} --reason "..."`}}function Xo(t,e){let r=tr(t);r[e]&&(delete r[e],tu(t,r))}async function Vo(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 nu(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(!zo(_r(s,".git")))continue;let a=Jo(s),c=t.spec.repos.find(p=>p.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(p){r.warn(`rollback failed in ${i.mountAs}: ${Ar(p)} \u2014 check manually`)}}Xo(t.contextDir,e)}}async function Sh(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 Dn=pu(Ih(),".codepipe","history"),ou=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],du=500,iu=40;async function fu(){let t=ge();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=D(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(`
628
628
  \u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
629
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=rr.createInterface({input:process.stdin,output:process.stdout,completer:kh,history:Gh(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};fs(s=>St(i,s)),i.daemon=kn({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>St(i,s),warn:s=>St(i,s)},onEvent:s=>Oh(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Qo(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await $h(i,a)){ou(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Qo(i),o.prompt()}),o.on("close",()=>{ou(i)})}function kh(t){let e=Zl.filter(r=>r.startsWith(t));return[e.length?e:Zl,t]}async function $h(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return xh(),!1;case"/status":return await vh(t),!1;case"/tasks":return await Sh(t,n),!1;case"/task":return await Rh(t,n),!1;case"/sync":return await Ch(t),!1;case"/logs":return Nh(t,n),!1;case"/monitor":return Uh(t),!1;case"/apply":return await tu(t,n,"apply"),!1;case"/unstash":return await tu(t,n,"unstash"),!1;case"/applied":return await Th(t,n),!1;case"/abort":return await Ih(t,n),!1;case"/approve":return await ru(t,n,"approve"),!1;case"/merge":return await ru(t,n,"merge"),!1;case"/login":return Ph(t,n),!1;case"/secret":return Eh(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function xh(){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(`
630
- `))}async function vh(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=iu(su(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function Sh(t,e){let r=Lh(e,"--phase");try{let n=await wa(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){Ur(n)}}async function Rh(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await ba(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){Ur(n)}}async function Ch(t){let e=await jr(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 tu(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Xl(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function Th(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=Dh(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,d;if(l>0?(u=c.slice(0,l),d=c.slice(l+1)):(d=c,u=o?.repos.length===1?jh(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${d}`);return}let p=d.match(/(?:pull|pull-requests)\/(\d+)/);if(!p){console.log(` cannot parse PR number from ${d}`);return}a.push({repoName:u,url:d,number:Number(p[1])})}try{let c=await $a(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);zo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Ur(c)}}async function ru(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){Ur(o)}}async function Ih(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=Bh(e,"--reason")||"local apply aborted";await Ql(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await xa(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Ur(o)}}function jh(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Ph(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 Eh(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(`
631
- `)}`:" (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}Ah(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}_h(t.secrets,n),V(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function Ah(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 _h(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 Oh(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",Nr(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",Nr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Nr(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`):Nr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function St(t,e){t.logBuffer.push(e),t.logBuffer.length>au&&t.logBuffer.shift(),t.follow&&Nr(t,e)}function Nh(t,e){let r=e[0];if(r==="follow"||r==="on"){Xo(t,!0);return}if(r==="off"){Xo(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(au,Number(r)||eu)):eu,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 Uh(t){Xo(t,!t.follow)}function Xo(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Nr(t,e){rr.cursorTo(process.stdout,0),rr.clearLine(process.stdout,0),process.stdout.write(e+`
632
- `),t.unread+=1,Qo(t),t.rl.prompt(!0)}function Qo(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var nu=!1;function ou(t){nu||(nu=!0,Mh(t.rl),t.daemon.stop(),console.log(`
633
- bye.`),setTimeout(()=>process.exit(0),150))}function Lh(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Dh(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 Bh(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Ur(t){t instanceof A?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Gh(){if(!iu(Ln))return[];try{return hh(Ln,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Mh(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{gh(bh(Ln),{recursive:!0}),yh(Ln,r.slice().reverse().join(`
629
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=rr.createInterface({input:process.stdin,output:process.stdout,completer:Ph,history:zh(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};hs(s=>St(i,s)),i.daemon=kn({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>St(i,s),warn:s=>St(i,s)},onEvent:s=>Kh(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Zo(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await Eh(i,a)){lu(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Zo(i),o.prompt()}),o.on("close",()=>{lu(i)})}function Ph(t){let e=ou.filter(r=>r.startsWith(t));return[e.length?e:ou,t]}async function Eh(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return Ah(),!1;case"/status":return await _h(t),!1;case"/tasks":return await Oh(t,n),!1;case"/task":return await Nh(t,n),!1;case"/sync":return await Uh(t),!1;case"/logs":return Wh(t,n),!1;case"/monitor":return qh(t),!1;case"/apply":return await su(t,n,"apply"),!1;case"/unstash":return await su(t,n,"unstash"),!1;case"/applied":return await Dh(t,n),!1;case"/abort":return await Lh(t,n),!1;case"/approve":return await au(t,n,"approve"),!1;case"/merge":return await au(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 Ah(){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(`
630
+ `))}async function _h(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=uu(pu(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function Oh(t,e){let r=Yh(e,"--phase");try{let n=await va(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 Nh(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Sa(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 su(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await ru(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function Dh(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("="),p,d;if(l>0?(p=c.slice(0,l),d=c.slice(l+1)):(d=c,p=o?.repos.length===1?Bh(t,o.repos[0].mountAs):s.length===1?s[0]:""),!p){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${d}`);return}let u=d.match(/(?:pull|pull-requests)\/(\d+)/);if(!u){console.log(` cannot parse PR number from ${d}`);return}a.push({repoName:p,url:d,number:Number(u[1])})}try{let c=await Ca(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Xo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Nr(c)}}async function au(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Ia(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 Lh(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=Jh(e,"--reason")||"local apply aborted";await nu(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await Ta(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 Bh(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},Y(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(`
631
+ `)}`:" (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}Fh(t.secrets,n,i),Y(t.secrets),pr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}Hh(t.secrets,n),Y(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function Fh(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 Hh(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 Kh(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>du&&t.logBuffer.shift(),t.follow&&Or(t,e)}function Wh(t,e){let r=e[0];if(r==="follow"||r==="on"){Qo(t,!0);return}if(r==="off"){Qo(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(du,Number(r)||iu)):iu,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 qh(t){Qo(t,!t.follow)}function Qo(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+`
632
+ `),t.unread+=1,Zo(t),t.rl.prompt(!0)}function Zo(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var cu=!1;function lu(t){cu||(cu=!0,Xh(t.rl),t.daemon.stop(),console.log(`
633
+ bye.`),setTimeout(()=>process.exit(0),150))}function Yh(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 Jh(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 zh(){if(!uu(Dn))return[];try{return Ch(Dn,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Xh(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{Rh(jh(Dn),{recursive:!0}),Th(Dn,r.slice().reverse().join(`
634
634
  `)+`
635
- `)}catch{}}import{hostname as Fh}from"node:os";import{cancel as Hh,confirm as lu,intro as Kh,isCancel as du,log as nr,multiselect as Wh,outro as uu,password as qh,select as Zo,text as ei}from"@clack/prompts";function Lr(t){Hh(t),process.exit(1)}function or(t){return du(t)&&Lr("aborted"),t}function Dn(t){return du(t)&&Lr("aborted"),typeof t=="string"?t:""}function ti(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function pu(t,e){try{let{secret:r}=await yn(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&Lr("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 Yh(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 ga(t,e);if(o.length>0)return or(await Wh({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 Dn(await ei({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 ri(t){Kh("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 lu({message:"re-register this worker?",initialValue:!1}))||Lr("keeping the existing registration"));let r=$e(t.profile)??$e(),n=Dn(await ei({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 pu(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 pu(n,a),nr.success("account-issued registration token minted")}else s=Dn(await qh({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Lr("a registration token is required");let c=await Yh(n,a),l=Dn(await ei({message:"worker name",initialValue:Fh(),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 wt({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 lu({message:"start the claim-loop now?",initialValue:!0}))){uu("registered. start later with `codepipe worker`.");return}uu("starting the claim-loop\u2026"),await Ir(t.profile?{profile:t.profile}:{})}function Jh(){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 Q=Jh();Ci(Q);ji();var pe=new Vh;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 cu()}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 Tl({configPath:t.config,skipVerify:t.skipVerify===!0}):await yl({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 Bi({...t,profile:Q})}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 wl({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 Za({profile:Q})}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 ll({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 Al({profile:Q,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 Hc({profile:Q})}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 Yl({profile:Q,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var fu=pe.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");fu.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(Q)?.hubUrl??Te,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ti()){await ri({profile:Q});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 wt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...Q?{profile:Q}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});fu.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ie(Q)&&ti()){await ri({profile:Q});return}await Ir(Q?{profile:Q}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var mu=pe.command("project").description("Manage CodePipe projects");mu.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Ul({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});mu.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await Dl({...t,cliProfile:Q})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var ni=pe.command("repo").description("Manage the project's git repositories");ni.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 Hl({profile:Q,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ni.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 Kl({profile:Q,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ni.command("list").description("List the project's repos").action(async()=>{try{await Wl({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});pe.parseAsync();
635
+ `)}catch{}}import{hostname as Qh}from"node:os";import{cancel as Zh,confirm as mu,intro as ey,isCancel as yu,log as nr,multiselect as ty,outro as gu,password as ry,select as ei,text as ti}from"@clack/prompts";function Ur(t){Zh(t),process.exit(1)}function or(t){return yu(t)&&Ur("aborted"),t}function Ln(t){return yu(t)&&Ur("aborted"),typeof t=="string"?t:""}function ri(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function hu(t,e){try{let{secret:r}=await yn(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 ny(t,e){if(or(await ei({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 ka(t,e);if(o.length>0)return or(await ty({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 Ln(await ti({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 ni(t){ey("codepipe worker \u2014 set up this machine as a runner");let e=se(t.profile);e&&(nr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),or(await mu({message:"re-register this worker?",initialValue:!1}))||Ur("keeping the existing registration"));let r=$e(t.profile)??$e(),n=Ln(await ti({message:"HUB URL",placeholder:Ce,initialValue:L("HUB_URL")??r?.hubUrl??Ce,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=or(await ei({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 hu(n,a),nr.success("account-issued registration token minted");else if(i==="login"){let u=await Qt();a=(await Zt(n,u)).cliToken,s=await hu(n,a),nr.success("account-issued registration token minted")}else s=Ln(await ry({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Ur("a registration token is required");let c=await ny(n,a),l=Ln(await ti({message:"worker name",initialValue:Qh(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=or(await ei({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:n,token:s,name:l,projects:c,...p?{llm:p}:{},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 mu({message:"start the claim-loop now?",initialValue:!0}))){gu("registered. start later with `codepipe worker`.");return}gu("starting the claim-loop\u2026"),await Tr(t.profile?{profile:t.profile}:{})}function iy(){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 Q=iy();ji(Q);Ai();var de=new oy;de.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(me).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await fu()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});de.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Al({configPath:t.config,skipVerify:t.skipVerify===!0}):await xl({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});de.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Fi({...t,profile:Q})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});de.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await vl({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});de.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await oc({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});de.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await ml({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});de.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Dl({profile:Q,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});de.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Vc({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});de.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await Ql({profile:Q,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var wu=de.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");wu.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(Q)?.hubUrl??Ce,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ri()){await ni({profile:Q});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 wt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...Q?{profile:Q}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});wu.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!se(Q)&&ri()){await ni({profile:Q});return}await Tr(Q?{profile:Q}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var bu=de.command("project").description("Manage CodePipe projects");bu.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Gl({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});bu.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await Hl({...t,cliProfile:Q})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var oi=de.command("repo").description("Manage the project's git repositories");oi.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 Vl({profile:Q,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});oi.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 Jl({profile:Q,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});oi.command("list").description("List the project's repos").action(async()=>{try{await zl({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});de.parseAsync();