@code-partner/codepipe 0.4.1-dev.131.ge050bff → 0.5.1-dev.133.g6ad609e
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.
- package/dist/index.js +99 -92
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var xf=Object.defineProperty;var R=(t,e)=>()=>(t&&(e=t(t=0)),e);var Sf=(t,e)=>{for(var r in e)xf(t,r,{get:e[r],enumerable:!0})};var xe,Ge,Wo=R(()=>{"use strict";xe="0.
|
|
2
|
+
var xf=Object.defineProperty;var R=(t,e)=>()=>(t&&(e=t(t=0)),e);var Sf=(t,e)=>{for(var r in e)xf(t,r,{get:e[r],enumerable:!0})};var xe,Ge,Wo=R(()=>{"use strict";xe="0.5.1-dev.133.g6ad609e",Ge="https://hub.dev.codepipe.dev"});function Tn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Rf&&t<=Fe}var Fe,Rf,As=R(()=>{"use strict";Wo();Fe=4,Rf=4});var _s=R(()=>{"use strict";Wo()});function In(t=3){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 Ns(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 Os(t,e=_s){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 Ds(t,e=_s){return e.filter(r=>r.version>t)}var He,Ur,_s,Us=R(()=>{"use strict";He=".codepipe-context.yaml",Ur=".devpipe-context.yaml",_s=[{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",He]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[He]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]}]});var Ls=R(()=>{"use strict"});var Tf,Zb,Bs=R(()=>{"use strict";Tf=[{id:"intake",label:"Intake",phases:["INTAKE"]},{id:"analysis",label:"Analysis",phases:["ANALYZING","ESTIMATING"]},{id:"ready",label:"Ready",phases:["READY"]},{id:"implementation",label:"Implementation",phases:["IMPLEMENTING","BUILD"]},{id:"delivery",label:"Delivery",phases:["READY_TO_APPLY","APPLYING"]}],Zb=Tf.flatMap(t=>t.phases)});function Et(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ms,Yo=R(()=>{"use strict";Ms=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});var Ke,Cn,If,qo,Gs,Vo=R(()=>{"use strict";Ke="opus",Cn="sonnet",If="haiku",qo=[Ke,Cn,If],Gs={analyze:Ke,implement:Ke,"resolve-conflict":Ke,rework:Ke,estimate:Cn,build:Cn,"code-review":Ke,draft:Cn,index:Ke,backfill:Ke,analysis:Ke,chat:Ke}});function pt(t){return Cf.has(t)?!0:Pf.some(e=>t.startsWith(e))}function Pn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function jt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Jo(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Ys(t,e){let r=Pn(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=jt(r.id,"id")??n;if(!Fs.test(o))throw new Error(`id must match ${Fs} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=jt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let d=Pn(r.env,"env");s={};for(let[u,m]of Object.entries(d)){if(!Se.test(u))throw new Error(`env name "${u}" must match ${Se}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${u} must be a scalar`);s[u]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Hs)throw new Error(`too many params (max ${Hs})`);let d=new Set;a=c.map((u,m)=>Ef(u,m,d))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>Ks)throw new Error(`too many steps (max ${Ks})`);let p=l.map((d,u)=>{let m=Pn(d,`steps[${u}]`),f=jt(m.run,`steps[${u}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${u}].run is required`);let y=jt(m.name,`steps[${u}].name`),w=Jo(m.timeout_sec,`steps[${u}].timeout_sec`);if(w!==void 0&&(!Number.isInteger(w)||w<=0))throw new Error(`steps[${u}].timeout_sec must be a positive integer`);return{run:f,...y?{name:y}:{},...w!==void 0?{timeout_sec:w}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:p}}function Ef(t,e,r){let n=Pn(t,`params[${e}]`),o=jt(n.name,`params[${e}].name`);if(!o||!Se.test(o))throw new Error(`params[${e}].name must match ${Se}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=jt(n.label,`params[${e}].label`),c=jt(n.help,`params[${e}].help`),l=n.required===!0,p=Jo(n.min,`params[${e}].min`),d=Jo(n.max,`params[${e}].max`),u=n.default;if(u!=null&&typeof u!="string"&&typeof u!="number"&&typeof u!="boolean")throw new Error(`params[${e}].default must be a scalar`);return{name:o,type:i,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...s?{enum:s}:{},...p!==void 0?{min:p}:{},...d!==void 0?{max:d}:{},...u!=null?{default:u}:{}}}function qs(t,e){let r=t.params??[],n=new Map(r.map(i=>[i.name,i]));for(let i of Object.keys(e))if(!n.has(i))return{ok:!1,error:`unknown param: ${i}`};let o={};for(let i of r){let s=e[i.name];if(s==null||typeof s=="string"&&s.trim()==="")if(i.default!==void 0)s=i.default;else{if(i.required)return{ok:!1,error:`${i.name} is required`};continue}switch(i.type){case"string":{if(typeof s!="string")return{ok:!1,error:`${i.name} must be a string`};o[i.name]=s;break}case"enum":{if(typeof s!="string"||!(i.enum??[]).includes(s))return{ok:!1,error:`${i.name} must be one of: ${(i.enum??[]).join(", ")}`};o[i.name]=s;break}case"number":{let a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${i.name} must be a number`};if(i.min!==void 0&&a<i.min)return{ok:!1,error:`${i.name} must be \u2265 ${i.min}`};if(i.max!==void 0&&a>i.max)return{ok:!1,error:`${i.name} must be \u2264 ${i.max}`};o[i.name]=a;break}case"boolean":{let a=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:null;if(a===null)return{ok:!1,error:`${i.name} must be a boolean`};o[i.name]=a;break}}}return{ok:!0,values:o}}var Se,Cf,Pf,Ws,Fs,Hs,Ks,zo=R(()=>{"use strict";Se=/^[A-Z][A-Z0-9_]*$/,Cf=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Pf=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ws=600,Fs=/^[a-z0-9-]+$/,Hs=32,Ks=64});function Xs(t=jf){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Xs(r.groups));return e}function Af(t,e){let r=JSON.stringify(e);return Xs().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Qs(t){let e=Af(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}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{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}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Vs)return{ok:!1,error:`${e.id} must have \u2264 ${Vs} entries`};let s={};for(let[a,c]of i){if(!Se.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Se}`};if(pt(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>Js)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Js} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Vs,Js,zs,jf,Zs=R(()=>{"use strict";zo();Yo();Vo();Vs=64,Js=2e3,zs=2e3,jf=[{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:[...qo],help:"Overrides the recommended defaults for every role not listed below."},...Ms.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...qo],help:`recommended: ${Gs[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:zs,help:'e.g. "English, imperative mood, first line \u2264 72 chars, start with the issue key". Empty \u21D2 "<KEY>: <task title>".'},{id:"apply.pr_style",file:"project.yaml",path:["apply","pr_style"],type:"string",label:"PR description style",nullable:!0,multiline:!0,maxLength:zs,help:'e.g. "Russian, implementation details, bullet list of what was done". Empty \u21D2 the default PR body.'}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{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."}]}]});var ea=R(()=>{"use strict"});var ta=R(()=>{"use strict"});var ra=R(()=>{"use strict"});var na=R(()=>{"use strict"});function oa(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("/."))}function et(t){return`${t}${_f}`}var At,_f,ia=R(()=>{"use strict";At=/^[a-z][a-z0-9-]{1,30}$/,_f="-codepipe-ctx"});var sa=R(()=>{"use strict"});var aa=R(()=>{"use strict"});function qt(t){for(let e of Nf){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Nf,ca=R(()=>{"use strict";Nf=[{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}]});var la=R(()=>{"use strict"});var ua=R(()=>{"use strict"});var pa=R(()=>{"use strict"});function da(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function ma(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=da(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Vt.test(r))return r;let n=da(t);return Vt.test(n)?n:Xo}function ga(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),i=t.slice(0,10-o.length)+o;if(!r.has(i.toUpperCase()))return i}return t}function Br(t){return`tasks/${t}/issue.yaml`}var fa,En,Xo,Vt,Qo,f$,jn,Lr,ha=R(()=>{"use strict";fa=["bug","feature","epic"],En="feature",Xo="TASK",Vt=/^[A-Z][A-Z0-9]{1,9}$/;Qo={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},f$=Qo.backlog,jn="tracker/config.yaml",Lr="tracker/counter"});var ya=R(()=>{"use strict"});function Jt(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}function An(t){switch(t){case Mr.gitlab:return"oauth2";case Mr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Mr,_t,wa=R(()=>{"use strict";Mr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};_t="x-bitbucket-api-token-auth"});var ka=R(()=>{"use strict"});var ba=R(()=>{"use strict";ya();wa();ka()});var $a,q=R(()=>{"use strict";js();As();Us();Ls();Bs();Yo();Vo();Zs();zo();ea();ta();ra();na();ia();sa();aa();ca();la();ua();pa();ha();ba();$a=20});function K(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ne=R(()=>{"use strict"});import{existsSync as va,renameSync as Of}from"node:fs";function Nt(t,e,r=n=>console.error(n)){if(va(e)||!va(t))return!1;try{return Of(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 _n=R(()=>{"use strict"});import{existsSync as Nn,readFileSync as xa,readdirSync as Df,writeFileSync as Uf}from"node:fs";import{dirname as Lf,join as dt}from"node:path";import{parse as Bf}from"yaml";function Mf(t=process.cwd()){let e=t;for(;;){if(Nn(dt(e,We,"project.yaml")))return e;if(Nn(dt(e,Zo,"project.yaml")))return Nt(dt(e,Zo),dt(e,We))&&Ff(e),e;let r=Lf(e);if(r===e)return null;e=r}}function Gf(t){let e=dt(t,We);return Nn(e)?e:dt(t,Zo)}function Ff(t){let e=dt(t,".gitignore");if(!Nn(e))return;let r=xa(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&&Uf(e,n)}function Re(t=process.cwd()){let e=Mf(t);if(!e)return null;let r=Gf(e),n=Hf(
|
|
7
|
-
`,{mode:384})}function Un(t){if(t)return{cfg:Te(t),profile:t};let e;try{e=Re()?.spec.projectId||void 0}catch{}if(e){let r=Oe(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:Te(void 0),profile:void 0}}function Te(t){let e=Oe(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 ${zt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var
|
|
8
|
-
`,{mode:384})}function Bn(){return
|
|
9
|
-
`,{mode:384})}function Xt(t){let e=M(t)?.claude?.oauthToken;return e||ti()?.claude?.oauthToken}function Gr(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 Qt(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var re=R(()=>{"use strict"});import{appendFileSync as Jf,existsSync as
|
|
5
|
+
`}function Os(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 Ds(t,e=Ns){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 Us(t,e=Ns){return e.filter(r=>r.version>t)}var He,Ur,Ns,Ls=R(()=>{"use strict";He=".codepipe-context.yaml",Ur=".devpipe-context.yaml",Ns=[{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",He]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[He]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]}]});var Bs=R(()=>{"use strict"});var Tf,o$,Ms=R(()=>{"use strict";Tf=[{id:"intake",label:"Intake",phases:["INTAKE"]},{id:"analysis",label:"Analysis",phases:["ANALYZING","ESTIMATING"]},{id:"ready",label:"Ready",phases:["READY"]},{id:"implementation",label:"Implementation",phases:["IMPLEMENTING","BUILD"]},{id:"delivery",label:"Delivery",phases:["READY_TO_APPLY","APPLYING"]}],o$=Tf.flatMap(t=>t.phases)});function Et(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Gs,Yo=R(()=>{"use strict";Gs=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});var Ke,Cn,If,qo,Fs,Vo=R(()=>{"use strict";Ke="opus",Cn="sonnet",If="haiku",qo=[Ke,Cn,If],Fs={analyze:Ke,implement:Ke,"resolve-conflict":Ke,rework:Ke,estimate:Cn,build:Cn,"code-review":Ke,draft:Cn,index:Ke,backfill:Ke,analysis:Ke,chat:Ke}});function pt(t){return Cf.has(t)?!0:Pf.some(e=>t.startsWith(e))}function Pn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function jt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Jo(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function qs(t,e){let r=Pn(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=jt(r.id,"id")??n;if(!Hs.test(o))throw new Error(`id must match ${Hs} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=jt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let f=Pn(r.env,"env");s={};for(let[u,m]of Object.entries(f)){if(!Se.test(u))throw new Error(`env name "${u}" must match ${Se}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${u} must be a scalar`);s[u]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Ks)throw new Error(`too many params (max ${Ks})`);let f=new Set;a=c.map((u,m)=>Ef(u,m,f))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>Ws)throw new Error(`too many steps (max ${Ws})`);let p=l.map((f,u)=>{let m=Pn(f,`steps[${u}]`),d=jt(m.run,`steps[${u}].run`);if(!d||d.trim().length===0)throw new Error(`steps[${u}].run is required`);let h=jt(m.name,`steps[${u}].name`),y=Jo(m.timeout_sec,`steps[${u}].timeout_sec`);if(y!==void 0&&(!Number.isInteger(y)||y<=0))throw new Error(`steps[${u}].timeout_sec must be a positive integer`);return{run:d,...h?{name:h}:{},...y!==void 0?{timeout_sec:y}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:p}}function Ef(t,e,r){let n=Pn(t,`params[${e}]`),o=jt(n.name,`params[${e}].name`);if(!o||!Se.test(o))throw new Error(`params[${e}].name must match ${Se}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(d=>typeof d=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=jt(n.label,`params[${e}].label`),c=jt(n.help,`params[${e}].help`),l=n.required===!0,p=Jo(n.min,`params[${e}].min`),f=Jo(n.max,`params[${e}].max`),u=n.default;if(u!=null&&typeof u!="string"&&typeof u!="number"&&typeof u!="boolean")throw new Error(`params[${e}].default must be a scalar`);return{name:o,type:i,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...s?{enum:s}:{},...p!==void 0?{min:p}:{},...f!==void 0?{max:f}:{},...u!=null?{default:u}:{}}}function Vs(t,e){let r=t.params??[],n=new Map(r.map(i=>[i.name,i]));for(let i of Object.keys(e))if(!n.has(i))return{ok:!1,error:`unknown param: ${i}`};let o={};for(let i of r){let s=e[i.name];if(s==null||typeof s=="string"&&s.trim()==="")if(i.default!==void 0)s=i.default;else{if(i.required)return{ok:!1,error:`${i.name} is required`};continue}switch(i.type){case"string":{if(typeof s!="string")return{ok:!1,error:`${i.name} must be a string`};o[i.name]=s;break}case"enum":{if(typeof s!="string"||!(i.enum??[]).includes(s))return{ok:!1,error:`${i.name} must be one of: ${(i.enum??[]).join(", ")}`};o[i.name]=s;break}case"number":{let a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${i.name} must be a number`};if(i.min!==void 0&&a<i.min)return{ok:!1,error:`${i.name} must be \u2265 ${i.min}`};if(i.max!==void 0&&a>i.max)return{ok:!1,error:`${i.name} must be \u2264 ${i.max}`};o[i.name]=a;break}case"boolean":{let a=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:null;if(a===null)return{ok:!1,error:`${i.name} must be a boolean`};o[i.name]=a;break}}}return{ok:!0,values:o}}var Se,Cf,Pf,Ys,Hs,Ks,Ws,zo=R(()=>{"use strict";Se=/^[A-Z][A-Z0-9_]*$/,Cf=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Pf=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ys=600,Hs=/^[a-z0-9-]+$/,Ks=32,Ws=64});function Qs(t=jf){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Qs(r.groups));return e}function Af(t,e){let r=JSON.stringify(e);return Qs().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Zs(t){let e=Af(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}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{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}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Js)return{ok:!1,error:`${e.id} must have \u2264 ${Js} entries`};let s={};for(let[a,c]of i){if(!Se.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Se}`};if(pt(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>zs)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${zs} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Js,zs,Xs,jf,ea=R(()=>{"use strict";zo();Yo();Vo();Js=64,zs=2e3,Xs=2e3,jf=[{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:[...qo],help:"Overrides the recommended defaults for every role not listed below."},...Gs.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...qo],help:`recommended: ${Fs[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:Xs,help:'e.g. "English, imperative mood, first line \u2264 72 chars, start with the issue key". Empty \u21D2 "<KEY>: <task title>".'},{id:"apply.pr_style",file:"project.yaml",path:["apply","pr_style"],type:"string",label:"PR description style",nullable:!0,multiline:!0,maxLength:Xs,help:'e.g. "Russian, implementation details, bullet list of what was done". Empty \u21D2 the default PR body.'}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{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."}]}]});var ta=R(()=>{"use strict"});var ra=R(()=>{"use strict"});var na=R(()=>{"use strict"});var oa=R(()=>{"use strict"});function ia(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("/."))}function et(t){return`${t}${_f}`}var At,_f,sa=R(()=>{"use strict";At=/^[a-z][a-z0-9-]{1,30}$/,_f="-codepipe-ctx"});var aa=R(()=>{"use strict"});var ca=R(()=>{"use strict"});function qt(t){for(let e of Nf){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Nf,la=R(()=>{"use strict";Nf=[{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}]});var ua=R(()=>{"use strict"});var pa=R(()=>{"use strict"});var da=R(()=>{"use strict"});function fa(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function ga(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=fa(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Vt.test(r))return r;let n=fa(t);return Vt.test(n)?n:Xo}function ha(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),i=t.slice(0,10-o.length)+o;if(!r.has(i.toUpperCase()))return i}return t}function Br(t){return`tasks/${t}/issue.yaml`}var ma,En,Xo,Vt,Qo,w$,jn,Lr,ya=R(()=>{"use strict";ma=["bug","feature","epic"],En="feature",Xo="TASK",Vt=/^[A-Z][A-Z0-9]{1,9}$/;Qo={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},w$=Qo.backlog,jn="tracker/config.yaml",Lr="tracker/counter"});var wa=R(()=>{"use strict"});function Jt(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}function An(t){switch(t){case Mr.gitlab:return"oauth2";case Mr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Mr,_t,ka=R(()=>{"use strict";Mr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};_t="x-bitbucket-api-token-auth"});var ba=R(()=>{"use strict"});var $a=R(()=>{"use strict";wa();ka();ba()});var va,q=R(()=>{"use strict";As();_s();Ls();Bs();Ms();Yo();Vo();ea();zo();ta();ra();na();oa();sa();aa();ca();la();ua();pa();da();ya();$a();va=20});function K(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ne=R(()=>{"use strict"});import{existsSync as xa,renameSync as Of}from"node:fs";function Nt(t,e,r=n=>console.error(n)){if(xa(e)||!xa(t))return!1;try{return Of(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 _n=R(()=>{"use strict"});import{existsSync as Nn,readFileSync as Sa,readdirSync as Df,writeFileSync as Uf}from"node:fs";import{dirname as Lf,join as dt}from"node:path";import{parse as Bf}from"yaml";function Mf(t=process.cwd()){let e=t;for(;;){if(Nn(dt(e,We,"project.yaml")))return e;if(Nn(dt(e,Zo,"project.yaml")))return Nt(dt(e,Zo),dt(e,We))&&Ff(e),e;let r=Lf(e);if(r===e)return null;e=r}}function Gf(t){let e=dt(t,We);return Nn(e)?e:dt(t,Zo)}function Ff(t){let e=dt(t,".gitignore");if(!Nn(e))return;let r=Sa(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&&Uf(e,n)}function Re(t=process.cwd()){let e=Mf(t);if(!e)return null;let r=Gf(e),n=Hf(Sa(dt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Ra(t,e,r){return Df(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 On(t,e=process.cwd()){try{let r=Re(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Hf(t){let e=Bf(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,f=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:l,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function Ta(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 We,Zo,tt=R(()=>{"use strict";_n();We=".codepipe",Zo=".devpipe"});import{homedir as Ia}from"node:os";import{mkdirSync as Kf,readFileSync as Wf,writeFileSync as Yf,existsSync as ei}from"node:fs";import{dirname as Pa,join as Dn,resolve as qf}from"node:path";import{fileURLToPath as Vf}from"node:url";function Ea(t){let e=Dn(Ca,".env");if(ei(e)&&process.loadEnvFile(e),t){let r=Dn(Ca,"profiles",t,".env");ei(r)&&process.loadEnvFile(r)}}function zt(t){let e=K("CONFIG");return e||(t?Dn(Ia(),".codepipe","profiles",t,"config.json"):Dn(Ia(),".codepipe","config.json"))}function Oe(t){let e=zt(t);if(!ei(e))return null;let r=Wf(e,"utf-8");return JSON.parse(r)}function rt(t,e){let r=zt(e);Kf(Pa(r),{recursive:!0}),Yf(r,JSON.stringify(t,null,2)+`
|
|
7
|
+
`,{mode:384})}function Un(t){if(t)return{cfg:Te(t),profile:t};let e;try{e=Re()?.spec.projectId||void 0}catch{}if(e){let r=Oe(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:Te(void 0),profile:void 0}}function Te(t){let e=Oe(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 ${zt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Ca,ke=R(()=>{"use strict";Ne();tt();Ca=qf(Pa(Vf(import.meta.url)),"..")});import{homedir as Na}from"node:os";import{existsSync as Oa,mkdirSync as Da,readFileSync as Ua,writeFileSync as La}from"node:fs";import{dirname as Ba,join as Ma}from"node:path";function Ga(t,e,r){let n=M(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},X(n)}function Fa(t,e){let r=M(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],X(r),!0)}function Ha(t){return Object.keys(M(t)?.secrets??{}).sort()}function Ln(t,e,r){let n=M(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,X(n),"pinned")}function Ka(t,e){let r=M(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],X(r),!0):!1}function Ye(t){return Ma(Na(),".codepipe","secrets",`${t}.json`)}function M(t){let e=Ye(t);return Oa(e)?JSON.parse(Ua(e,"utf-8")):null}function X(t){let e=Ye(t.projectId);Da(Ba(e),{recursive:!0}),La(e,JSON.stringify(t,null,2)+`
|
|
8
|
+
`,{mode:384})}function Bn(){return Ma(Na(),".codepipe","shared.json")}function ti(){let t=Bn();return Oa(t)?JSON.parse(Ua(t,"utf-8")):null}function Wa(t){let e=Bn();Da(Ba(e),{recursive:!0}),La(e,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function Xt(t){let e=M(t)?.claude?.oauthToken;return e||ti()?.claude?.oauthToken}function Gr(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 Qt(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var re=R(()=>{"use strict"});import{appendFileSync as Jf,existsSync as qa,mkdirSync as zf,renameSync as Va,statSync as Xf,unlinkSync as Qf}from"node:fs";import{Writable as Zf}from"node:stream";import{join as em}from"node:path";function Mn(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=tm(process.env[`${t}_MAX_BYTES`]??String(Ja.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Ja.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function tm(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 Gn(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(rm(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 rm(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:nm(o)).join(" ");return`${r} ${t} ${n}`}function nm(t){try{return JSON.stringify(t)}catch{return String(t)}}var Ja,Zt,ri=R(()=>{"use strict";Ja={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Zt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&zf(e.dir,{recursive:!0}),this.currentPath=em(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
|
-
`;Jf(this.currentPath,r,"utf-8")}asWritable(){return new Zf({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||!
|
|
11
|
+
`;Jf(this.currentPath,r,"utf-8")}asWritable(){return new Zf({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||!qa(this.currentPath)||Xf(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;qa(n)&&(r>=this.cfg.maxFiles?Qf(n):Va(n,`${this.currentPath}.${r+1}`))}Va(this.currentPath,`${this.currentPath}.1`)}}}});import{existsSync as ft,mkdirSync as oc,readFileSync as ai,writeFileSync as er}from"node:fs";import{homedir as wm}from"node:os";import{join as qe}from"node:path";import{simpleGit as km}from"simple-git";function Fr(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=qe(t,o);ft(s)||(er(s,i),r.push(o))}return r}function Ot(t,e,r){let n=qe(wm(),".codepipe","profiles",t,"context-config");return oc(n,{recursive:!0}),er(qe(n,"project.yaml"),e.projectYaml),er(qe(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Kn(t,e,r){if(ft(e))for(let n of tr){let o=qe(e,n),i=qe(t,n);if(!(!ft(o)||ft(i)))try{er(i,ai(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)}`)}}}function rr(t){let e=qe(t,".gitignore"),r=ft(e)?ai(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(tr.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
12
12
|
`)?"":`
|
|
13
13
|
`;return er(e,r+i+bm.join(`
|
|
14
14
|
`)+`
|
|
15
|
-
`),!0}async function
|
|
16
|
-
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;rr(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 ui(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 ci(t){let e=new Map;for(let r of tr){let n=qe(t,r);ft(n)&&e.set(r,ai(n))}return e}function li(t,e){
|
|
15
|
+
`),!0}async function ic(t,e){try{if(!ft(qe(t,".git")))return;let r=km(t),n=(await r.raw(["ls-files","--",...tr])).split(`
|
|
16
|
+
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;rr(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 ui(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 ci(t){let e=new Map;for(let r of tr){let n=qe(t,r);ft(n)&&e.set(r,ai(n))}return e}function li(t,e){oc(t,{recursive:!0});for(let[r,n]of e){let o=qe(t,r);ft(o)||er(o,n)}}var tr,bm,nt=R(()=>{"use strict";mt();tr=["project.yaml","regimen.yaml"];bm=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as $m,mkdirSync as vm,rmSync as xm,writeFileSync as pi}from"node:fs";import{dirname as Sm,isAbsolute as Rm,join as cc,normalize as Yn}from"node:path";import{simpleGit as lc}from"simple-git";async function di(t,e){let r=Yn(t),o=(Wn.get(r)??Promise.resolve()).catch(()=>{}).then(e);Wn.set(r,o);try{return await o}finally{Wn.get(r)===o&&Wn.delete(r)}}async function ot(t,e,r){return di(t,()=>fi(t,e,r))}async function fi(t,e,r){if(!$m(cc(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=ue(t,i.path);if(i.deleted){xm(s,{force:!0});continue}vm(Sm(s),{recursive:!0}),i.encoding==="base64"?pi(s,Buffer.from(i.content,"base64")):pi(s,i.content)}let n=lc(t);await n.add(["-A","--","."]),await n.raw(["reset","-q","--",...tr]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await ui(t))}async function ui(t){let e=lc(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=sc;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 Cm(e);if(i.length>0&&i.every(a=>Tm.has(a)||ac.test(a))){for(let a of i)ac.test(a)?await Im(e,t,a):await e.raw(["checkout","--theirs","--",a]);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 ${sc} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Im(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
|
|
17
17
|
`)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);pi(ue(e,r),i.join(`
|
|
18
18
|
`)+(i.length>0?`
|
|
19
19
|
`:""))}async function Cm(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
20
|
-
`).map(r=>r.trim()).filter(Boolean)}function ue(t,e){if(Rm(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Yn(
|
|
21
|
-
`+t.slice(t.length-e)}async function gt(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 Vn(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 ht(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 Gm(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 Gm(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Jn(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=gc.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${gc.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function yt(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 hc(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}}function Fm(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"}}function gi(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 De(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new yi(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new hi(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new wi(e)}return new ki}var Dt,gc,hi,yi,wi,ki,wt=R(()=>{"use strict";Dt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};gc=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];hi=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 Dt(`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 addPRComment(e,r,n){let o=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(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);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()}`)}},yi=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 Dt(`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 m=(await u.json()).jobs??[];for(let f of m.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();p.push(`### CI job: ${f.name}
|
|
20
|
+
`).map(r=>r.trim()).filter(Boolean)}function ue(t,e){if(Rm(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Yn(cc(t,e)),n=Yn(t+"/");if(r!==Yn(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var sc,Tm,ac,Wn,mt=R(()=>{"use strict";nt();sc=3,Tm=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),ac=/^tasks\/[^/]+\/comments\.jsonl$/,Wn=new Map});function gc(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
21
|
+
`+t.slice(t.length-e)}async function gt(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 Vn(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 ht(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 Gm(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 Gm(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Jn(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=hc.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${hc.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function yt(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 yc(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}}function Fm(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"}}function gi(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 De(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new yi(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new hi(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new wi(e)}return new ki}var Dt,hc,hi,yi,wi,ki,wt=R(()=>{"use strict";Dt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};hc=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];hi=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 Dt(`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 addPRComment(e,r,n){let o=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(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);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()}`)}},yi=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 Dt(`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 f of p.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(l=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let 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 f of l.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${o}/actions/runs/${f.id}/jobs?per_page=50`,{headers:n});if(!u.ok)continue;let m=(await u.json()).jobs??[];for(let d of m.filter(h=>h.conclusion==="failure")){let h=await fetch(`${o}/actions/jobs/${d.id}/logs`,{headers:n});if(!h.ok)continue;let y=await h.text();p.push(`### CI job: ${d.name}
|
|
22
22
|
|
|
23
|
-
${
|
|
23
|
+
${gc(y,8e3)}`)}}return p.length===0?void 0:gc(p.join(`
|
|
24
24
|
|
|
25
|
-
`),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 addPRComment(e,r,n){let o=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(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);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()}`)}},wi=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 Dt(`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=Fm(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 addPRComment(e,r,n){let o=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(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);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()}`)}};ki=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(gi(e,r,"merge"))}async closePR(e,r,n){throw new Error(gi(e,r,"close"))}async addPRComment(e,r,n){throw new Error(gi(e,r,"comment"))}}});import{existsSync as kt,readFileSync as nr,readdirSync as
|
|
25
|
+
`),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 addPRComment(e,r,n){let o=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(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);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()}`)}},wi=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 Dt(`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=Fm(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 addPRComment(e,r,n){let o=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(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);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()}`)}};ki=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(gi(e,r,"merge"))}async closePR(e,r,n){throw new Error(gi(e,r,"close"))}async addPRComment(e,r,n){throw new Error(gi(e,r,"comment"))}}});import{existsSync as kt,readFileSync as nr,readdirSync as kc}from"node:fs";import{join as bi}from"node:path";import{simpleGit as bc}from"simple-git";import{parse as $c}from"yaml";function vc(t){try{let e=ue(t,jn);if(!kt(e))return null;let r=$c(nr(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Vt.test(n)?null:{prefix:n}}catch{return null}}function xc(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
26
26
|
# The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
|
|
27
27
|
# later would orphan existing tasks/<KEY>/ directories.
|
|
28
28
|
prefix: ${t}
|
|
@@ -31,14 +31,14 @@ prefix: ${t}
|
|
|
31
31
|
# Backlog | To Do | In Progress | Review | Done | Rejected
|
|
32
32
|
# A configurable status set / pipeline mapping is a planned extension.
|
|
33
33
|
`}function $i(t=0){return`${t}
|
|
34
|
-
`}function Hm(t){return t==="depends_on"||t==="subtask"}function Km(t){let e;try{e
|
|
34
|
+
`}function Hm(t){return t==="depends_on"||t==="subtask"}function Km(t){let e;try{e=$c(t)}catch{return null}if(!e||typeof e!="object")return null;let r=e;if(typeof r.key!="string"||r.key.length===0||typeof r.title!="string"||r.title.length===0)return null;let n=ma.includes(r.type)?r.type:En,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;Hm(l.type)&&typeof l.target=="string"&&l.target&&o.push({type:l.type,targetKey:l.target})}let i=typeof r.created=="string"?r.created:new Date(0).toISOString(),s=typeof r.updated=="string"?r.updated:i,a=typeof r.assignee=="string"&&r.assignee.trim().length>0?r.assignee.trim():void 0;return{key:r.key,title:r.title,type:n,status:typeof r.status=="string"&&r.status?r.status:"Backlog",...a?{assignee:a}:{},links:o,created:i,updated:s}}function vi(t){let e=[`key: ${t.key}`,`title: ${JSON.stringify(t.title)}`,`type: ${t.type}`,`status: ${JSON.stringify(t.status)}`];if(t.assignee&&e.push(`assignee: ${JSON.stringify(t.assignee)}`),t.links.length>0){e.push("links:");for(let r of t.links)e.push(` - type: ${r.type}`,` target: ${r.targetKey}`)}return e.push(`created: ${t.created}`,`updated: ${t.updated}`),e.join(`
|
|
35
35
|
`)+`
|
|
36
|
-
`}function Kr(t,e){let r=ue(t,Br(e));return kt(r)?Km(nr(r,"utf-8")):null}function
|
|
36
|
+
`}function Kr(t,e){let r=ue(t,Br(e));return kt(r)?Km(nr(r,"utf-8")):null}function Sc(t){let e=bi(t,"tasks");if(!kt(e))return[];let r=[];for(let n of kc(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Kr(t,n.name);o&&r.push(o)}return r}function Wm(t,e){let r=ue(t,`tasks/${e}/task.md`);if(!kt(r))return;let n=nr(r,"utf-8").split(`
|
|
37
37
|
`),o=n.indexOf("---");if(o<0)return;let i=n.slice(o+1),s=i.lastIndexOf("## Attachments");s>=0&&i.slice(s+1).every(p=>p.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(p.trim()))&&(i=i.slice(0,s));let a=i.join(`
|
|
38
|
-
`).trim();if(!(!a||a==="_(no description)_"))return a}function Wr(t,e,r={}){let n=r.withDescription?Wm(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:Ym(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function Ym(t){return t.charAt(0).toUpperCase()+t.slice(1)}function qm(t){let e=ue(t,Lr);if(!kt(e))return 0;let r=Number.parseInt(nr(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function Vm(t,e){let r=bi(t,"tasks");if(!kt(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of
|
|
38
|
+
`).trim();if(!(!a||a==="_(no description)_"))return a}function Wr(t,e,r={}){let n=r.withDescription?Wm(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:Ym(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function Ym(t){return t.charAt(0).toUpperCase()+t.slice(1)}function qm(t){let e=ue(t,Lr);if(!kt(e))return 0;let r=Number.parseInt(nr(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function Vm(t,e){let r=bi(t,"tasks");if(!kt(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of kc(r,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=n.exec(i.name);if(!s)continue;let a=Number.parseInt(s[1],10);Number.isFinite(a)&&a>o&&(o=a)}return o}function Jm(t,e){return Math.max(qm(t),Vm(t,e))+1}async function Rc(t,e,r,n){return di(t,()=>zm(t,e,r,n))}async function zm(t,e,r,n){if(!kt(bi(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Hr(t);let o=null;for(let i=0;i<wc;i++){let s=Jm(t,e),a=`${e}-${s}`,c=[...r(a),{path:Lr,content:$i(s)}];try{return await fi(t,c,n(a)),a}catch(l){if(o=l,await Qm(t,n(a)),await Hr(t),Xm(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${wc} attempts: ${o instanceof Error?o.message:String(o)}`)}function Xm(t,e){for(let r of e){let n=ue(t,r.path);if(!kt(n)||(r.encoding==="base64"?nr(n).toString("base64"):nr(n,"utf-8"))!==r.content)return!1}return!0}async function Hr(t){let e=bc(t);try{await e.fetch()}catch{return}try{let r=(await e.revparse(["--abbrev-ref","HEAD"])).trim();await e.rebase([`origin/${r}`])}catch{await e.rebase(["--abort"]).catch(()=>{})}}async function Qm(t,e){let r=bc(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
|
|
39
39
|
`)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
|
|
40
40
|
`).some(i=>i.trim()===e.split(`
|
|
41
|
-
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var
|
|
41
|
+
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var wc,zn=R(()=>{"use strict";q();mt();wc=5});function or(t,e,r,n){return[{path:"README.md",content:lg(t,e)},{path:".gitignore",content:ng()},{path:"CLAUDE.md",content:ig(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:og()},{path:"knowledge/README.md",content:sg()},{path:"knowledge/build.yaml",content:cg()},{path:"actions/README.md",content:ag()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:rg()},{path:"adr/README.md",content:Zm()},{path:"adr/0000-template.md",content:eg()},{path:"adr/INDEX.md",content:tg()},{path:He,content:In()},...t.trackerProvider==="internal"?[{path:jn,content:xc(t.youtrackProjectKey??Xo)},{path:Lr,content:$i()}]:[]]}function Zm(){return`# ADR \u2014 architecture decision records
|
|
42
42
|
|
|
43
43
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
44
44
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -315,8 +315,8 @@ branch:
|
|
|
315
315
|
pattern: codepipe/<TASK_ID>
|
|
316
316
|
|
|
317
317
|
repos:
|
|
318
|
-
${
|
|
319
|
-
`}function
|
|
318
|
+
${Tc(t)}
|
|
319
|
+
`}function Tc(t){return t.repos.length===0?` [] # add repos here
|
|
320
320
|
`:t.repos.map(e=>` - name: ${e.name}
|
|
321
321
|
host: ${e.host}
|
|
322
322
|
owner: ${e.owner}
|
|
@@ -371,7 +371,7 @@ ${Rc(t)}
|
|
|
371
371
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
372
372
|
${o}`:` # project_key: \u2026
|
|
373
373
|
# tracker_url: https://your.youtrack.cloud
|
|
374
|
-
poll_interval_sec: 60`,s=
|
|
374
|
+
poll_interval_sec: 60`,s=Tc(t);return`# Project description for CodePipe.
|
|
375
375
|
id: ${t.projectId}
|
|
376
376
|
name: ${t.name}
|
|
377
377
|
|
|
@@ -537,19 +537,19 @@ llm:
|
|
|
537
537
|
# # the previous task's branch (auto-merge without reworking the
|
|
538
538
|
# # tail of the chain).
|
|
539
539
|
# mode: parallel
|
|
540
|
-
`}var Ut=R(()=>{"use strict";q();zn()});import{createCipheriv as jg,createDecipheriv as Ag,createHash as _g,createPrivateKey as Ng,createPublicKey as Ti,diffieHellman as
|
|
541
|
-
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Mg(t,e,r){return new Promise((n,o)=>{let i=bt.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 qc(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Ii(t,e,r){return new Promise(n=>{let o=bt.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 Gg(t){try{let e=await fetch(t);return e.ok?new qc(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Qc(t,e=443,r=Jc){let n=`${t}:${e}`,o=Yc.get(n);if(o)return o;let i=Fg(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Yc.set(n,i),i}async function Fg(t,e,r){if(!Vc)return!1;let n=8e3;if(await Ii(t,e,n))return!0;let o=await Mg(t,e,n),i=bt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Bg(o);if(!c)break;let l=await Gg(c);if(!l)break;if(s.push(l.toString()),bt.setDefaultCACertificates([...i,...s]),await Ii(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 Ii(t,e,n)}var Vc,Wc,Yc,Jc,Zc=R(()=>{"use strict";Ne();Vc=typeof bt.getCACertificates=="function"&&typeof bt.setDefaultCACertificates=="function",Wc=!1,Yc=new Map,Jc=t=>console.warn(t)});function nl(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Pe(t,e,r){zc();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(Xc(s)&&await Qc(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Hg(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Kg(){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 Ci(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Kg(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Pe(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&&Hg(l.status,p)){await el(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<o){await el(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function $t(t){let e;try{e=await Pe(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 ol(t){try{let e=await Pe(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Wg(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=tl.get(o);if(i)return i;let s=await Pe(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 tl.set(o,l.id),l.id}async function il(t,e,r,n=Xr){let o=await Wg(t,e,r,n);await Ci(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 sl(t,e,r){return await(await Ci(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function al(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Ci(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function cl(t,e){let r=rl.get(e);if(r)return r;let n=await Pe(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 rl.set(e,i.id),i.id}async function ll(t,e,r,n,o,i=Xr){let s=await cl(t,e),a=await Pe(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 ul(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Pe(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()}`)}function fl(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 ml(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 gl(t,e){let r=e.stageField??Xr,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=${dl}&$top=200`,s=await Pe(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>wl(c,r))}async function hl(t,e,r=Xr){let n=`/api/issues/${encodeURIComponent(e)}?fields=${dl}`,o=await Pe(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return wl(await o.json(),r)}async function yl(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${qg}&$top=500`,o=await Pe(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=fl(s.attachments);return c&&(a.attachments=c),a})}function Vg(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 wl(t,e=Xr){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=fl(t.attachments);a&&(s.attachments=a);let c=Vg(t.links);return c&&(s.links=c),s}async function kl(t,e){let r=await Jg(t,e);return r.length>0?r:zg(t,e)}async function Jg(t,e){let r=await cl(t,e),n=await Pe(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:bl(s.bundle)});return i}async function zg(t,e){let r=`project: ${e}`,n=await Pe(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:bl(s.projectCustomField?.bundle)});return i}function bl(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var el,Xr,tl,rl,pl,Yg,dl,qg,Lt=R(()=>{"use strict";Zc();el=t=>new Promise(e=>setTimeout(e,t));Xr="Stage",tl=new Map;rl=new Map;pl="attachments(id,name,url,size,mimeType)",Yg="links(direction,linkType(name),issues(idReadable))",dl=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${pl},${Yg}`,qg=`id,text,created,author(login),${pl}`});function Qr(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 Zr(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 en(t,e=process.env){if(!t)return!1;let r=`https://${_t}:${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 Ei(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 vl(t,e=process.env){return Ei(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Qr(t,e),e)}function xl(t,e=process.env){return Ei(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Zr(t,e),e)}function Sl(t,e=process.env){return Ei(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${_t}:${encodeURIComponent(t)}@bitbucket.org/`,()=>en(t,e),e)}var eo=R(()=>{"use strict";q()});import{homedir as Rh}from"node:os";import{existsSync as Th,mkdirSync as Ih,readFileSync as Ch,writeFileSync as Ph}from"node:fs";import{dirname as Eh,join as jh}from"node:path";function Oi(){return K("FARM_PINS")??jh(Rh(),".codepipe","farm-pins.json")}function Kl(){let t=Oi();if(!Th(t))return{};try{return JSON.parse(Ch(t,"utf-8"))}catch{return{}}}function Ah(t){let e=Oi();Ih(Eh(e),{recursive:!0}),Ph(e,JSON.stringify(t,null,2)+`
|
|
542
|
-
`,{mode:384})}function _h(t){return
|
|
540
|
+
`}var Ut=R(()=>{"use strict";q();zn()});import{createCipheriv as jg,createDecipheriv as Ag,createHash as _g,createPrivateKey as Ng,createPublicKey as Ti,diffieHellman as Gc,generateKeyPairSync as Fc,hkdfSync as Hc,randomBytes as Og}from"node:crypto";function Zn(){let{publicKey:t,privateKey:e}=Fc("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ye(t){let e=Buffer.from(t,"base64");return(_g("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function it(t,e){let r=Ti({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Fc("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Gc({privateKey:o,publicKey:r}),c=Buffer.from(Hc("sha256",a,Buffer.concat([i,s]),Kc,32)),l=Og(12),p=jg("aes-256-gcm",c,l),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,u=Buffer.concat([p.update(f),p.final()]),m=p.getAuthTag(),d={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:u.toString("base64")};return Buffer.from(JSON.stringify(d),"utf-8").toString("base64")}function ir(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=Ng({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Ti({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Ti(n).export({type:"spki",format:"der"}),a=Gc({privateKey:n,publicKey:o}),c=Buffer.from(Hc("sha256",a,Buffer.concat([i,s]),Kc,32)),l=Ag("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()])}var Kc,Ce=R(()=>{"use strict";Kc=Buffer.from("devpipe-sealedbox-v1","utf-8")});import{X509Certificate as Vc}from"node:crypto";import{readFileSync as Ug}from"node:fs";import bt from"node:tls";function Lg(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Xc(t=zc){if(Yc)return;Yc=!0;let e=K("EXTRA_CA_FILE");if(!(!e||!Jc))try{let r=Lg(Ug(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}bt.setDefaultCACertificates([...bt.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 Qc(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 Bg(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
541
|
+
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Mg(t,e,r){return new Promise((n,o)=>{let i=bt.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 Vc(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Ii(t,e,r){return new Promise(n=>{let o=bt.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 Gg(t){try{let e=await fetch(t);return e.ok?new Vc(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Zc(t,e=443,r=zc){let n=`${t}:${e}`,o=qc.get(n);if(o)return o;let i=Fg(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return qc.set(n,i),i}async function Fg(t,e,r){if(!Jc)return!1;let n=8e3;if(await Ii(t,e,n))return!0;let o=await Mg(t,e,n),i=bt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Bg(o);if(!c)break;let l=await Gg(c);if(!l)break;if(s.push(l.toString()),bt.setDefaultCACertificates([...i,...s]),await Ii(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 Ii(t,e,n)}var Jc,Yc,qc,zc,el=R(()=>{"use strict";Ne();Jc=typeof bt.getCACertificates=="function"&&typeof bt.setDefaultCACertificates=="function",Yc=!1,qc=new Map,zc=t=>console.warn(t)});function ol(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Pe(t,e,r){Xc();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(Qc(s)&&await Zc(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Hg(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Kg(){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 Ci(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Kg(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Pe(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&&Hg(l.status,p)){await tl(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<o){await tl(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function $t(t){let e;try{e=await Pe(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 il(t){try{let e=await Pe(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Wg(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=rl.get(o);if(i)return i;let s=await Pe(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 rl.set(o,l.id),l.id}async function sl(t,e,r,n=Xr){let o=await Wg(t,e,r,n);await Ci(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 al(t,e,r){return await(await Ci(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function cl(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Ci(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function ll(t,e){let r=nl.get(e);if(r)return r;let n=await Pe(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 nl.set(e,i.id),i.id}async function ul(t,e,r,n,o,i=Xr){let s=await ll(t,e),a=await Pe(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 pl(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Pe(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()}`)}function ml(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 gl(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 hl(t,e){let r=e.stageField??Xr,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=${fl}&$top=200`,s=await Pe(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>kl(c,r))}async function yl(t,e,r=Xr){let n=`/api/issues/${encodeURIComponent(e)}?fields=${fl}`,o=await Pe(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return kl(await o.json(),r)}async function wl(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${qg}&$top=500`,o=await Pe(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=ml(s.attachments);return c&&(a.attachments=c),a})}function Vg(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 kl(t,e=Xr){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=ml(t.attachments);a&&(s.attachments=a);let c=Vg(t.links);return c&&(s.links=c),s}async function bl(t,e){let r=await Jg(t,e);return r.length>0?r:zg(t,e)}async function Jg(t,e){let r=await ll(t,e),n=await Pe(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:$l(s.bundle)});return i}async function zg(t,e){let r=`project: ${e}`,n=await Pe(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:$l(s.projectCustomField?.bundle)});return i}function $l(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var tl,Xr,rl,nl,dl,Yg,fl,qg,Lt=R(()=>{"use strict";el();tl=t=>new Promise(e=>setTimeout(e,t));Xr="Stage",rl=new Map;nl=new Map;dl="attachments(id,name,url,size,mimeType)",Yg="links(direction,linkType(name),issues(idReadable))",fl=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${dl},${Yg}`,qg=`id,text,created,author(login),${dl}`});function Qr(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 Zr(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 en(t,e=process.env){if(!t)return!1;let r=`https://${_t}:${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 Ei(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 xl(t,e=process.env){return Ei(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Qr(t,e),e)}function Sl(t,e=process.env){return Ei(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Zr(t,e),e)}function Rl(t,e=process.env){return Ei(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${_t}:${encodeURIComponent(t)}@bitbucket.org/`,()=>en(t,e),e)}var eo=R(()=>{"use strict";q()});import{homedir as Rh}from"node:os";import{existsSync as Th,mkdirSync as Ih,readFileSync as Ch,writeFileSync as Ph}from"node:fs";import{dirname as Eh,join as jh}from"node:path";function Oi(){return K("FARM_PINS")??jh(Rh(),".codepipe","farm-pins.json")}function Wl(){let t=Oi();if(!Th(t))return{};try{return JSON.parse(Ch(t,"utf-8"))}catch{return{}}}function Ah(t){let e=Oi();Ih(Eh(e),{recursive:!0}),Ph(e,JSON.stringify(t,null,2)+`
|
|
542
|
+
`,{mode:384})}function _h(t){return Wl()[t]}function ao(t,e){let r=Wl();r[t]=e,Ah(r)}function co(t,e){let r=ye(e),n=_h(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 ${Oi()}.`);return r}var Di=R(()=>{"use strict";Ne();Ce()});import{setTimeout as Nh}from"node:timers/promises";import Oh from"ws";function lo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Oh(r)}async function vt(t,e,r){return Le(t,e,"/projects",r)}async function Yl(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new O(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function uo(t,e,r,n){return Le(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function ql(t,e,r,n){return Le(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Vl(t,e,r,n){return Le(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Jl(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 O(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function po(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new O(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Ui(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new O(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function zl(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Ui(t,e),a=new Set;for(let c of s)c.id!==r.excludeProjectId&&c.trackerProvider==="internal"&&c.youtrackProjectKey&&a.add(c.youtrackProjectKey.toUpperCase());return a}catch(s){o=s,i<n-1&&await Nh(r.delayMs??1500)}throw o}async function Xl(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 nn(e)}if(!r.ok)throw new O(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Ql(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new O(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Zl(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new O(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function eu(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 O(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function tu(t,e,r,n){return Le(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function ru(t,e,r,n,o){return Le(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function nu(t,e,r,n,o){return Le(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function ou(t,e,r,n,o){return Le(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function on(t,e,r,n){return Le(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Li(t,e,r,n){await Le(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function iu(t,e,r,n){return Le(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function su(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 O(o.status,s,a)}return s}async function J(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new O(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function Le(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 O(o.status,s,a)}return s}var O,nn,fe=R(()=>{"use strict";O=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};nn=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{execFileSync as oy}from"node:child_process";import{mkdtempSync as iy,mkdirSync as sy,readFileSync as Tu,rmSync as ay,writeFileSync as cy}from"node:fs";import{tmpdir as ly}from"node:os";import{dirname as uy,join as Iu}from"node:path";function Cu(t="codepipe-context"){let e=iy(Iu(ly(),"codepipe-ssh-")),r=Iu(e,"id_ed25519");try{return oy("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Tu(r,"utf-8"),publicKey:Tu(`${r}.pub`,"utf-8").trim()}}finally{ay(e,{recursive:!0,force:!0})}}async function Pu(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 Eu(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 ju(t,e){sy(uy(t),{recursive:!0});let r=e.endsWith(`
|
|
543
543
|
`)?e:e+`
|
|
544
|
-
`;return cy(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Hi=R(()=>{"use strict"});import{existsSync as
|
|
545
|
-
`,{mode:384})}var ko=R(()=>{"use strict";Ne();_n();Yi(".env")&&process.loadEnvFile(".env")});import $y from"ws";var lr,qi=R(()=>{"use strict";lr=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 $y(e)}}});import{hostname as vy}from"node:os";async function Bt(t){wo();let e=ge(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Be(t.profile)}.`),process.exit(1));let r=t.name??vy(),n=
|
|
546
|
-
`}async function
|
|
544
|
+
`;return cy(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Hi=R(()=>{"use strict"});import{existsSync as Au,mkdirSync as _u}from"node:fs";import{dirname as Nu}from"node:path";import{simpleGit as ar}from"simple-git";function py(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 dy(t,e){return e?.contextWrite?.token?{user:An(t),secret:e.contextWrite.token}:t===Mr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Mr.bitbucket?e?.bitbucket?.apiToken?{user:_t,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Ou(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 ho))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 yo(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await J(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new ho(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=dy(Jt(s.cloneUrl),r);if(a){let c=await fy({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 my({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 fy(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=py(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(Au(`${r}/.git`)){let l=ar(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let p=ci(r);await l.reset(["--hard",`origin/${s}`]),li(r,p),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else _u(Nu(r),{recursive:!0}),await ar().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Du(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 my(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=ju(i,n),a=Eu(e.cloneUrl),c=e.branch;try{if(Au(`${r}/.git`)){let l=ar(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=ci(r);await l.reset(["--hard",`origin/${c}`]),li(r,p),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else _u(Nu(r),{recursive:!0}),await ar().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await ar(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Du(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 Du(t){let e=ar(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"))}var ho,Ki=R(()=>{"use strict";q();fe();nt();Hi();ho=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as gy}from"node:child_process";function hy(){try{return gy("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Lu(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:hy(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Bu=R(()=>{"use strict"});import{homedir as cr}from"node:os";import{mkdirSync as yy,readFileSync as Mu,writeFileSync as wy,existsSync as Yi}from"node:fs";import{dirname as ky,join as xt}from"node:path";function by(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Be(t){let e=K("SANDBOX_CONFIG");if(e)return e;let r=xt(cr(),".codepipe","worker");return t?xt(r,"profiles",t,"config.json"):xt(r,"config.json")}function Gu(){return xt(cr(),".devpipe-sandbox","config.json")}function wo(){Nt(xt(cr(),".devpipe"),xt(cr(),".codepipe")),K("SANDBOX_CONFIG")||Nt(xt(cr(),".devpipe-sandbox"),xt(cr(),".codepipe-sandbox"))}function ge(t){let e=Be(t),r=null;return Yi(e)?r=JSON.parse(Mu(e,"utf-8")):!t&&!K("SANDBOX_CONFIG")&&Yi(Gu())&&(r=JSON.parse(Mu(Gu(),"utf-8"))),r?(r.planningLane=by(),r):null}function Fu(t,e){let r=Be(e);yy(ky(r),{recursive:!0}),wy(r,JSON.stringify(t,null,2)+`
|
|
545
|
+
`,{mode:384})}var ko=R(()=>{"use strict";Ne();_n();Yi(".env")&&process.loadEnvFile(".env")});import $y from"ws";var lr,qi=R(()=>{"use strict";lr=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 $y(e)}}});import{hostname as vy}from"node:os";async function Bt(t){wo();let e=ge(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Be(t.profile)}.`),process.exit(1));let r=t.name??vy(),n=Lu({projects:t.projects??[],llm:t.llm??null}),o=new lr(t.hub.replace(/\/$/,"")),i=Zn(),s=ye(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Fu({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 ${Be(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}var Hu=R(()=>{"use strict";Ce();Bu();ko();qi()});import{spawn as xy}from"node:child_process";function Vi(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Ry(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 Ty(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Mt(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ji(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
|
|
546
|
+
`}async function qu(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new st;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 f=c.message;for(let u of f?.content??[]){let m=u.type;if(m==="text"){let d=String(u.text??"").trim();d&&o({ts:l,kind:"text",author:"agent",text:Vi(d,Ku)})}else if(m==="tool_use"){let d=String(u.name??""),h=u.input?.file_path??u.input?.path,y=Ry(h,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:d,...y?{file:y}:{}})}}return}if(p==="user"){let f=c.message;for(let u of f?.content??[])if(u.type==="tool_result"){let m=u.is_error===!0,d=m?Vi(Ty(u.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:m,...d?{text:d}:{}})}return}if(p==="result"){s=c;let f=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...f?{text:f}:{}});return}if(p==="system"){let f=String(c.subtype??"").trim();f&&o({ts:l,kind:"system",author:"agent",text:f})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let p=xy(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 f=!1,u=!1,m=null,d=()=>{f=!0,p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Wu)};e.signal?.addEventListener("abort",d,{once:!0});let h=null,y=()=>{h&&clearTimeout(h),h=setTimeout(()=>{u=!0,console.warn(`[claude:chat] idle for ${Yu}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Wu)},Yu)},b=()=>{m&&clearTimeout(m),h&&clearTimeout(h),e.signal?.removeEventListener("abort",d)},w=!0,k=T=>{if(!(!w||p.stdin.destroyed))try{p.stdin.write(T)}catch{}};k(Ji(e.prompt)),y(),(async()=>{try{for await(let T of e.interactive.inbox){if(f||!w)break;if(y(),T.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:Vi(T.text,Ku)}),k(Ji(T.text));else{k(Ji(Sy)),w=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let C="",G=T=>{let _;try{_=JSON.parse(T)}catch{return}a(_)};p.stdout.on("data",T=>{i.push(T),y(),C+=T;let _;for(;(_=C.indexOf(`
|
|
547
547
|
`))!==-1;){let F=C.slice(0,_).trim();C=C.slice(_+1),F&&G(F)}}),p.stderr.on("data",T=>{i.push(T);for(let _ of T.split(`
|
|
548
|
-
`)){let F=_.trim();F&&console.warn(`[claude:chat:stderr] ${F}`)}}),p.on("error",T=>{
|
|
548
|
+
`)){let F=_.trim();F&&console.warn(`[claude:chat:stderr] ${F}`)}}),p.on("error",T=>{b(),l(T)}),p.on("close",T=>{if(b(),f){l(new st);return}if(u){l(new Error("chat session ended: idle for too long without a reply"));return}C.trim()&&G(C.trim()),console.log(`[claude:chat] exit code=${T}`),c({artifactPaths:[],log:i.join(""),usage:Iy(s)})})})}function Iy(t){let e=Et();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Mt(r.input_tokens),e.outputTokens=Mt(r.output_tokens),e.cacheReadInputTokens=Mt(r.cache_read_input_tokens),e.cacheCreationInputTokens=Mt(r.cache_creation_input_tokens)),e.totalCostUsd=Mt(t.total_cost_usd),e.numTurns=Mt(t.num_turns),e.durationMs=Mt(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Ku,Wu,Yu,Sy,Vu=R(()=>{"use strict";q();ur();Ku=16e3,Wu=5e3,Yu=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Sy="\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."});import{spawn as Cy}from"node:child_process";import{existsSync as Py}from"node:fs";function Ju(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: ${St(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=_y(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=Xu(o.content);console.log(`[claude] tool_result (error)${i?`: ${St(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)} ${St(JSON.stringify(e),200)}`),e}function jy(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(St(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(St(r.trim().split(`
|
|
549
549
|
`).slice(-5).join(`
|
|
550
|
-
`),500)),n.join(" \u2014 ")}function Ay(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
|
|
551
|
-
`))!==-1;){let F=G.slice(0,_).trim();if(G=G.slice(_+1),F){let E=
|
|
552
|
-
`)){let F=_.trim();F&&console.warn(`[claude:stderr] ${F}`)}}),
|
|
550
|
+
`),500)),n.join(" \u2014 ")}function Ay(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 Xu(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function _y(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=${St(r,80)}`}return""}function St(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function we(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ny(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=we(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:we(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 Oy(t,e,r,n){let o=Et(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=we(i.input_tokens),o.outputTokens=we(i.output_tokens),o.cacheReadInputTokens=we(i.cache_read_input_tokens),o.cacheCreationInputTokens=we(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=we(t?.total_cost_usd),o.numTurns=t&&we(t.num_turns)>0?we(t.num_turns):r,o.durationMs=we(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function Dy(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:St(c,zu)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,p=l?.file_path??l?.path??l?.notebook_path,f=Uy(p,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?St(Xu(s.content),zu):"";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 Uy(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}var pr,st,Ey,cn,zu,ur=R(()=>{"use strict";q();Vu();pr=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},st=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Ey=5e3,cn=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return qu(this.binary,e);if(e.signal?.aborted)throw new st;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let d of e.addDirs??[])r.push("--add-dir",d);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,p=d=>{if(d){if(d.type==="result"){i=d;return}if(d.type==="rate_limit_event"){let h=Ny(d.rate_limit_info);h&&(!l||h.utilization>l.utilization)&&(l=h);return}if(d.type==="assistant"){let h=d.message;typeof h?.model=="string"&&(c=h.model);let y=h?.usage;y&&(a+=1,s.input+=we(y.input_tokens),s.output+=we(y.output_tokens),s.cacheRead+=we(y.cache_read_input_tokens),s.cacheCreate+=we(y.cache_creation_input_tokens))}}},f=e.role,u=e.onActivity,m=d=>{if(u)for(let h of Dy(d,e.workspaceDir))try{u(h)}catch{}};return u?.({ts:Date.now(),kind:"start",text:`${f} job started`}),console.log(`[claude] spawn ${this.binary} role=${f}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((d,h)=>{let y=Cy(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"}});y.stdout.setEncoding("utf-8"),y.stderr.setEncoding("utf-8");let b=!1,w=null,k=()=>{b=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),y.kill("SIGTERM"),w=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),y.kill("SIGKILL")},Ey)};e.signal?.addEventListener("abort",k,{once:!0});let C=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",k)},G="";y.stdout.on("data",T=>{n.push(T),G+=T;let _;for(;(_=G.indexOf(`
|
|
551
|
+
`))!==-1;){let F=G.slice(0,_).trim();if(G=G.slice(_+1),F){let E=Ju(F);p(E),E&&m(E)}}}),y.stderr.on("data",T=>{n.push(T),o.push(T);for(let _ of T.split(`
|
|
552
|
+
`)){let F=_.trim();F&&console.warn(`[claude:stderr] ${F}`)}}),y.on("error",T=>{C(),h(T)}),y.on("close",T=>{if(C(),b){h(new st);return}if(G.trim()){let F=Ju(G.trim());p(F),F&&m(F)}let _=i?.is_error===!0;if(T!==0||_){let F=typeof i?.api_error_status=="number"?i.api_error_status:void 0,E=typeof i?.subtype=="string"?i.subtype:void 0,g=typeof i?.result=="string"?i.result:void 0;h(new pr(jy(T,i,o.join("")),{code:T,apiErrorStatus:F,subtype:E,resultText:g,retryAfterMs:Ay(i)}));return}console.log("[claude] exit code=0"),d({artifactPaths:[],log:n.join(""),usage:Oy(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("/")&&Py(n))}};zu=200});import{mkdirSync as Ly,writeFileSync as dr}from"node:fs";import{dirname as By,join as fr}from"node:path";function Qu(t,e,r){let n=fr(t,e);Ly(By(n),{recursive:!0}),dr(n,r)}function My(t,e,r){return`# ${t} \u2014 Estimate
|
|
553
553
|
|
|
554
554
|
**Title:** ${e}
|
|
555
555
|
|
|
@@ -624,35 +624,42 @@ ${r?`
|
|
|
624
624
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
625
625
|
|
|
626
626
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
627
|
-
`}var ln,zi=R(()=>{"use strict";q();ur();ln=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=My(n,o,i);dr(fr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;dr(fr(e.workspaceDir,"SOLUTION.md"),Gy(n,o,i,a)),s.push("SOLUTION.md"),dr(fr(e.workspaceDir,"QUESTIONS.md"),Fy(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;
|
|
627
|
+
`}var ln,zi=R(()=>{"use strict";q();ur();ln=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=My(n,o,i);dr(fr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;dr(fr(e.workspaceDir,"SOLUTION.md"),Gy(n,o,i,a)),s.push("SOLUTION.md"),dr(fr(e.workspaceDir,"QUESTIONS.md"),Fy(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Qu(e.workspaceDir,"changes/sample.patch",Hy(n,o,a)),s.push("changes/sample.patch"),Qu(e.workspaceDir,"diff-summary.md",Ky(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(dr(fr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
628
628
|
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:Et()}}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 st;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 dr(fr(e.workspaceDir,"DRAFT.md"),`${o}
|
|
629
629
|
|
|
630
630
|
\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).
|
|
631
|
-
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Et()}}}});function
|
|
631
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Et()}}}});function Zu(t){switch(t){case"mock":return new ln;case"claude-headless":return new cn;default:return null}}var ep=R(()=>{"use strict";ur();zi();ur();zi()});function np(t=process.env){return{maxAttempts:bo(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:bo(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:bo(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:bo(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function Vy(t){if(t instanceof pr){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return Yy.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&qy.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:Wy.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:tp.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 tp.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function op(t){if(t instanceof pr){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&rp.test(n)}let e=t instanceof Error?t.message:String(t);return rp.test(e)}function Jy(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 ip(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=Vy(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=Jy(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 bo(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var Wy,tp,Yy,qy,rp,sp=R(()=>{"use strict";ur();Wy=new Set([429,500,502,503,529]),tp=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,Yy=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,qy=new Set(["error_max_turns"]);rp=/(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});import{mkdtempSync as zy,rmSync as Xy,writeFileSync as ap}from"node:fs";import{tmpdir as Qy}from"node:os";import{join as Xi}from"node:path";function $o(t){return`[url "https://${t}/"]
|
|
632
632
|
insteadOf = git@${t}:
|
|
633
633
|
insteadOf = ssh://git@${t}/
|
|
634
|
-
`}function
|
|
634
|
+
`}function cp(t,e){if(t.length===0)return null;let r=zy(Xi(Qy(),"devpipe-gitcreds-")),n=Xi(r,"credentials"),o=Xi(r,"gitconfig");return ap(n,t.join(`
|
|
635
635
|
`)+`
|
|
636
|
-
`,{mode:384}),
|
|
636
|
+
`,{mode:384}),ap(o,`[credential]
|
|
637
637
|
helper = store --file=${n}
|
|
638
|
-
`+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{Xy(r,{recursive:!0,force:!0})}catch{}}}}function Qi(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Zy)),t.bitbucket?.apiToken&&(e.push(`https://${_t}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(ew)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(tw)),
|
|
639
|
-
`).map(
|
|
640
|
-
`).map(l=>l.trim()).filter(l=>l.length>0),c=await me(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function Z(t,e,r){return new Promise((n,o)=>{let i=
|
|
641
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function me(t,e,r){return new Promise((n,o)=>{let i=
|
|
642
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
643
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=rw(Gt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var mr,gr,hr,
|
|
644
|
-
`+e.subarray(e.length-ts).toString("utf-8")}var ts,Rt,un,
|
|
645
|
-
\u2026 [${r.length-e} bytes elided]`}var pw,dw,at,yr,
|
|
638
|
+
`+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{Xy(r,{recursive:!0,force:!0})}catch{}}}}function Qi(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Zy)),t.bitbucket?.apiToken&&(e.push(`https://${_t}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(ew)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(tw)),cp(e,r)}function lp(t,e){if(t.contextWrite?.token){let r=Jt(e)??"github.com",n=An(r);return cp([`https://${n}:${t.contextWrite.token}@${r}`],[$o(r)])}return Qi(t)}var Zy,ew,tw,up=R(()=>{"use strict";q();Zy=$o("github.com"),ew=$o("bitbucket.org"),tw=$o("gitlab.com")});import{spawn as dp}from"node:child_process";import{existsSync as vo,mkdirSync as xo,readFileSync as rw,rmSync as Zi,symlinkSync as nw}from"node:fs";import{homedir as ow}from"node:os";import{dirname as So,join as Gt}from"node:path";function fp(){return Gt(ow(),".codepipe-sandbox","repos")}function mp(t,e){let n=(mr.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{mr.get(t)===o&&mr.delete(t)},()=>{mr.get(t)===o&&mr.delete(t)});return mr.set(t,o),n}function pp(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 iw(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 gp(t,e,r,n,o){let i=async c=>{await Z(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await Z(t,["reset","--hard",`origin/${c}`],o),await Z(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!pp(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{vo(t)&&Zi(t,{recursive:!0,force:!0}),xo(So(t),{recursive:!0});try{return await Z(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!pp(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),vo(t)&&Zi(t,{recursive:!0,force:!0}),xo(So(t),{recursive:!0}),await Z(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(vo(Gt(t,".git")))try{return await s()}catch(c){if(!iw(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 hp(t){await Z(t.workspacePath,["reset","--hard",t.baseSha]),await Z(t.workspacePath,["clean","-fdx"])}async function yp(t,e){let r=t.workspacePath;await Z(r,["add","-A"]);let n=(await me(r,["write-tree"])).trim(),o=(await me(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:gr,GIT_AUTHOR_EMAIL:hr,GIT_COMMITTER_NAME:gr,GIT_COMMITTER_EMAIL:hr};return(await me(r,["commit-tree",n,"-m",e],i)).trim()}async function wp(t,e,r,n,o){try{await Z(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Jt(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 kp(t,e){return me(t.workspacePath,["diff","--binary",t.baseSha,e])}async function bp(t,e,r,n,o){await Z(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await Z(t.workspacePath,["checkout","--force",r])}async function $p(t,e,r,n,o,i){let s=t.workspacePath;await Z(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await me(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=d=>me(s,["rev-parse","-q","--verify",`${d}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await me(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Z(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(h=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(h)}`)}),await c(n)||await Z(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:gr,GIT_AUTHOR_EMAIL:hr,GIT_COMMITTER_NAME:gr,GIT_COMMITTER_EMAIL:hr},p=(await me(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),f=(await me(s,["commit-tree",p,"-p",n,"-m","delivery"],l)).trim();await Z(s,["cherry-pick","--quit"],l).catch(()=>{});let u=null;try{await Z(s,["cherry-pick","--no-commit",f],l)}catch(d){u=d instanceof Error?d.message:String(d)}let m=(await me(s,["diff","--name-only","--diff-filter=U"])).split(`
|
|
639
|
+
`).map(d=>d.trim()).filter(d=>d.length>0);if(u&&m.length===0)throw await Z(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${u}`);return m}async function es(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:gr,GIT_AUTHOR_EMAIL:hr,GIT_COMMITTER_NAME:gr,GIT_COMMITTER_EMAIL:hr};(await me(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Z(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await Z(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await Z(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await me(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
640
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await me(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function Z(t,e,r){return new Promise((n,o)=>{let i=dp("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}):
|
|
641
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function me(t,e,r){return new Promise((n,o)=>{let i=dp("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}):
|
|
642
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function vp(t,e){vo(t)&&Zi(t,{recursive:!0,force:!0}),xo(So(t),{recursive:!0}),nw(e,t,"dir")}async function xp(t,e,r){await Z(t,["worktree","prune"]).catch(()=>{}),xo(So(r),{recursive:!0}),await Z(t,["worktree","add","--detach",r,`origin/${e}`])}async function Sp(t,e,r,n="worktree",o){return r.length===0?[]:mp(e,async()=>{let i=[];for(let s of r){let a=Gt(fp(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await gp(a,s.cloneUrl,s.ref,s.defaultBranch,o)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await me(a,["rev-parse","HEAD"])).trim(),p=Gt(t,"code",s.name);n==="direct"?(vp(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${l.slice(0,10)}`)):(await xp(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 Rp(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=r;return mp(e,async()=>{let s=Gt(fp(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await gp(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=Gt(t,"context");n==="direct"?(vp(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await xp(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await me(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function Tp(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await Z(r,["add","-A",...n]).catch(()=>{});let o;try{o=await me(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
|
|
643
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=rw(Gt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var mr,gr,hr,Ip=R(()=>{"use strict";q();mr=new Map;gr="CodePipe Agent",hr="codepipe@codepartner.ee"});import{readFileSync as sw}from"node:fs";import{join as aw}from"node:path";function Cp(t){let e=aw(t,un),r;try{r=sw(e,"utf-8")}catch{throw new Rt(`BUILD produced no ${un} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(p){throw new Rt(`${un} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!n||typeof n!="object")throw new Rt(`${un} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Rt(`${un}: "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 f=p,u=typeof f.name=="string"?f.name:null,m=typeof f.exitCode=="number"?f.exitCode:null;if(u===null||m===null)return[];let d={name:u,exitCode:m};return typeof f.durationMs=="number"&&(d.durationMs=f.durationMs),[d]}),c=typeof o.logTail=="string"?cw(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(f=>f.exitCode!==0);p&&(l.failedStep=p.name)}return l}function cw(t){let e=Buffer.from(t,"utf-8");return e.length<=ts?t:`\u2026 [${e.length-ts} bytes elided] \u2026
|
|
644
|
+
`+e.subarray(e.length-ts).toString("utf-8")}var ts,Rt,un,Pp=R(()=>{"use strict";ts=8*1024,Rt=class extends Error{},un="meta/build-result.json"});import{readFileSync as lw}from"node:fs";import{join as uw}from"node:path";function jp(t){let e=uw(t,yr),r;try{r=lw(e,"utf-8")}catch{throw new at(`code review produced no ${yr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new at(`${yr} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new at(`${yr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new at(`${yr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?Ep(o.remarks,pw):"";if(!i&&s.trim().length===0)throw new at(`${yr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?Ep(o.summary,dw):"";return{approved:i,remarks:s,summary:a}}function Ep(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
|
|
645
|
+
\u2026 [${r.length-e} bytes elided]`}var pw,dw,at,yr,Ap=R(()=>{"use strict";pw=16*1024,dw=4*1024,at=class extends Error{},yr="meta/review-result.json"});import{readFileSync as fw,statSync as mw}from"node:fs";import{join as _p}from"node:path";function $w(t){return t.startsWith("meta/")||bw.has(t)}function vw(t,e,r,n){return`[codepipe] artifact omitted from upload: ${t} was ${e} bytes, exceeds the SANDBOX upload budget (per-artifact ${r} / total ${n}). The delivered code (git) and the build/review verdict are unaffected \u2014 only this display/durability copy was dropped.`}function xw(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Np(t,e,r){let n=r?.maxBytes??gw,o=r?.totalBytes??hw,i=r?.maxCount??yw,s=e.map((d,h)=>{let y=null;try{y=mw(_p(t,d)).size}catch{}return{path:d,index:h,size:y}}),a=[...s].sort((d,h)=>{let y=b=>$w(b.path)?0:1;return y(d)!==y(h)?y(d)-y(h):(d.size??0)-(h.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((d,h)=>d.index-h.index).map(d=>d.path),p=new Array(s.length),f=[],u=0;for(let d of c){let h=null;if(d.size!==null&&d.size<=n&&u+d.size<=o)try{h=fw(_p(t,d.path))}catch{}if(h!==null){u+=h.length,p[d.index]={path:d.path,contentBase64:h.toString("base64")};continue}let y=d.size===null?xw(d.path):vw(d.path,d.size,n,o),b=Buffer.from(y,"utf-8");u+=b.length,p[d.index]={path:d.path,contentBase64:b.toString("base64")},f.push({path:d.path,bytes:d.size??0})}let m=p.filter(d=>d!==void 0);if(l.length>0){let d=l.slice(0,kw),h=`# Artifacts omitted from upload
|
|
646
|
+
|
|
647
|
+
${l.length} file(s) exceeded the SANDBOX artifact count budget (${i}) and were dropped from the listing. The delivered code (git) and the build/review verdicts are unaffected. Usually this means a job left a stray tree in the workspace \u2014 throwaway copies belong in the workspace's \`scratch/\` directory, which is never uploaded.
|
|
648
|
+
|
|
649
|
+
`+d.map(y=>`- ${y}
|
|
650
|
+
`).join("")+(l.length>d.length?`
|
|
651
|
+
\u2026and ${l.length-d.length} more.
|
|
652
|
+
`:"");m.push({path:ww,contentBase64:Buffer.from(h,"utf-8").toString("base64")})}return{artifacts:m,omitted:f,dropped:l}}var gw,hw,yw,ww,kw,bw,Op=R(()=>{"use strict";gw=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),hw=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),yw=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),ww="artifacts-omitted.md",kw=500,bw=new Set(["QUESTIONS.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as Sw,mkdtempSync as Rw,readFileSync as Tw,readdirSync as Up,rmSync as Dp}from"node:fs";import{tmpdir as Iw}from"node:os";import{join as Ro,relative as Cw}from"node:path";function Lp(t){let e=Rw(Ro(Iw(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Dp(e,{recursive:!0,force:!0}),listFiles:()=>Bp(e,e),readFile:r=>Tw(Ro(e,r),"utf-8"),clean:()=>{for(let r of Up(e))Ew.has(r)||Dp(Ro(e,r),{recursive:!0,force:!0})}}}function Bp(t,e){let r=[];for(let n of Up(e)){let o=Ro(e,n),i=Sw(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Pw.has(n))continue;r.push(...Bp(t,o))}else r.push(Cw(t,o))}return r}var Pw,Ew,Mp=R(()=>{"use strict";Pw=new Set(["code","context","scratch"]),Ew=new Set(["code","context"])});import{mkdirSync as jw,readFileSync as Gp,readdirSync as Aw,writeFileSync as _w}from"node:fs";import{homedir as Nw}from"node:os";import{dirname as Ow,join as wr}from"node:path";function Uw(t){let e=Buffer.from(t,"utf-8");if(e.length<=To)return t;let r=Math.floor(To/4),n=To-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}
|
|
646
653
|
|
|
647
654
|
\u2026 [${s} bytes elided \u2014 log capped at ${To} bytes for upload] \u2026
|
|
648
655
|
|
|
649
|
-
${i}`}function
|
|
656
|
+
${i}`}function Lw(){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 pn(t={}){wo();let e=ge(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=wr(Nw(),".codepipe","logs"),i=Mn("SANDBOX_LOG",n,o);if(i.enabled){let E=new Zt(i);Gn(E),console.log(`[log] file logging \u2192 ${E.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe-sandbox v${xe} (protocol ${Fe})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let s=Zu(e.llm);console.log(`llm backend: ${s?s.name():"(none \u2014 will not claim agent jobs)"}`);let a=np();console.log(`llm retry: maxAttempts=${a.maxAttempts} backoff=${a.baseDelayMs}\u2013${a.maxDelayMs}ms budget=${a.totalBudgetMs}ms`);let c=new lr(e.hubUrl,e.token),l=!1,p=new AbortController,f=new Map,u=null,m=null,d=!1,h=()=>{let E=c.openControlSocket();return u=E,E.on("open",()=>{console.log("[ws] connected");let g={type:"sandbox_hello",platformVersion:xe,protocolVersion:Fe};E.send(JSON.stringify(g))}),E.on("message",g=>{let N=g.toString("utf-8"),$=null;try{let P=JSON.parse(N);P&&typeof P=="object"&&($=P)}catch{}if($&&$.type==="hello"){let P=$;m=Tn(P.protocolVersion);let x=m?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${P.platformVersion} (protocol ${P.protocolVersion}) \u2014 ${x}`),m&&(d=!1);return}if($&&$.type==="pause_job"){let P=typeof $.jobId=="string"?$.jobId:"",x=P?f.get(P):void 0;x?(console.warn(`[ws] pause_job ${P} \u2014 aborting agent`),x.paused=!0,x.abort.abort()):console.log(`[ws] pause_job ${P} \u2014 not a running job, ignoring`),P&&E.send(JSON.stringify({type:"job_paused",jobId:P}));return}if($&&($.type==="chat_user_message"||$.type==="chat_finalize")){let P=typeof $.jobId=="string"?$.jobId:"",x=P?f.get(P):void 0;if(x?.chatInbox)if($.type==="chat_user_message"){let j=typeof $.text=="string"?$.text:"";j.trim()&&x.chatInbox.push({kind:"user",text:j})}else x.chatInbox.finalize();else console.log(`[ws] ${String($.type)} ${P} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${N}`)}),E.on("close",(g,N)=>{console.log(`[ws] closed code=${g} reason=${N?.toString()||""}`),u===E&&(u=null),!l&&setTimeout(h,2e3)}),E.on("error",g=>console.warn(`[ws] error: ${g.message}`)),E},y=h(),b=async E=>{for(;!l;){if(m===!1){d||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${xe}, protocol ${Fe}) \u2014 not claiming jobs until versions align.`),d=!0),await new Promise(g=>setTimeout(g,5e3));continue}try{let g=await c.claim(p.signal,E);if(g.status===204)continue;if(g.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(!g.ok){console.warn(`[claim:${E}] ${g.status} \u2014 backoff 5s`),await new Promise($=>setTimeout($,5e3));continue}let N=await g.json();await w(c,N)}catch(g){if(p.signal.aborted)break;let N=g instanceof Error?g.message:String(g);console.warn(`[claim:${E}] error: ${N} \u2014 backoff 5s`),await new Promise($=>setTimeout($,5e3))}}};async function w(E,g){let N={abort:new AbortController,paused:!1};g.role==="chat"&&(N.chatInbox=Lw()),f.set(g.jobId,N);let $=!1,P=null,x=null,j=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),B=async()=>{try{await E.heartbeat(g.jobId)==="claim_lost"&&($=!0,console.warn(`[job] ${g.jobId} claim lost \u2014 HUB sweeper took it`))}catch(U){let Ae=U instanceof Error?U.message:String(U);console.warn(`[job] ${g.jobId} heartbeat error: ${Ae}`)}};B();let v=setInterval(()=>{B()},j),S=new Date().toISOString();console.log(`[job] ${g.jobId} claimed \u2014 role=${g.role} task=${g.taskId} phase=${g.phase}`),console.log(`[job] ${g.jobId} prompt (${g.prompt.length} chars):`),console.log(C(g.prompt," \u2502 "));let H=[],te=null,xn=400,Lo=25,A=500,ae=()=>{if(te&&(clearTimeout(te),te=null),H.length===0)return;let U=H.splice(0,H.length),Ae=u;if(!Ae||Ae.readyState!==Ae.OPEN)return;let Xe={type:"agent_activity",jobId:g.jobId,taskId:g.taskId,projectId:g.projectId,role:g.role,phase:g.phase,events:U};try{Ae.send(JSON.stringify(Xe))}catch{}},je=U=>{H.push(U),H.length>A&&H.shift(),H.length>=Lo?ae():te||(te=setTimeout(ae,xn))},Me=g.role==="analysis"&&g.taskId.startsWith("draft::")?g.taskId.slice(7):null,lt=new Set,ut=null;try{if(!s){$||await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:S,finishedAt:new Date().toISOString()});return}let U=Lp(g.jobId);console.log(`[job] ${g.jobId} workspace=${U.dir}`);let Ae=k(g,r);P=Ae.gitCreds,x=Ae.contextGitCreds;let Xe=P?.env,Rs=Ae.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Ae.claudeOauthToken}:void 0,Qe=[],_r=null,Bo=null;try{let D="worktree";Qe=await Sp(U.dir,g.projectId,g.projectRepos,D,Xe);let L=await Rp(U.dir,g.projectId,g.contextRepo,D,Xe);Bo=L,_r=L?.workspacePath??null}catch(D){let L=D instanceof Error?D.message:String(D);console.warn(`[job] ${g.jobId} materialize failed: ${L}`),$||await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${L}`},startedAt:S,finishedAt:new Date().toISOString()}),U.dispose();return}let Ts=async()=>{if(!g.deliveries||g.deliveries.length===0)return[];let D=g.contextRepo?.cloneUrl;if(!D||!Xe)throw new Error(D?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let L=[];for(let V of g.deliveries){let Y=Qe.find(ce=>ce.name===V.name);if(Y){if(g.role==="implement"&&V.baseSha&&V.baseSha!==Y.baseSha){let ce=await $p(Y,V.deliveryRef,V.deliverySha,V.baseSha,D,Xe);console.log(`[job] ${g.jobId} ${Y.name}: base moved ${V.baseSha.slice(0,10)} \u2192 ${Y.baseSha.slice(0,10)} \u2014 re-applied delivery ${V.deliverySha.slice(0,10)} (${ce.length} conflicted file(s))`),ce.length>0&&L.push(`- **${Y.name}**:`,...ce.map(Nr=>` - \`${Nr}\``));continue}await bp(Y,V.deliveryRef,V.deliverySha,D,Xe),console.log(`[job] ${g.jobId} ${Y.name}: checked out delivery ${V.deliverySha.slice(0,10)} for ${g.role}`)}}return L},Mo=[];if(g.role==="build"||g.role==="implement"||g.role==="code-review")try{Mo=await Ts()}catch(D){let L=D instanceof Error?D.message:String(D);console.warn(`[job] ${g.jobId} delivery checkout failed: ${L}`),$||await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${L}`},startedAt:S,finishedAt:new Date().toISOString()}),U.dispose();return}let Go=g.role==="resolve-conflict"?g.metadata?.taskBranchByRepo??{}:{},Is="";if(g.role==="resolve-conflict"){if(!Qe.some(D=>Go[D.name])){let D="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] ${g.jobId} ${D}`),$||await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:D},startedAt:S,finishedAt:new Date().toISOString()}),U.dispose();return}try{let D=[];for(let L of Qe){let V=Go[L.name];if(!V)continue;let Y=await es(L,V,Xe);console.log(`[job] ${g.jobId} ${L.name}: merged ${V} into ${L.ref} \u2014 ${Y.length} conflicted file(s)`),Y.length>0?D.push(`- **${L.name}**:`,...Y.map(ce=>` - \`${ce}\``)):D.push(`- **${L.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Is=`
|
|
650
657
|
|
|
651
658
|
## Conflicts to resolve
|
|
652
659
|
|
|
653
660
|
`+(D.length>0?D.join(`
|
|
654
661
|
`):"(no task branches to merge)")+`
|
|
655
|
-
`}catch(D){let L=D instanceof Error?D.message:String(D);console.warn(`[job] ${g.jobId} conflict merge failed: ${L}`)
|
|
662
|
+
`}catch(D){let L=D instanceof Error?D.message:String(D);console.warn(`[job] ${g.jobId} conflict merge failed: ${L}`),$||await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${L}`},startedAt:S,finishedAt:new Date().toISOString()}),U.dispose();return}}let kf=Mo.length>0?`
|
|
656
663
|
|
|
657
664
|
## Base branch moved \u2014 conflicts to resolve
|
|
658
665
|
|
|
@@ -660,97 +667,97 @@ The base branch advanced since the previous iteration; its delivery was re-appli
|
|
|
660
667
|
|
|
661
668
|
`+Mo.join(`
|
|
662
669
|
`)+`
|
|
663
|
-
`:"",bf=T(G(g.prompt,Qe,_r),_r,g.taskId)+Is+kf,Fo=[...Qe.map(D=>D.workspacePath),..._r?[_r]:[]];Fo.length>0&&console.log(`[job] ${g.jobId} --add-dir: ${Fo.join(", ")}`),Me&&(ut=setInterval(()=>{let L=u;if(!L||L.readyState!==L.OPEN)return;let V;try{V=
|
|
670
|
+
`:"",bf=T(G(g.prompt,Qe,_r),_r,g.taskId)+Is+kf,Fo=[...Qe.map(D=>D.workspacePath),..._r?[_r]:[]];Fo.length>0&&console.log(`[job] ${g.jobId} --add-dir: ${Fo.join(", ")}`),Me&&(ut=setInterval(()=>{let L=u;if(!L||L.readyState!==L.OPEN)return;let V;try{V=Aw(wr(U.dir,"drafts")).filter(Y=>Y.endsWith(".json")).sort()}catch{return}for(let Y of V){if(lt.has(Y))continue;if(lt.size>=va)break;let ce;try{let _e=JSON.parse(Gp(wr(U.dir,"drafts",Y),"utf-8")),Yt=typeof _e.localRef=="string"?_e.localRef:"",Sn=typeof _e.title=="string"?_e.title:"",Ho=typeof _e.body=="string"?_e.body:"";if(!Yt||!Sn)continue;ce={localRef:Yt,title:Sn,body:Ho,..._e.isEpic===!0?{isEpic:!0}:{},...Array.isArray(_e.links)?{links:_e.links}:{}}}catch{continue}lt.add(Y);let Nr={type:"child_draft",jobId:g.jobId,projectId:g.projectId,draftId:Me,child:ce};try{L.send(JSON.stringify(Nr))}catch{}}},1500));try{let D={workspaceDir:U.dir,role:g.role,prompt:bf,addDirs:Fo,metadata:g.metadata??{},...g.model?{model:g.model}:{},...Rs?{env:Rs}:{},signal:N.abort.signal,onActivity:je},L=N.chatInbox?await s.run({...D,interactive:{inbox:N.chatInbox.iterable}}):await ip(s,D,{jobId:g.jobId,policy:a,onBeforeRetry:async()=>{U.clean();for(let Q of Qe)try{await hp(Q);let le=Go[Q.name];g.role==="resolve-conflict"&&le&&await es(Q,le,Xe)}catch(le){let Or=le instanceof Error?le.message:String(le);console.warn(`[job] ${g.jobId} worktree reset failed (${Q.name}): ${Or}`)}try{await Ts()}catch(Q){let le=Q instanceof Error?Q.message:String(Q);console.warn(`[job] ${g.jobId} delivery re-checkout failed: ${le}`)}},aborted:()=>$||N.paused}),V=[];if(Dw.has(g.role)&&Qe.length>0){let Q=g.metadata??{},le=typeof Q.commitMessage=="string"?Q.commitMessage:`${g.taskId}: changes`,Or=g.contextRepo?.cloneUrl,Ps=x?.env;if(!Or||!Ps)throw new Error("delivery requested but "+(Or?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let $f=g.taskId.includes(":")?g.taskId.slice(g.taskId.indexOf(":")+1):g.taskId;for(let Ze of Qe){let Dr=await yp(Ze,le);if(!Dr){console.log(`[job] ${g.jobId} ${Ze.name}: no changes \u2014 no delivery`);continue}let Ko=`codepipe/deliveries/${$f}/${g.jobId}/${Ze.name}`;await wp(Ze,Dr,Ko,Or,Ps),V.push({name:Ze.name,deliveryRef:Ko,deliverySha:Dr,baseSha:Ze.baseSha}),console.log(`[job] ${g.jobId} ${Ze.name}: delivered ${Dr.slice(0,10)} \u2192 ${Ko}`);let Es=await kp(Ze,Dr);if(Es.trim().length>0){let vf=wr("display",`${Ze.name}.diff`),js=wr(U.dir,vf);jw(Ow(js),{recursive:!0}),_w(js,Es)}}}if(g.role==="resolve-conflict"&&V.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 Y;g.role==="build"&&(Y=Cp(U.dir),console.log(`[job] ${g.jobId} build verdict: ok=${Y.ok}`+(Y.failedStep?` failedStep=${Y.failedStep}`:"")));let ce;g.role==="code-review"&&(ce=jp(U.dir),console.log(`[job] ${g.jobId} review verdict: approved=${ce.approved}`));let Nr=L.artifactPaths.length>0?L.artifactPaths:U.listFiles(),_e=Array.from(new Set(Nr)),Yt;if(Bo)try{let Q=g.role==="index"?["adr/SOURCES.md"]:g.role==="backfill"?["adr"]:[],le=await Tp(Bo,Q);le.length>0&&(Yt=le,console.log(`[job] ${g.jobId} captured ${le.length} knowledge file(s) for Context Repo`))}catch(Q){let le=Q instanceof Error?Q.message:String(Q);console.warn(`[job] ${g.jobId} knowledge capture failed (non-fatal): ${le}`)}let{artifacts:Sn,omitted:Ho,dropped:Cs}=Np(U.dir,_e);for(let Q of Ho)console.warn(`[job] ${g.jobId} artifact ${Q.path} (${Q.bytes} bytes) exceeded upload budget \u2014 content omitted`);Cs.length>0&&console.warn(`[job] ${g.jobId} artifact listing truncated: ${Cs.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Rn={jobId:g.jobId,status:"succeeded",artifacts:Sn,...Yt?{contextWrites:Yt}:{},...V.length>0?{deliveries:V}:{},log:Uw(L.log),startedAt:S,finishedAt:new Date().toISOString(),usage:L.usage,...L.rateLimit?{rateLimit:L.rateLimit}:{},...Y?{build:Y}:{},...ce?{review:ce}:{}};if($||N.paused)console.warn(`[job] ${g.jobId} skipping result upload \u2014 ${N.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await E.submitResult(Rn),console.log(`[job] ${g.jobId} done \u2014 uploaded ${Rn.artifacts.length} artifact(s):`);for(let Q of Rn.artifacts){let le=Buffer.from(Q.contentBase64,"base64").length;console.log(` \xB7 ${Q.path} (${le} bytes)`)}Rn.artifacts.length===0&&console.warn(`[job] ${g.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(D){let L=D instanceof Error?D.message:String(D);if(N.paused)console.log(`[job] ${g.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if($)console.warn(`[job] ${g.jobId} failed after claim lost (${L}) \u2014 skipping result upload`);else{let V=op(D),Y=D instanceof Rt,ce=D instanceof at;console.warn(V?`[job] ${g.jobId} failed: ${L} (Claude auth \u2014 token invalid/expired)`:Y?`[job] ${g.jobId} failed: ${L} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:ce?`[job] ${g.jobId} failed: ${L} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${g.jobId} failed: ${L}`),await E.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:L},startedAt:S,finishedAt:new Date().toISOString(),...V?{authError:!0}:{},...Y?{buildInconclusive:!0}:{},...ce?{reviewInconclusive:!0}:{}})}}finally{U.dispose()}}finally{clearInterval(v),ut&&clearInterval(ut),ae(),N.chatInbox?.close(),f.delete(g.jobId),P?.cleanup(),x?.cleanup()}}function k(E,g){if(!E.credBundle)return{gitCreds:null,contextGitCreds:null};if(!g)return console.warn(`[job] ${E.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let N;try{N=JSON.parse(ir(g,E.credBundle).toString("utf-8"))}catch(j){return console.warn(`[job] ${E.jobId} failed to open credBundle: ${j instanceof Error?j.message:String(j)}`),{gitCreds:null,contextGitCreds:null}}let $=Qi(N);$&&console.log(`[job] ${E.jobId} cred bundle opened \u2014 git creds configured`);let P=lp(N,E.contextRepo.cloneUrl),x={gitCreds:$,contextGitCreds:P};return N.claudeOauthToken&&(x.claudeOauthToken=N.claudeOauthToken),x}function C(E,g){return E.split(`
|
|
664
671
|
`).map(N=>g+N).join(`
|
|
665
|
-
`)}function G(E,g,N){let
|
|
666
|
-
[${E}] shutting down`),p.abort();let g=[...d.keys()];for(let P of d.values())P.abort.abort();let N=new AbortController,b=setTimeout(()=>N.abort(),3e3);(async()=>(await Promise.all(g.map(async P=>{try{await c.releaseJob(P,`sandbox ${E}`,N.signal),console.log(`[${E}] released job ${P}`)}catch(x){let j=x instanceof Error?x.message:String(x);console.warn(`[${E}] release failed: ${j} (sweeper will reclaim)`)}})),clearTimeout(b),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>_("SIGINT")),process.on("SIGTERM",()=>_("SIGTERM"));let F=[$("implementation")];e.planningLane!==!1?F.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(F)}var To,jw,Fp=R(()=>{"use strict";q();Ce();ri();Zu();ip();ko();lp();qi();Tp();Cp();jp();Np();Mp();To=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),jw=new Set(["implement","resolve-conflict"])});var kr=R(()=>{"use strict";Fu();Fp();ko()});async function $r(t,e,r){return e.host==="github"?Ow(t,e,r):e.host==="gitlab"?Fw(t,e,r):Kw(t,e,r)}async function Kp(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 Wp(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 Tt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Yp(e.gitlabToken,t):o}}return e.bitbucket?(await br(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await qp(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 Wp(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 Yp(t,e){let r=!1;try{r=(await Tt(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function qp(t,e){let r=!1;try{r=(await br(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`}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(Nw+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 Ow(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 Dw(n,e,r),i=await Lw(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=or(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Bw(n,o.owner,o.name,a.path,i)||await Mw(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 Dw(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 Wp(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Uw(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 Uw(t,e){let{status:r,data:n}=await It(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Lw(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 Bw(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 Mw(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)}async function Tt(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(Gw+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 Fw(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 Tt(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 Yp(n,e)} (attach joins an existing Context Repo and never creates one)`);let d=await Tt(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 Tt(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 m=await Tt(n,"POST","/projects",u);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=or(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let d=1;;d++){let m=(await Tt(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${d}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.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 Tt(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}}async function br(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(Hw+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 Kw(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 br(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 qp(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 br(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=or(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let d of c)(await br(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 m of l)d.set(m.path,m.content);if((await br(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 Nw,Gw,Hw,Io=R(()=>{"use strict";Ut();Nw="https://api.github.com";Gw="https://gitlab.com/api/v4";Hw="https://api.bitbucket.org/2.0"});function Ee(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=Ww[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}var Ww,Co=R(()=>{"use strict";Ww={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as Yw}from"node:crypto";import{existsSync as Vp,mkdirSync as qw,readFileSync as Jp,readdirSync as Vw,rmSync as Po,writeFileSync as Jw}from"node:fs";import{homedir as zw}from"node:os";import{dirname as Xw,join as rs}from"node:path";function zp(){return rs(zw(),".codepipe","init-drafts")}function ns(t){let e=Yw("sha256").update(t).digest("hex").slice(0,16);return rs(zp(),`${e}.json`)}function Xp(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Qw)}function Qp(t){let e=ns(t);if(!Vp(e))return null;try{let r=JSON.parse(Jp(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Xp(r.savedAt)?(Po(e,{force:!0}),null):r}catch{return null}}function os(t){Po(ns(t),{force:!0})}function Zp(){let t=zp();if(Vp(t))for(let e of Vw(t)){let r=rs(t,e);try{let n=JSON.parse(Jp(r,"utf-8"));Xp(n.savedAt)&&Po(r,{force:!0})}catch{Po(r,{force:!0})}}}var Qw,vr,ed=R(()=>{"use strict";Qw=24*60*60*1e3;vr=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(){os(this.cwd)}persist(){let e=ns(this.cwd);qw(Xw(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Jw(e,JSON.stringify(r,null,2)+`
|
|
667
|
-
`,{mode:384})}}});function td(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 rd(){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 nd(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}}var od=R(()=>{"use strict"});import{existsSync as
|
|
668
|
-
`).map(n=>n.trim()).filter(Boolean);return id(r)}catch{return!1}}async function
|
|
669
|
-
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`),
|
|
670
|
-
`))
|
|
671
|
-
`)};m.stdout?.on("data",
|
|
672
|
-
[up] ${m} \u2014 stopping both roles`);for(let{child:
|
|
672
|
+
`)}function G(E,g,N){let $=g[0]?.workspacePath??"";return E.replace(/\{\{codeDir\}\}/g,$).replace(/\{\{codeRoot\}\}/g,$?$.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,N??"")}function T(E,g,N){let $=E,P=N.includes("::")?"":N.split(":",2)[1]??"",x=j=>{if(!g||!P)return"";try{return Gp(wr(g,"tasks",P,j),"utf-8").trim()}catch{return""}};if($.includes("{{solutionMd}}")){let j=x("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";$=$.replace(/\{\{solutionMd\}\}/g,()=>j)}if($.includes("{{taskDescription}}")){let j=x("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";$=$.replace(/\{\{taskDescription\}\}/g,()=>j)}return $}let _=E=>{if(l)return;l=!0,console.log(`
|
|
673
|
+
[${E}] shutting down`),p.abort();let g=[...f.keys()];for(let P of f.values())P.abort.abort();let N=new AbortController,$=setTimeout(()=>N.abort(),3e3);(async()=>(await Promise.all(g.map(async P=>{try{await c.releaseJob(P,`sandbox ${E}`,N.signal),console.log(`[${E}] released job ${P}`)}catch(x){let j=x instanceof Error?x.message:String(x);console.warn(`[${E}] release failed: ${j} (sweeper will reclaim)`)}})),clearTimeout($),y.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>_("SIGINT")),process.on("SIGTERM",()=>_("SIGTERM"));let F=[b("implementation")];e.planningLane!==!1?F.push(b("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(F)}var To,Dw,Fp=R(()=>{"use strict";q();Ce();ri();ep();sp();ko();up();qi();Ip();Pp();Ap();Op();Mp();To=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Dw=new Set(["implement","resolve-conflict"])});var kr=R(()=>{"use strict";Hu();Fp();ko()});async function $r(t,e,r){return e.host==="github"?Mw(t,e,r):e.host==="gitlab"?qw(t,e,r):Jw(t,e,r)}async function Kp(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 Wp(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 Tt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Yp(e.gitlabToken,t):o}}return e.bitbucket?(await br(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await qp(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 Wp(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 Yp(t,e){let r=!1;try{r=(await Tt(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function qp(t,e){let r=!1;try{r=(await br(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`}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(Bw+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 Mw(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 Gw(n,e,r),i=await Hw(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=or(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Kw(n,o.owner,o.name,a.path,i)||await Ww(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 Gw(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 Wp(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Fw(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 Fw(t,e){let{status:r,data:n}=await It(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Hw(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 Kw(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 Ww(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)}async function Tt(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(Yw+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 qw(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 Tt(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 Yp(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Tt(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(f.data?.username!==e.owner){let d=await Tt(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(d.status===404||!d.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);u.namespace_id=d.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await Tt(n,"POST","/projects",u);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=or(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let m=(await Tt(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let d of m)l.add(d.path);if(m.length<100)break}let p=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return p.length>0?await Tt(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}}async function br(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(Vw+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 Jw(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 br(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 qp(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let f=await br(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=f.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=or(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await br(n,"GET",`${o}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let m of l)f.set(m.path,m.content);if((await br(n,"POST",`${o}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let p=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:p??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Bw,Yw,Vw,Io=R(()=>{"use strict";Ut();Bw="https://api.github.com";Yw="https://gitlab.com/api/v4";Vw="https://api.bitbucket.org/2.0"});function Ee(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=zw[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}var zw,Co=R(()=>{"use strict";zw={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as Xw}from"node:crypto";import{existsSync as Vp,mkdirSync as Qw,readFileSync as Jp,readdirSync as Zw,rmSync as Po,writeFileSync as ek}from"node:fs";import{homedir as tk}from"node:os";import{dirname as rk,join as rs}from"node:path";function zp(){return rs(tk(),".codepipe","init-drafts")}function ns(t){let e=Xw("sha256").update(t).digest("hex").slice(0,16);return rs(zp(),`${e}.json`)}function Xp(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=nk)}function Qp(t){let e=ns(t);if(!Vp(e))return null;try{let r=JSON.parse(Jp(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Xp(r.savedAt)?(Po(e,{force:!0}),null):r}catch{return null}}function os(t){Po(ns(t),{force:!0})}function Zp(){let t=zp();if(Vp(t))for(let e of Zw(t)){let r=rs(t,e);try{let n=JSON.parse(Jp(r,"utf-8"));Xp(n.savedAt)&&Po(r,{force:!0})}catch{Po(r,{force:!0})}}}var nk,vr,ed=R(()=>{"use strict";nk=24*60*60*1e3;vr=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(){os(this.cwd)}persist(){let e=ns(this.cwd);Qw(rk(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};ek(e,JSON.stringify(r,null,2)+`
|
|
674
|
+
`,{mode:384})}}});function td(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 rd(){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 nd(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}}var od=R(()=>{"use strict"});import{existsSync as ok}from"node:fs";import{join as ik}from"node:path";import{simpleGit as sk}from"simple-git";function uk(t){let e=t.split("/");return e[e.length-1]??t}function id(t){if(t.filter(r=>!ck.test(uk(r))).length>ak)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(lk.has(n))return!0}return!1}async function pk(t){try{let r=(await sk(t).raw(["ls-files"])).split(`
|
|
675
|
+
`).map(n=>n.trim()).filter(Boolean);return id(r)}catch{return!1}}async function dk(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)?id(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function sd(t,e){for(let r of t)try{let n=e.localRoot!=null?ik(e.localRoot,r.mountAs??r.name):null;if(n&&ok(n)?await pk(n):await dk(r,e.tokens))return!0}catch{}return!1}var ak,ck,lk,ad=R(()=>{"use strict";ak=3,ck=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,lk=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as cd}from"node:fs";import{join as ld}from"node:path";import{simpleGit as ud}from"simple-git";async function fn(t,e,r={}){let n=r.log??fk,o=[];for(let i of e){let s=ld(t,i.mountAs),a=Ta(i);if(!cd(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 ud().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(p){let f=dn(p instanceof Error?p.message:String(p));n.warn(`clone failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!cd(ld(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=ud(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!mk(l,a)){n.warn(`${i.mountAs}/ origin (${dn(l)||"none"}) != expected (${dn(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:dn(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 f=dn(p instanceof Error?p.message:String(p));n.warn(`fetch failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}}return o}function mk(t,e){return pd(t)===pd(e)}function pd(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function dn(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function dd(t={}){let e=Re();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 fn(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 fk,Eo=R(()=>{"use strict";tt();fk={info:t=>console.log(t),warn:t=>console.warn(t)}});var md={};Sf(md,{upCommand:()=>is});import{spawn as gk}from"node:child_process";import{existsSync as fd}from"node:fs";import{homedir as hk,hostname as yk}from"node:os";import{join as jo}from"node:path";async function wk(t,e,r){let n=ge(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Be(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 Jl(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 ${Be(e)} still holds its token.
|
|
676
|
+
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`),Ka(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function kk(t,e,r){let n=ge(e)!==null;if(!await wk(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 po(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof O&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof O&&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 O?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 Bt({hub:t.hubUrl,token:o,name:r.name??`${yk()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function bk(t,e){let r=ge(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=ye(r.sealPublicKey);if(!M(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Ln(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 $k(t,e){let r=process.cwd(),n=jo(r,We);if(On(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(fd(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 J(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 as(r);if(!Ra(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=M(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await yo({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=jo(hk(),".codepipe",e?jo("profiles",e,"context-config"):"context-config");if(Kn(c.contextDir,l,a),!fd(jo(c.contextDir,"project.yaml"))){rr(c.contextDir);let p={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Fr(c.contextDir,Ve(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 is(t){let{cfg:e,profile:r}=Un(t.profile);await $k(e,r),await kk(e,r,t),bk(e.projectId,r);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,d)=>{let h=y=>b=>{for(let w of b.toString("utf-8").split(`
|
|
677
|
+
`))w.length>0&&y.write(`${d} ${w}
|
|
678
|
+
`)};m.stdout?.on("data",h(process.stdout)),m.stderr?.on("data",h(process.stderr))},i=(m,d)=>{let h=gk(process.execPath,[n,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return o(h,m),h};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,p=m=>{if(!l){l=!0,console.log(`
|
|
679
|
+
[up] ${m} \u2014 stopping both roles`);for(let{child:d}of c)d.exitCode===null&&d.kill(m);setTimeout(()=>{for(let{name:d,child:h}of c)h.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),h.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM"));let f=c.map(({name:m,child:d})=>new Promise(h=>{d.on("exit",(y,b)=>h({name:m,code:y??(b?1:0)}))})),u=await Promise.race(f);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),p("SIGTERM")),await Promise.all(f),process.exit(u.code)}var ss=R(()=>{"use strict";Ce();kr();ke();nt();Ki();Ut();fe();re();tt();mn()});import{spawn as vk}from"node:child_process";import{existsSync as xr,mkdirSync as hd,readFileSync as yd,readdirSync as xk,writeFileSync as wd}from"node:fs";import{join as Ft,resolve as kd}from"node:path";import{setTimeout as cs}from"node:timers/promises";import{cancel as Sk,confirm as Sr,intro as bd,isCancel as Ao,log as I,outro as ls,password as Rr,select as ct,spinner as ps,text as oe}from"@clack/prompts";import{simpleGit as No}from"simple-git";function ee(t){Sk(t),process.exit(1)}function be(t){return Ao(t)&&ee("aborted"),t}function z(t){return Ao(t)&&ee("aborted"),typeof t=="string"?t:""}async function $d(t={}){bd("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Zp();let r=Qp(e),n,o=!1;r&&Object.keys(r.answers).length>0?be(await Sr({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(I.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new vr(e,r),o=!0):(os(e),n=new vr(e)):n=new vr(e);let i=t.force===!0?null:await as(e),s=await n.ask("target",async()=>be(await ct({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?I.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||xd(e,t.force===!0));let c=await n.ask("hubUrl",async()=>z(await oe({message:"HUB URL",placeholder:Ge,initialValue:K("HUB_URL")??Ge,validate:A=>A.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Tr()),{cliToken:p,accountEmail:f}=await n.ask("bootstrap",()=>Ir(c,l)),u=null;s==="farm"&&(u=await Rk(c,p));let m=a?Ik(a.parsed.repoName):"",d=await n.ask("projectId",async()=>z(await oe({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:A=>At.test(A.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await n.ask("projectName",async()=>z(await oe({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:A=>A.trim().length>0?void 0:"required"})).trim()),y=await n.ask("automationLevel",async()=>be(await ct({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("trackerProvider",async()=>be(await ct({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),w=b==="internal",k=null,C,G=!0;if(w){let A,ae=ps();ae.start("checking task-key prefixes on your account\u2026");try{A=await zl(c,p,{excludeProjectId:d}),ae.stop("prefixes checked")}catch{ae.stop("could not reach the HUB",1),ee("Could not verify the task-key prefix against your account \u2014 the HUB is unreachable right now. Prefix uniqueness is required, so init can't continue. Check your connection and re-run `codepipe init` later.")}let je=ha(ga(h),A);C=await n.ask("trackerPrefix",async()=>z(await oe({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:je,initialValue:je,validate:Me=>{let lt=Me.trim();if(!Vt.test(lt))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(A.has(lt.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else k=await n.ask("youtrack",()=>jd()),C=await n.ask("youtrackProjectKey",async()=>z(await oe({message:"YouTrack project key",placeholder:"DEV",validate:A=>A.trim().length>0?void 0:"required"})).trim()),G=await n.ask("youtrackWrites",async()=>be(await Sr({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let T=n.get("tokens")??{},_=()=>n.set("tokens",T),F=await n.ask("repos",()=>Ek(T,l,a,{onCred:_,initial:n.get("reposPartial")??[],onProgress:A=>n.set("reposPartial",A)}));n.delete("reposPartial");let E=await jk(await n.ask("contextRepo",()=>Cd(d,F,T,l)),d,F,T,l,_,A=>n.set("contextRepo",A)),{spec:g,mode:N}=E,$;w||(I.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),$=await n.ask("assigneeLogin",async()=>z(await oe({message:"your YouTrack login (the assignee value)",...k?.login?{initialValue:k.login}:{},validate:A=>A.trim().length>0?void 0:"required"})).trim()));let P=await n.ask("claudeToken",()=>Lk(s==="farm")),x={projectId:d,name:h,automationLevel:y,repos:F,trackerProvider:b,youtrackProjectKey:C};I.step(`${N==="attach"?"attaching to":"provisioning"} Context Repo ${g.owner}/${g.name} (${g.host})\u2026`);let j;try{j=await $r(x,g,{...Pd(T),youtrackWrites:G,...k?{trackerUrl:k.url}:{},mode:N,log:{info:A=>I.message(A),warn:A=>I.warn(A)}})}catch(A){ee(`Context Repo provisioning failed: ${A instanceof Error?A.message:String(A)}`)}x.contextRepo=j,I.success(`Context Repo ready: ${j.owner}/${j.name}@${j.branch}`),I.step(`registering project on ${c}\u2026`);let B;try{B=await vt(c,p,x)}catch(A){if(A instanceof O&&A.status===409){I.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{B=await J(c,p,d)}catch(ae){throw ae instanceof O&&ee(`HUB \u2192 ${ae.status} ${ae.message}`),ae}}else if(A instanceof O&&A.status===401)n.delete("cliToken"),ee("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(A instanceof O)ee(`HUB \u2192 ${A.status} ${A.message}`);else throw A}let v=B.contextRepo??j;I.success(`project ${B.projectId} ready (${B.provisioningStatus})`);let S=await Dk(v),H=k?{url:k.url,token:k.token}:void 0;if(s==="farm"){let A=u,ae={...T,...S?{contextWrite:S}:{},...P?{claude:{oauthToken:P}}:{},...H?{youtrack:H}:{}},je=T.github?.token;if(v.host==="github"&&je)try{let U=Cu(`devpipe-${d}`);await Pu(v,je,U.publicKey,`devpipe-${d}`),ae.contextSsh={privateKey:U.privateKey},I.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(U){I.warn(`could not set up Context Repo SSH deploy key (${U instanceof Error?U.message:String(U)}); the farm will fall back to the token path.`)}let Me={projectId:d,config:{hubUrl:c,cliToken:p,projectId:d},secrets:ae,contextRepo:v,projectConfig:Ve(x,G,k?.url,$||void 0)},lt=it(A.farm.publicKey,JSON.stringify(Me));I.step(`handing project ${d} to farm ${A.farm.name}\u2026`);let ut;try{ut=await uo(c,p,A.farm.farmId,{projectId:d,sealedBundle:lt})}catch(U){throw U instanceof O&&ee(U.status===409?`farm ${A.farm.name} is offline \u2014 start it and re-run.`:U.status===504?`farm ${A.farm.name} did not respond in time.`:`HUB \u2192 ${U.status} ${U.message}`),U}ut.ok||ee(`farm rejected provisioning: ${ut.error??"unknown error"}`),await us(c,p,d,v,je,B.repos,null,T),n.clear(),ls(`done. project ${d} is now hosted on farm ${A.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}Ed(T),await Rd(e,v.cloneUrl,v.branch),Id(e),a&&await Pk(e);{let A=Ft(e,We);rr(A);let ae=Ve(x,G,k?.url,$||void 0),je=Fr(A,ae);je.length>0&&I.success(`local project config \u2192 .codepipe/{${je.join(", ")}}`),Ot(d,ae,{info:Me=>I.message(Me),warn:Me=>I.warn(Me)})}await Td(e,B.repos);let te={hubUrl:c,cliToken:p,projectId:d,...T,...S?{contextWrite:S}:{},...P?{claude:{oauthToken:P}}:{},...H?{youtrack:H}:{}};X(te),rt({hubUrl:c,cliToken:p,projectId:d,accountEmail:f},d),I.success(`secrets \u2192 ${Ye(d)}`),await us(c,p,d,v,T.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,B.repos,e,T),n.clear();let xn=`${c}/?project=${encodeURIComponent(d)}`;Sd(xn),ls(`done. your project on the dashboard (sign in there to work with it):
|
|
673
680
|
${xn}
|
|
674
|
-
starting \`codepipe up\` \u2014 the CLI daemon + an agent worker. Ctrl+C stops both; start again anytime with \`codepipe up\` from this folder.`);let{upCommand:Lo}=await Promise.resolve().then(()=>(ss(),md));await Lo({profile:void 0})}async function us(t,e,r,n,o,i=[],s=null,a={}){let c=await nd(n,o);if(!c){let
|
|
681
|
+
starting \`codepipe up\` \u2014 the CLI daemon + an agent worker. Ctrl+C stops both; start again anytime with \`codepipe up\` from this folder.`);let{upCommand:Lo}=await Promise.resolve().then(()=>(ss(),md));await Lo({profile:void 0})}async function us(t,e,r,n,o,i=[],s=null,a={}){let c=await nd(n,o);if(!c){let f=!1;try{f=await sd(i,{localRoot:s,tokens:a})}catch{f=!1}if(f){let u=rd(),m=await ct({message:u.message,options:u.options,initialValue:u.initialValue});if(!Ao(m)&&m===u.proceedValue)try{let{jobId:d}=await on(t,e,r,{reindex:!1,backfill:!0});I.success(`retrospective architecture analysis queued (job ${d}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(d){I.warn(`could not start the retrospective analysis: ${d instanceof Error?d.message:String(d)}. Registration is not affected.`)}}}let l=td(c),p=await ct({message:l.message,options:l.options,initialValue:l.initialValue});if(!(Ao(p)||p!==l.proceedValue))try{let{jobId:f}=await on(t,e,r,{reindex:l.reindex});I.success(`indexing queued (job ${f}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(f){I.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function Rk(t,e){let r;try{r=await Yl(t,e)}catch(c){throw c instanceof O&&ee(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&ee("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 ct({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=co(i.farmId,i.publicKey)}catch(c){ee(c instanceof Error?c.message:String(c))}return be(await Sr({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
675
682
|
${s}
|
|
676
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||ee("farm fingerprint not confirmed \u2014 aborting."),ao(i.farmId,s),{farm:i,fingerprint:s}}async function vd(t){bd(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();xd(e,t.force===!0);let r=z(await oe({message:"HUB URL",initialValue:K("HUB_URL")??Ge,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Tr(),{cliToken:o,accountEmail:i}=await Ir(r,n);I.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await J(r,o,t.projectId)}catch(u){throw u instanceof O&&ee(`HUB \u2192 ${u.status} ${u.message}`),u}s.contextRepo||ee(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await jd(),l={},p=new Set(s.repos.map(u=>u.host));p.add(s.contextRepo.host);for(let u of p){let m=s.repos.find(
|
|
683
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||ee("farm fingerprint not confirmed \u2014 aborting."),ao(i.farmId,s),{farm:i,fingerprint:s}}async function vd(t){bd(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();xd(e,t.force===!0);let r=z(await oe({message:"HUB URL",initialValue:K("HUB_URL")??Ge,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Tr(),{cliToken:o,accountEmail:i}=await Ir(r,n);I.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await J(r,o,t.projectId)}catch(u){throw u instanceof O&&ee(`HUB \u2192 ${u.status} ${u.message}`),u}s.contextRepo||ee(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await jd(),l={},p=new Set(s.repos.map(u=>u.host));p.add(s.contextRepo.host);for(let u of p){let m=s.repos.find(d=>d.host===u);await _o(u,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}Ed(l),await Rd(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Id(e);{let u=Ft(e,We);rr(u);let m={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},d=Ve(m,!0,c?.url),h=Fr(u,d);h.length>0&&I.success(`local project config \u2192 .codepipe/{${h.join(", ")}} (defaults \u2014 review and adjust)`),Ot(t.projectId,d,{info:y=>I.message(y),warn:y=>I.warn(y)})}await Td(e,s.repos);let f={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};X(f),rt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),I.success(`secrets \u2192 ${Ye(t.projectId)}`),await us(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),ls("done.")}function xd(t,e){if(!xr(t)){hd(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=xk(t).filter(o=>!r.has(o));n.length!==0&&(e||ee(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function as(t){if(!xr(Ft(t,".git")))return null;try{let r=(await No(t).remote(["get-url","origin"])||"").toString().trim(),n=r?Ee(r):null;return n?{parsed:n,defaultBranch:await Tk(t)}:null}catch{return null}}async function Tk(t){let e=No(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 Ik(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return At.test(e)?e:""}function Ck(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Pk(t){let e=Ft(t,".gitignore"),r=xr(e)?yd(e,"utf-8"):"";if(Ck(r))return;if(!be(await Sr({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){I.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
|
|
677
684
|
`)?"":`
|
|
678
685
|
`;wd(e,r+o+`
|
|
679
686
|
# codepipe workspace (added by \`codepipe init\`)
|
|
680
687
|
.codepipe/
|
|
681
|
-
`),I.success(`.codepipe/ added to ${kd(e)}`)}function Sd(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=
|
|
688
|
+
`),I.success(`.codepipe/ added to ${kd(e)}`)}function Sd(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=vk(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function Tr(){let t="";try{t=(await No().raw(["config","--global","user.email"])||"").trim()}catch{}return z(await oe({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Ir(t,e){I.step(`connecting account ${e}`);let r;try{r=await Xl(t,e)}catch(s){throw s instanceof nn&&ee(`${e} is not authorized on this HUB yet.
|
|
682
689
|
Sign up at ${t} (registration form on the login screen),
|
|
683
690
|
wait for the operator to approve it by email, then re-run
|
|
684
691
|
\`codepipe init\` with the same email.`),s}r.accountCreated&&I.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&I.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Sd(r.authorizeUrl),I.message(`a browser tab was opened to confirm this CLI:
|
|
685
692
|
${r.authorizeUrl}
|
|
686
693
|
`+(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
|
|
687
|
-
otherwise use the emailed link the page offers.`))),r.approvalRequired&&I.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),I.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
|
|
694
|
+
otherwise use the emailed link the page offers.`))),r.approvalRequired&&I.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),I.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 Ql(t,r.requestId)}catch(a){I.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await cs(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&I.message(`connected as ${a} (the account confirmed in the browser).`),I.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&ee("the HUB rejected this account"),s.status==="expired"&&ee("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,I.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
688
695
|
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await cs(5e3);continue}await cs(2e3)}ee("bootstrap timed out")}async function Rd(t,e,r){let n=Ft(t,We);if(xr(Ft(n,".git"))){I.message(`${n} already cloned \u2014 skipping`);return}xr(n)&&ee(`${n} exists but is not a git repo \u2014 remove it and re-run`),hd(n,{recursive:!0}),I.step(`cloning Context Repo \u2192 ${n}`);try{await No().clone(e,n,["--branch",r]),I.success(`cloned ${e}`)}catch(o){ee(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function Td(t,e){if(e.length===0)return;I.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 fn(t,r,{log:{info:o=>I.message(o),warn:o=>I.warn(o)}});for(let o of n)I.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Id(t){let e=Ft(t,We,".gitignore"),r="";if(xr(e)&&(r=yd(e,"utf-8")),gd.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
|
|
689
696
|
`)||r.length===0?"":`
|
|
690
697
|
`,i=gd.join(`
|
|
691
698
|
`)+`
|
|
692
699
|
`;wd(e,r+o+(r?`
|
|
693
|
-
`:"")+i),I.message(`appended runtime entries to ${kd(e)}`)}async function
|
|
700
|
+
`:"")+i),I.message(`appended runtime entries to ${kd(e)}`)}async function Ek(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;I.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await _o(s.host,t,s.owner,e,s.repoName),i?.();let c=z(await oe({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=z(await oe({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 Sr({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=z(await oe({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||Ee(m)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=Ee(a);I.message(`${c.host}: ${c.owner}/${c.repoName}`),await _o(c.host,t,c.owner,e,c.repoName),i?.();let l=z(await oe({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:m=>m.trim().length>0?void 0:"required"})).trim(),p=z(await oe({message:"default branch (optional)",placeholder:"main"})).trim(),f=z(await oe({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),u={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(u.defaultBranch=p),f&&f!==l&&(u.mountAs=f),o.push(u),n.onProgress?.(o)}return o}async function Cd(t,e,r,n){I.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 ct({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"&&I.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=z(await oe({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:et(t),validate:p=>{let f=(p??"").trim();if(!f)return"required";if(!Ee(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=Ee(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Ak(),l=z(await oe({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),p=z(await oe({message:"Context Repo name",placeholder:et(t),initialValue:et(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:p}}return{spec:a,mode:o}}function Pd(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??Qt()}}async function jk(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await _o(c.host,n,c.owner,o),i?.();let p=ps();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await Kp(c,Pd(n),{explain:l==="attach"});if(f.found===!0)return p.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return p.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(l==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(f.detail,1);let u=be(await ct({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"&&ee("aborted"),u==="create")return a={spec:c,mode:"create"},s(a),a;a=await Cd(e,r,n,o),s(a)}}async function Ak(){return be(await ct({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function gn(t,e){let r=ps();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 Ed(t){Qr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Zr(t.gitlab?.token??process.env.GITLAB_TOKEN),en(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function _o(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await _k(r);i?e.github=i:I.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await Nk(r,n,o);i?e.bitbucket=i:I.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 i=await Ok();i?e.gitlab=i:I.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function _k(t){for(;;){let e=z(await Rr({message:`GitHub PAT \u2014 blank to skip
|
|
694
701
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
695
702
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
696
703
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
697
704
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
698
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await gn("GitHub",()=>gt(e,t?{owner:t}:void 0)))return{token:e};I.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function
|
|
705
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await gn("GitHub",()=>gt(e,t?{owner:t}:void 0)))return{token:e};I.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Nk(t,e,r){for(I.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
699
706
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
700
707
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
|
|
701
708
|
read:repository:bitbucket + write:repository:bitbucket +
|
|
702
709
|
read:pullrequest:bitbucket + write:pullrequest:bitbucket
|
|
703
710
|
\u2014 write scopes do NOT include read: pick BOTH scopes of each pair
|
|
704
711
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
705
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let n=z(await oe({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=z(await Rr({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){I.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await gn("Bitbucket",async()=>{let i=await ht(n,o,t);if(t&&r){let s=await Jn(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};I.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function
|
|
706
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await gn("GitLab",()=>yt(t))){let e=await
|
|
712
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let n=z(await oe({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=z(await Rr({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){I.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await gn("Bitbucket",async()=>{let i=await ht(n,o,t);if(t&&r){let s=await Jn(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};I.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Ok(){for(;;){let t=z(await Rr({message:`GitLab PAT \u2014 blank to skip
|
|
713
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await gn("GitLab",()=>yt(t))){let e=await yc(t);return e&&I.warn(e),{token:t}}I.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Dk(t){if(be(await Sr({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
707
714
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
708
715
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
709
716
|
your trusted network.`,initialValue:!1})))for(t.host==="github"?I.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
710
717
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
711
718
|
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):I.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
712
|
-
(${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=z(await Rr({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await gn("contextWrite",()=>
|
|
713
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=z(await Rr({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||I.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):(I.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 jd(){for(;;){let t=z(await oe({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=z(await Rr({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await gn("YouTrack",()=>$t({baseUrl:t,token:e}))){let r=await
|
|
719
|
+
(${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=z(await Rr({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await gn("contextWrite",()=>Uk(r,t)))return{token:r};I.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Uk(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 Lk(t){if(ti()?.claude?.oauthToken&&!t)return I.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`)."),"";I.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?`
|
|
720
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=z(await Rr({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||I.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):(I.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 jd(){for(;;){let t=z(await oe({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=z(await Rr({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await gn("YouTrack",()=>$t({baseUrl:t,token:e}))){let r=await il({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}I.warn("re-enter the YouTrack URL / token.")}}var gd,mn=R(()=>{"use strict";Ne();q();Ce();ke();nt();Ut();Io();Hi();Co();wt();Lt();ed();fe();od();ad();Di();eo();re();Eo();tt();gd=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});q();Ne();ke();import{Command as Vb}from"commander";_n();import{homedir as ja}from"node:os";import{join as Aa}from"node:path";function _a(){Nt(Aa(ja(),".devpipe"),Aa(ja(),".codepipe"))}ke();re();async function Ya(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=Oe(e);r&&!t.force&&(console.error(`already configured at ${zt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");rt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...M(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};X(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${zt(e)}`)}ri();ke();import{homedir as Wi}from"node:os";import{join as an}from"node:path";Ne();q();import{existsSync as Ru,rmSync as Xh}from"node:fs";import{join as sn}from"node:path";import{simpleGit as Qh}from"simple-git";import"ws";Ne();re();import{createHash as om}from"node:crypto";import{existsSync as im,readFileSync as sm}from"node:fs";import{homedir as am,hostname as ni}from"node:os";import{join as cm}from"node:path";function za(t){return om("sha256").update(t).digest("hex").slice(0,12)}function lm(){let t=K("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=cm(am(),".claude","credentials.json");if(!im(e))return;let r=JSON.parse(sm(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 Xa(t){let e=lm(),r=K("ACCOUNT_ID")?.trim(),n=K("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Xt(t);return o?{accountId:`acct-${za(o)}`,label:n||ni(),...e?{email:e}:{}}:{accountId:`acct-${za(`host:${ni()}`)}`,label:n||ni(),...e?{email:e}:{}}}import{existsSync as um}from"node:fs";import{join as pm}from"node:path";import{simpleGit as dm}from"simple-git";async function Qa(t,e){if(!um(pm(t,".git")))return{status:"skipped"};let r=dm(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${fm(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 fm(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as ii,readFileSync as nc,readdirSync as hm,watch as ym}from"node:fs";import{join as si}from"node:path";q();import{existsSync as Za,readFileSync as ec,readdirSync as mm,statSync as gm}from"node:fs";import{join as oi}from"node:path";import{parse as tc}from"yaml";function Fn(t){let e=oi(t,"actions"),r=[],n=[];if(!Za(e))return{defs:r,errors:n};let o;try{o=mm(e).sort()}catch{return{defs:r,errors:n}}let i=new Set;for(let s of o){if(!/\.(yml|yaml)$/i.test(s))continue;let a=oi(e,s);try{if(!gm(a).isFile())continue;let c=qs(s,tc(ec(a,"utf-8")));if(i.has(c.id))throw new Error(`duplicate action id "${c.id}"`);i.add(c.id),r.push(c)}catch(c){n.push({file:`actions/${s}`,error:c instanceof Error?c.message:String(c)})}}return{defs:r,errors:n}}function rc(t){let e={},r=oi(t,"project.yaml");if(!Za(r))return e;let n;try{n=tc(ec(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[i,s]of Object.entries(o))!Se.test(i)||pt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var Hn=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(ii(this.contextDir))try{this.watcher=ym(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(){let e=Fn(this.contextDir);return{type:"config_observation",projectId:this.projectId,projectYaml:this.readFile("project.yaml"),regimenYaml:this.readFile("regimen.yaml"),prompts:this.readPrompts(),actions:e.defs,actionErrors:e.errors}}readFile(e){let r=si(this.contextDir,e);if(!ii(r))return null;try{return nc(r,"utf-8")}catch{return null}}readPrompts(){let e=si(this.contextDir,"prompts"),r={};if(!ii(e))return r;let n;try{n=hm(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=nc(si(e,o),"utf-8")}catch{}}return r}};mt();import{existsSync as mi,readFileSync as uc,readdirSync as Pm}from"node:fs";import{join as pc}from"node:path";import{simpleGit as Em}from"simple-git";var jm=/^(\d{4})-(.+)\.md$/,Am="0000-template.md";function _m(t){let e=t.split(`
|
|
714
721
|
`),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 Nm(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
715
|
-
`),a=s.findIndex(
|
|
716
|
-
`).replace(/^\n+/,""),
|
|
717
|
-
`);return{content:
|
|
718
|
-
`)?
|
|
722
|
+
`),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"]),p=[],f="",u=null,m=a>=0?a+1:0;for(let b=m;b<s.length;b++){let w=(s[b]??"").trim();if(w===""){m=b+1;continue}let k=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!k)break;let C=(k[1]??"").trim().toLowerCase(),G=(k[2]??"").trim(),T=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(w);T&&(u=parseInt(T[1]??"",10)),C==="tasks"&&(f=G),l.has(C)||p.push(w),m=b+1}let d=f?f.includes(n)?f:`${f}, ${n}`:n,h=s.slice(m).join(`
|
|
723
|
+
`).replace(/^\n+/,""),y=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${d}`,...p,"",h].join(`
|
|
724
|
+
`);return{content:y.endsWith(`
|
|
725
|
+
`)?y:y+`
|
|
719
726
|
`,supersedes:u}}function Om(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
|
|
720
727
|
|
|
721
728
|
- **Status:** superseded by ADR-${r}`):n}function Dm(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(`
|
|
722
729
|
`)+`
|
|
723
|
-
`}async function
|
|
724
|
-
`)}async function
|
|
730
|
+
`}async function dc(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Em(t).pull(void 0,void 0,["--rebase"])}catch{}let i=y=>o==="staging"?`adr/DRAFT-${y}.md`:`tasks/${e}/adr/DRAFT-${y}.md`,s=[],a=[];for(let y of r){let b=ue(t,i(y));if(!mi(b)){a.push(y);continue}s.push({slug:y,content:uc(b,"utf-8")})}let c=pc(t,"adr"),l=new Map;if(mi(c))for(let y of Pm(c)){let b=jm.exec(y);!b||y===Am||l.set(y,{num:parseInt(b[1]??"",10),slug:b[2]??"",content:uc(pc(c,y),"utf-8")})}let p=Math.max(0,...[...l.values()].map(y=>y.num))+1,f=new Map,u=[],m=[];for(let y of s){if([...l.entries()].find(([,T])=>T.slug===y.slug&&T.content.includes(e))){m.push(y.slug);continue}let w=p++,k=`${String(w).padStart(4,"0")}-${y.slug}.md`,{content:C,supersedes:G}=Nm(y.content,w,y.slug,e,n);if(f.set(k,C),l.set(k,{num:w,slug:y.slug,content:C}),u.push(`adr/${k}`),G!==null){let T=[...l.keys()].find(_=>_.startsWith(`${String(G).padStart(4,"0")}-`));if(T&&T!==k){let _=Om(f.get(T)??l.get(T).content,w);f.set(T,_),l.set(T,{...l.get(T),content:_})}}}let d=[];if(o==="staging")for(let y of s)mi(ue(t,`adr/DRAFT-${y.slug}.md`))&&d.push({path:`adr/DRAFT-${y.slug}.md`,content:"",deleted:!0});if(u.length===0&&d.length===0)return{promoted:u,skipped:m,missing:a};if(u.length>0){let y=[...l.entries()].map(([b,w])=>({num:w.num,file:b,header:_m(w.content)}));f.set("INDEX.md",Dm(y))}for(let[y,b]of f.entries())d.push({path:`adr/${y}`,content:b});let h=u.length>0?`adr(${e}): promote ${s.map(y=>y.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await ot(t,d,h),{promoted:u,skipped:m,missing:a}}mt();nt();q();import{existsSync as fc,readFileSync as Lm}from"node:fs";import{join as mc}from"node:path";function Bm(t){for(let e of[He,Ur]){let r=mc(t,e);if(fc(r))try{return Os(Lm(r,"utf-8"))}catch{return 0}}return 0}function Mm(t,e,r,n=3){let o=e<n,i=o?Ds(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function qn(t,e){return Mm(e,Bm(t),r=>fc(mc(t,r)))}q();wt();import{existsSync as Ic,mkdirSync as fg,mkdtempSync as mg,rmSync as Cc,writeFileSync as Pc}from"node:fs";import{tmpdir as gg}from"node:os";import{dirname as hg,join as Xn}from"node:path";import{simpleGit as xi}from"simple-git";Ut();function yg(t){return`codepipe/context-migration-v${t}`}function wg(t){let e=Us(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 \`${He}\` stamp (renamed from \`${Ur}\``,"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(`
|
|
731
|
+
`)}async function Ec(t,e,r,n){let o=xi(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=qn(t,e);if(!i.outdated)return i;let s=yg(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 kg(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=De(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 f=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:wg(i)});return n.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function kg(t,e,r,n,o,i,s){let a=xi(t),c=mg(Xn(gg(),"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`},f=new Map(or(l,p).map(h=>[h.path,h.content])),u=0;for(let h of n.missingPaths){if(h===He)continue;let y=f.get(h);if(y==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let b=Xn(c,h);Ic(b)||(fg(hg(b),{recursive:!0}),Pc(b,y),u++)}Pc(Xn(c,He),In(n.currentVersion)),u++;let m=Xn(c,Ur);Ic(m)&&(Cc(m,{force:!0}),u++);let d=xi(c);await d.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await d.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await d.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${u} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Cc(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as bg,readFileSync as $g,writeFileSync as vg}from"node:fs";import{homedir as xg}from"node:os";import{join as jc}from"node:path";import{parseDocument as Sg}from"yaml";function Rg(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 Tg(t,e){let r=Sg(t);return r.set("repos",e.map(Rg)),r.toString()}function Ig(t,e){let r=[jc(xg(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(jc(e,"project.yaml")),r}function Yr(t,e,r){let n=[],o=[];for(let i of Ig(t,r))if(bg(i))try{let s=$g(i,"utf-8"),a=Tg(s,e);a!==s&&(vg(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 Cg}from"node:os";import{existsSync as Pg,mkdirSync as Eg}from"node:fs";import{join as Si}from"node:path";import{simpleGit as Ri}from"simple-git";var Ac=t=>console.log(t);function _c(t){Ac=t}function qr(t,e="info"){Ac(t,e)}function Ie(t,e,r){let n=r??Si(Cg(),".codepipe","repos");return Si(n,t,e)}async function Jr(t,e,r={}){let n=Ie(t,e.name,r.baseDir),o=r.cloneUrlOverride??zr(e);if(!Pg(Si(n,".git"))){Eg(n,{recursive:!0});let a=Ri();qr(`[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}
|
|
725
732
|
${l.trim()}`)}}let i=Ri(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
|
|
726
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Vr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var
|
|
727
|
-
${
|
|
728
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function
|
|
729
|
-
`,o.length>
|
|
730
|
-
`))!==-1;)o(m,
|
|
731
|
-
`)}function wh(t,e,r){let n=new Map,o=ue(t,`tasks/${e}/comments.jsonl`);if(
|
|
733
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Vr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var Nc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function Qn(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&&qr(`[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 Vr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Vr(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([...Nc,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Oc(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await Vr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Vr(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 Dc(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:p,force:f}=r,u=await Oc(t,i,()=>Qn(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;if(await Vr(t,m)||(m=`origin/${p??c}`),(await t.revparse([m])).trim()===s)await t.raw(["branch","-f",a,u]),await t.checkout(a);else{await t.checkout(["-B",a,m]);try{await t.raw([...Nc,"cherry-pick",u])}catch(b){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let w=b instanceof Error?b.message:String(b);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
734
|
+
${w.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),y=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(y),await t.push([n,"--delete",o]).catch(()=>{}),{commit:h}}async function Uc(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,p=await Oc(t,i,()=>Qn(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 Lc(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 zr(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`}async function Bc(t){return(await Ri().listRemote(["--heads",t])).split(`
|
|
735
|
+
`).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function Mc(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}Ce();re();function Dg(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 Wc(t,e,r,n){let o=Dg(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=Ln(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=it(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}Ce();re();wt();Lt();re();wt();Lt();function Ue(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function vl(t,e){let r=M(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await $t({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:Ue(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Ue(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 gt(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:Ue(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Ue(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 ht(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:Ue(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Ue(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await yt(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:Ue(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Ue(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 Vn(c,p.owner,p.repoName),n.push({name:`repo:${p.name}`,ok:!0})}catch(f){n.push({name:`repo:${p.name}`,ok:!1,detail:Ue(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Vn(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(p){n.push({name:"context-repo",ok:!1,detail:Ue(p)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Vn(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:Ue(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=Xt(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 Pi(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 Pi(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)}}eo();function Tl(t){let e=M(t);if(!e)return null;if(!e.sealKey){let r=Zn();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},X(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ye(e.sealKey.publicKey)}}async function Il(t,e,r,n){let o;try{o=JSON.parse(ir(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=M(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 gt(o.token);return i.github={token:o.token},sr(i,()=>{process.env.GH_TOKEN=o.token,xl(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await yt(o.token);return i.gitlab={token:o.token},sr(i,()=>{process.env.GITLAB_TOKEN=o.token,Sl(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 ht(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},sr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Rl(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 $t({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},sr(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 Pi(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},sr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},sr(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 sr(t,e){X(t),e()}q();q();import{spawn as Xg}from"node:child_process";var Qg=124,Cl=16*1024,Pl=4e3;function Zg(t,e,r,n,o,i){let s={...t},a=(c,l)=>{pt(c)||(s[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))s[c]=l;for(let[c,l]of Object.entries(i))s[`INPUT_${c}`]=String(l);return s}async function El(t){let{def:e,onEvent:r}=t,n=Zg(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
736
|
+
`,o.length>Cl&&(o=o.slice(o.length-Cl))},s=(a,c)=>{let l=c.length>Pl?c.slice(0,Pl)+"\u2026":c;i(l),r({ts:Date.now(),kind:"log",stream:a,text:l})};r({ts:Date.now(),kind:"start",status:"running"});for(let[a,c]of e.steps.entries()){let l=c.name??`step ${a+1}`;r({ts:Date.now(),kind:"step",stepName:l});let p=await eh(c.run,c.timeout_sec,t.cwd,n,s);if(p!==0)return i(`[${l}] exited with code ${p}`),r({ts:Date.now(),kind:"result",status:"failed",exitCode:p,failedStep:l}),{status:"failed",exitCode:p,failedStep:l,logTail:o}}return r({ts:Date.now(),kind:"result",status:"succeeded",exitCode:0}),{status:"succeeded",exitCode:0,logTail:o}}function eh(t,e,r,n,o){return new Promise(i=>{let s=Xg("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Ys)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let p=m=>{let d="";return{data:h=>{d+=h.toString("utf-8");let y;for(;(y=d.indexOf(`
|
|
737
|
+
`))!==-1;)o(m,d.slice(0,y).replace(/\r$/,"")),d=d.slice(y+1)},flush:()=>{d.length>0&&o(m,d.replace(/\r$/,"")),d=""}}},f=p("stdout"),u=p("stderr");s.stdout?.on("data",f.data),s.stderr?.on("data",u.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,d)=>{clearTimeout(l),f.flush(),u.flush(),i(a?Qg:m??(d?1:0))})})}mt();import{existsSync as th,readFileSync as rh,statSync as jl}from"node:fs";var Al=2*1024*1024;function nh(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function _l(t,e){let r=ue(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!th(r)||!jl(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=jl(r);if(n>Al)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Al})`);let o=rh(r);return nh(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}re();q();import{existsSync as oh,readFileSync as ih,writeFileSync as sh}from"node:fs";import{join as ah}from"node:path";import{parseDocument as ch}from"yaml";async function Nl(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=Zs(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=ah(t,o);if(!oh(s))throw new Error(`${o} not found in context repo (${t})`);let a=ch(ih(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);sh(s,a.toString()),n.push(o)}return{files:n}}q();import{existsSync as lh,readFileSync as uh,writeFileSync as ph}from"node:fs";import{join as dh}from"node:path";import{isMap as Ol,parseDocument as fh}from"yaml";async function Dl(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||!ia(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=dh(t,"project.yaml");if(!lh(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=fh(uh(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Ol(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Ol(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),ph(o,i.toString()),{repoName:r,defaultBranch:n}}import{existsSync as ji,readFileSync as Ai,writeFileSync as mh}from"node:fs";import{join as to}from"node:path";import{parseDocument as _i}from"yaml";async function Ul(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=to(t,"project.yaml");if(!ji(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=_i(Ai(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=to(t,"regimen.yaml");if(!ji(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=_i(Ai(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)mh(to(t,i.path),i.content);return{files:r.map(i=>i.path)}}function ro(t){if(!t)return"Stage";try{let e=to(t,"project.yaml");if(!ji(e))return"Stage";let n=_i(Ai(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}wt();Lt();import{existsSync as Ml,readFileSync as Gl}from"node:fs";import{join as Fl}from"node:path";import{parseDocument as Hl}from"yaml";Lt();var tn=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return hl(this.cfg,e)}getIssue(e,r){return yl(this.cfg,e,r??ro(this.contextDir))}listComments(e,r){return wl(this.cfg,e,r)}downloadAttachment(e){return gl(this.cfg,e)}updateStatus(e,r){return sl(this.cfg,e,r,ro(this.contextDir))}addComment(e,r,n){return al(this.cfg,e,r)}createIssue(e){return ul(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,ro(this.contextDir))}editIssue(e,r){return cl(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return pl(this.cfg,e,r,n)}fetchStateFields(e){return bl(this.cfg,e)}};q();mt();import{existsSync as $h,readFileSync as vh}from"node:fs";import{randomBytes as xh}from"node:crypto";import{existsSync as Ll,readFileSync as gh,readdirSync as hh}from"node:fs";q();mt();function no(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=bh(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:yh(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:kh(wh(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 oo(t,e,r){if(r.length===0)return;let n=no(t,e,r),o=r.map(i=>i.issue.key);await ot(t,n,`sync(${o.join(", ")}): task data`)}function yh(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(`
|
|
738
|
+
`)}function wh(t,e,r){let n=new Map,o=ue(t,`tasks/${e}/comments.jsonl`);if(Ll(o))for(let i of gh(o,"utf-8").split(`
|
|
732
739
|
`)){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){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=qt(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function kh(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
733
740
|
`)+(t.length>0?`
|
|
734
|
-
`:"")}function bh(t,e,r){let n=[],o=ue(t,`tasks/${e}/attachments`);if(
|
|
741
|
+
`:"")}function bh(t,e,r){let n=[],o=ue(t,`tasks/${e}/attachments`);if(Ll(o))for(let i of hh(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}zn();var rn=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Hr(this.contextDir);let r=e.columns??[];return Sc(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Wr(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Kr(this.contextDir,e);return r?Wr(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Bl(this.contextDir,e).map(n=>({id:n.id,issueId:e,author:n.author,body:n.body,createdAt:n.createdAt}))}async downloadAttachment(e){throw new Error(`internal tracker: no remote attachments (${e})`)}async updateStatus(e,r){await this.mutateRecord(e,n=>({...n,status:r}))}async addComment(e,r,n){if(await Hr(this.contextDir),!Kr(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${xh(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=qt(r);s&&(i.parsedCommand=s);let c=[...Bl(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
|
|
735
742
|
`)+`
|
|
736
|
-
`;return await ot(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:i.id}}async createIssue(e){let r=new Date().toISOString(),n=await
|
|
737
|
-
`)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}zn();function Ni(t){if(!t)return"youtrack";try{let e=Gl(t,"project.yaml");return Bl(e)&&Fl(Ml(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Je(t){let e=Ni(t.contextDir);if(e==="internal"){let n=t.contextDir;if(!n)return{ok:!1,kind:e,error:"internal tracker: no Context Repo clone on this CLI"};let o=$c(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Sh(n);return i?{ok:!0,kind:e,provider:new rn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=nl();return r?{ok:!0,kind:e,provider:new tn(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Sh(t){try{let e=Gl(t,"project.yaml");if(!Bl(e))return null;let r=Fl(Ml(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var io=new Map;async function so(t,e){let n=(io.get(t)??Promise.resolve()).catch(()=>{}).then(e);io.set(t,n);try{return await n}finally{io.get(t)===n&&io.delete(t)}}async function Hl(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;qr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return W("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return so(`${i}/${r.name}`,async()=>{let s=await Jr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{commit:c}=await Oc(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 ne({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 W("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return so(`${i}/${r.name}`,async()=>{let s=await Jr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{commit:c,pushed:l}=await Dc(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ne({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return W("no repo spec");let i=De(r),s=await i.createPullRequest(r,e);return ne({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return W("no repo spec");let i=De(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ne({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return W("no repo spec");let i=De(r);return await i.closePR(r,e.prNumber,e.comment),ne({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return W("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return so(`${i}/${r.name}`,async()=>{let s=await Jr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{mergedSha:c}=await Uc(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ne({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return W("no repo spec");let i=t.cloneUrlOverride??zr(r),a=(await Lc(i)).filter(p=>Bc(p,e.issueKey)),c=De(r),l=null;if(c.findOpenPrByBranch)for(let p of a){let d=await c.findOpenPrByBranch(r,p).catch(()=>null);if(d){l={number:d.number,url:d.url};break}}return ne({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return W("no repo spec");let i=De(r);return await i.addPRComment(r,e.prNumber,e.body),ne({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=Je({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ne({issueId:t.trackerIssueId,newStatus:e.newStatus})):W("no tracker_issue_id provided"):W(i.error)}case"tracker_comment":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);if(!t.trackerIssueId)return W("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ne({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);if(!e.projectKey)return W("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ne({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return W(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ne({applied:s})}case"set_project_setting":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=await _l(t.contextDir,e.edits);return ne({files:i.files})}case"tracker_edit":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);if(!t.contextDir)return W("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await oo(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ne({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=await Dl(t.contextDir,e);return ne({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=await Ol(t.contextDir,e);return ne({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ne({reported:!0})):W("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return W("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ne({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return W("no project workspace on this CLI");if(!r)return W("no repo spec");if(!t.onRunActivity)return W("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Fn(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return W(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=qs(c,e.input);if(!l.ok)return W(l.error);let p=tc(t.contextDir),d=M(e.projectId),u={};return d?.github?.token&&(u.GH_TOKEN=d.github.token),d?.gitlab?.token&&(u.GITLAB_TOKEN=d.gitlab.token),d?.bitbucket&&(u.BITBUCKET_EMAIL=d.bitbucket.email,u.BITBUCKET_API_TOKEN=d.bitbucket.apiToken),d?.youtrack&&(u.YOUTRACK_URL=d.youtrack.url,u.YOUTRACK_TOKEN=d.youtrack.token),so(`${e.projectId}/${r.name}`,async()=>{await Jr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=Ie(e.projectId,r.name,t.baseDir),f=await Pl({cwd:m,def:c,input:l.values,variables:p,secrets:d?.secrets??{},credEnv:u,onEvent:y=>i(e.runId,y)});return ne({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=Al(t.contextDir,e.path);return ne({path:e.path,...i})}default:return W(`unsupported action type: ${e.type}`)}}catch(i){return W(i instanceof Error?i.message:String(i))}}function ne(t){return{status:"done",result:t}}function W(t){return{status:"failed",error:t}}Ce();Di();fe();re();import{existsSync as su,readFileSync as au}from"node:fs";import{join as cu}from"node:path";async function lu(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=ye(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");co(e.farmId,e.farmPublicKey);let s=M(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await J(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=cu(r,"project.yaml"),m=cu(r,"regimen.yaml");su(u)&&su(m)?c={projectYaml:au(u,"utf-8"),regimenYaml:au(m,"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=it(e.farmPublicKey,JSON.stringify(l));ao(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let d=await uo(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))}}Ce();Ne();Ce();import{homedir as Dh}from"node:os";import{existsSync as Uh,mkdirSync as Lh,readFileSync as Bh,writeFileSync as Mh}from"node:fs";import{dirname as Gh,join as Fh}from"node:path";function Bi(){return K("RUNNER_PINS")??Fh(Dh(),".codepipe","runner-pins.json")}function uu(){let t=Bi();if(!Uh(t))return{};try{return JSON.parse(Bh(t,"utf-8"))}catch{return{}}}function Hh(t){let e=Bi();Lh(Gh(e),{recursive:!0}),Mh(e,JSON.stringify(t,null,2)+`
|
|
738
|
-
`,{mode:384})}function Kh(t){return uu()[t]}function Mi(t,e){let r=uu();r[t]=e,Hh(r)}function pu(t,e){let r=ye(e),n=Kh(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 ${Bi()}.`);return r}fe();re();var fu=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function du(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:fu(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 Wh={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:fu(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)=>du(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>du(t,e,r,"remove-token")},mu={api:Wh,fetchProject:J,provisionOnRunner:Yl,teardownOnRunner:ql};async function gu(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(ye(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");pu(e.runnerId,e.runnerPublicKey);let i=M(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 hu(t,e,r,n=mu){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 gu(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=it(e.runnerPublicKey,JSON.stringify(l));Mi(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 yu(t,e,r,n=mu){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 gu(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=it(e.runnerPublicKey,JSON.stringify(c));Mi(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))}}fe();q();Ce();re();var wu=16*1024;function Yh(t){return Se.test(t)?pt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Se}`}function ku(t,e,r,n){let o=Yh(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(ir(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>wu)return{ok:!1,detail:`secret value too large (max ${wu} chars)`};try{return Ma(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function bu(t,e){try{return Ga(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}re();wt();var fo=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=De(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 Dt){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=De(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=qh(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function qh(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}q();var mo=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 r=(this.options.resolveProvider??(()=>Je({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let k=e.stageField?{stageField:e.stageField}:{},C=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},T=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(T){let _=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[F,E]=await Promise.all([_.length>0?r.listIssues({projectKey:e.projectKey,columns:_,...k,...C}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...k})]),g=new Map;for(let N of[...F,...E])g.set(N.id,N);o=[...g.values()]}else{let _=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:_,...k,...C})}}catch(k){this.log.warn(`[yt-sync] listIssues failed: ${k instanceof Error?k.message:String(k)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let k of o){if(s.add(k.id),a.has(k.status))continue;let C=await vu(r,k.id,e.sinceMs,this.log);C&&i.set(k.id,C)}let c=[];for(let k of e.offBoardIssueIds){if(s.has(k))continue;let C=await vu(r,k,e.sinceMs,this.log);if(C&&C.length>0&&i.set(k,C),e.requireAssignee||C&&C.length>0){let G=await zh(r,k,e.stageField,this.log);if(G)c.push(G);else if(C&&C.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(k=>!a.has(k.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(k=>({issue:k,comments:i.get(k.id)??[],attachments:p.get(k.id)??[]}));try{await oo(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let k of d)this.shippedAttachments.add(k)}catch(k){let C=k instanceof Error?k.message:String(k);this.abandonTick(`context task sync failed: ${C}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],y=[];for(let[k,C]of i){let G=C.filter(_=>!m(_.id));if(G.length===0)continue;f.push({issueId:k,comments:G.map(Vh)});let T=G.flatMap(_=>{let F=qt(_.body);return F?[{commentId:_.id,author:_.author,name:F.name,args:F.args,createdAt:_.createdAt}]:[]});T.length>0&&y.push({issueId:k,commands:T})}let w={type:"youtrack_observation",projectId:e.projectId,issues:o.map($u),commentsBatch:f,...y.length>0?{commandsBatch:y}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map($u)}:{},observedAtMs:n};this.send(w);let $=f.reduce((k,C)=>k+C.comments.length,0),h=y.reduce((k,C)=>k+C.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${$} 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 n.downloadAttachment(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 m=Jh(p.name);l.has(m)&&(m=`${p.id}-${m}`),l.add(m),c.push({name:m,contentBase64:u.toString("base64")}),i.push(d)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function $u(t){let{description:e,...r}=t;return r}function Vh(t){let{body:e,...r}=t;return r}function Jh(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 zh(t,e,r,n){try{return await t.getIssue(e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function vu(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Gi="npm i -g @code-partner/codepipe@latest";function go(t,e={}){let r=e.log??{info:f=>console.log(f),warn:f=>console.warn(f)};r.info(`codepipe-cli v${xe} (protocol ${Fe})`);let n=f=>e.onEvent?.(f),o=e.workspace;o?.contextDir&&oc(o.contextDir,r);let i=xu("CLI_TRACKING_POLL_INTERVAL_SEC"),s=xu("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=m();function m(){let f=lo(t.hubUrl,t.cliToken),y=null,w=new fo(i,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r),$=new mo(s,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r,{contextDir:o?.contextDir??null,isSelfComment:b=>d.has(b)}),h=null,k=async()=>{try{let b={trackerProvider:Ni(o?.contextDir??null)};try{let j=await J(t.hubUrl,t.cliToken,t.projectId);b={...b,repos:j.repos,contextRepo:j.contextRepo}}catch(j){r.warn(`[readiness] could not fetch project summary for push checks: ${j instanceof Error?j.message:String(j)}`)}let P=await $l(t.projectId,b);if(f.readyState!==f.OPEN)return;let x={type:"cli_readiness",projectId:t.projectId,ready:P.ready,checks:P.checks,creds:P.creds,secretNames:Fa(t.projectId),checkedAt:P.checkedAt};if(f.send(JSON.stringify(x)),P.ready)r.info("[readiness] ready");else{let j=P.checks.filter(B=>!B.ok).map(B=>`${B.name}(${B.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${j.join(", ")}`)}}catch(b){r.warn(`[readiness] check failed: ${b instanceof Error?b.message:String(b)}`)}},C=()=>{k(),h=setInterval(()=>void k(),a),typeof h.unref=="function"&&h.unref()},G=()=>{h&&(clearInterval(h),h=null)},T=150,_=new Map,F=b=>{let P=_.get(b);if(!P||(P.timer&&clearTimeout(P.timer),_.delete(b),P.events.length===0||f.readyState!==f.OPEN))return;let x={type:"run_activity",projectId:t.projectId,runId:b,events:P.events};f.send(JSON.stringify(x))},E=(b,P)=>{let x=_.get(b);if(x||(x={events:[],timer:null},_.set(b,x)),x.events.push(P),P.kind==="result"){F(b);return}x.timer||(x.timer=setTimeout(()=>F(b),T),x.timer.unref?.())},g=o?.contextDir?new Hn(o.contextDir,t.projectId,b=>{f.readyState===f.OPEN&&f.send(JSON.stringify(b))},r):null,N=async()=>{let b=o?.contextDir;if(!b)throw new Error("no context repo clone on this CLI");let P;try{P=(await J(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let x=await Pc(b,t.projectId,P,r);return f.readyState===f.OPEN&&f.send(JSON.stringify(x)),x};return f.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let b=za(t.projectId),P=K("ORIGIN")==="farm"?"farm":"local",x=K("FARM_ID"),j=t.accountEmail??b.email,B;try{let S=Rl(t.projectId);S&&(B=S.publicKey,r.info(`[cred-channel] key fingerprint: ${S.fingerprint}`))}catch(S){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${S instanceof Error?S.message:String(S)}`)}let v={type:"register",projectId:t.projectId,platformVersion:xe,protocolVersion:Fe,accountId:b.accountId,accountLabel:b.label,origin:P,inFlightActionIds:[...p],...j?{accountEmail:j}:{},...P==="farm"&&x?{farmId:x}:{},...B?{sealPublicKey:B}:{}};f.send(JSON.stringify(v))}),f.on("message",async b=>{let P=b.toString("utf-8");if(P==="pong"||P==="ping")return;let x;try{x=JSON.parse(P)}catch{return}if(!x||typeof x!="object")return;let j=x.type;if(j==="registered"){let v=x;if(v.ok){if(r.info(`[ws] registered for project ${v.projectId}`),n({kind:"registered",projectId:v.projectId??t.projectId}),w.start(),g?.start(),C(),Fi(t,o,r),o?.contextDir)try{let S=qn(o.contextDir,t.projectId);f.readyState===f.OPEN&&f.send(JSON.stringify(S)),S.outdated&&(r.warn(`[ctx] context format outdated: v${S.templateVersion} \u2192 v${S.currentVersion}`+(S.missingPaths.length>0?` (missing: ${S.missingPaths.join(", ")})`:"")),l||(l=!0,N().catch(()=>{})))}catch(S){r.warn(`[ctx] context-format detect failed (non-fatal): ${S instanceof Error?S.message:String(S)}`)}}else r.warn(`[ws] register rejected: ${v.reason??"unknown"}`),n({kind:"register_rejected",reason:v.reason??"unknown"}),c=!0,f.close();return}if(j==="hello"){let v=x;y=Tn(v.protocolVersion);let S=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${v.platformVersion} (protocol ${v.protocolVersion}) \u2014 ${S}`),y||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${xe}, protocol ${Fe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Gi}`),n({kind:"incompatible",hubVersion:typeof v.platformVersion=="string"?v.platformVersion:null,hubProtocol:typeof v.protocolVersion=="number"?v.protocolVersion:null,updateCommand:Gi}));return}if(j==="tracking_targets"){w.setTargets(x.targets);return}if(j==="youtrack_sync_request"){$.setRequest(x);return}if(j==="youtrack_force_sync"){$.forceSync();return}if(j==="sync_local"){await ty(x,o,f,r);return}if(j==="provision_repo"){let v=x;r.info(`[repo] provision_repo: ${v.repo.name} (${v.repo.host}:${v.repo.owner}/${v.repo.repoName})`),await Zh(t,o,v.repo,r),await Fi(t,o,r);return}if(j==="remove_repo"){let v=x;r.info(`[repo] remove_repo: ${v.repoName}${v.purge?" (purge)":""}`),await Fi(t,o,r),v.purge&&ey(t,o,v.repoName,r);return}if(j==="context_write"){await ry(x,o,f,r);return}if(j==="adr_promote"){await ny(x,o,f,r);return}if(j==="cred_update"){let v=x,S=M(t.projectId),H=S?.sealKey?await Tl(t.projectId,v.kind,v.sealed,S.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},te={type:"cred_update_result",updateId:v.updateId,projectId:t.projectId,ok:H.ok,...H.detail?{detail:H.detail}:{}};f.readyState===f.OPEN&&f.send(JSON.stringify(te)),H.ok?(r.info(`[cred] ${v.kind} replaced${H.detail?` \u2014 ${H.detail}`:""}`),k()):r.warn(`[cred] ${v.kind} replacement rejected: ${H.detail??"unknown"}`);return}if(j==="move_to_farm"){let v=x;r.info(`[farm-move] request to move ${t.projectId} onto farm ${v.farmName} (${v.farmId})`);let S=await lu(t,v,o?.contextDir,r);f.readyState===f.OPEN&&f.send(JSON.stringify(S)),S.ok?r.info(`[farm-move] done \u2014 farm daemon ${S.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${S.error??"unknown error"}`);return}if(j==="gh_runner_setup"){let v=x;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let S=await hu(t,v,r);f.readyState===f.OPEN&&f.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners connected on ${v.runnerName}`):r.warn(`[ghr] setup failed: ${S.error??"see per-repo statuses"}`);return}if(j==="gh_runner_teardown"){let v=x;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let S=await yu(t,v,r);f.readyState===f.OPEN&&f.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners disconnected from ${v.runnerName}`):r.warn(`[ghr] teardown failed: ${S.error??"unknown error"}`);return}if(j==="tracker_fields_request"){let v=x,S={type:"tracker_fields_result",requestId:v.requestId,projectId:t.projectId,ok:!1},H=Je({contextDir:o?.contextDir??null});if(!H.ok)S.error=H.error;else try{S.fields=await H.provider.fetchStateFields(v.projectKey),S.ok=!0}catch(te){S.error=te instanceof Error?te.message:String(te)}f.readyState===f.OPEN&&f.send(JSON.stringify(S)),S.ok||r.warn(`[yt-fields] listing failed: ${S.error??"unknown"}`);return}if(j==="project_secret_update"||j==="project_secret_delete"){let v=x,S;if(v.type==="project_secret_update"){let te=M(t.projectId);S=te?.sealKey?ku(t.projectId,v.name,v.sealed,te.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else S=bu(t.projectId,v.name);let H={type:"project_secret_update_result",updateId:v.updateId,projectId:t.projectId,ok:S.ok,...S.detail?{detail:S.detail}:{}};f.readyState===f.OPEN&&f.send(JSON.stringify(H)),S.ok?(r.info(`[secret] ${v.name} ${v.type==="project_secret_update"?"saved":"deleted"}`+(S.detail?` \u2014 ${S.detail}`:"")),k()):r.warn(`[secret] ${v.name} rejected: ${S.detail??"unknown"}`);return}if(j==="sandbox_keys"){let v=M(t.projectId);if(!v){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let S=Xt(t.projectId),H=Kc(x,v,S,r);for(let te of H)f.readyState===f.OPEN&&f.send(JSON.stringify(te));return}if(j!=="dispatch_action")return;let B=x;if(y===!1){let v=`refused: HUB protocol incompatible with CLI v${xe} (protocol ${Fe})`;f.send(JSON.stringify({type:"action_result",actionId:B.actionId,status:"failed",error:v})),r.warn(`[exec] ${B.actionId} (${B.action.type}) \u2192 REFUSED: ${v}`),r.warn(`[exec] update the CLI to clear this: ${Gi}`),n({kind:"action",actionId:B.actionId,actionType:B.action.type,ok:!1,error:v});return}p.add(B.actionId);try{let v=await Hl({action:B.action,repo:B.repo,trackerIssueId:B.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:g?()=>g.reportNow():void 0,refreshContextStatus:o?.contextDir?N:void 0,onRunActivity:E}).catch(te=>({status:"failed",error:te instanceof Error?te.message:String(te)}));B.action.type==="tracker_comment"&&v.status==="done"&&"result"in v&&typeof v.result?.commentId=="string"&&d.add(v.result.commentId),f.send(JSON.stringify({type:"action_result",actionId:B.actionId,...v}));let S=v.status!=="failed",H=!S&&"error"in v?v.error:void 0;S?r.info(`[exec] ${B.actionId} (${B.action.type}) \u2192 done`):r.warn(`[exec] ${B.actionId} (${B.action.type}) \u2192 FAILED: ${H??"?"}`),n({kind:"action",actionId:B.actionId,actionType:B.action.type,ok:S,...H?{error:H}:{}})}finally{p.delete(B.actionId)}}),f.on("close",(b,P)=>{let x=P?.toString("utf-8")??"";if(r.info(`[ws] closed code=${b}${x?` reason=${x}`:""}`),w.stop(),$.stop(),g?.stop(),G(),x==="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:b}),!c&&setTimeout(()=>{u=m()},2e3)}),f.on("error",b=>r.warn(`[ws] error: ${b.message}`)),f}return{stop(){c=!0,u.close()}}}async function Fi(t,e,r){try{let n=await J(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Yr(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 Zh(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?sn(e.root,o):Ie(t.projectId,r.name);if(Su(sn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await Qh().clone(zr(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 ey(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?sn(e.root,o):Ie(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Su(sn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Xh(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 ty(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=sn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Xa(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 ry(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 ot(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 ny(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 pc(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 xu(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}fe();re();nt();Ki();tt();eo();async function Du(t={profile:void 0}){let{cfg:e,profile:r}=Un(t.profile),n=M(e.projectId);n&&Gr(n),Qr(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Zr(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),en(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=an(Wi(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Mn("CLI_LOG",i,o);if(s.enabled){let u=new Zt(s);Gn(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=On(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=an(Wi(),".codepipe",r?an("profiles",r,"context"):"context");if(await Li(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Nu(()=>yo({cfg:e,secrets:n,contextDir:u,log:{info:m=>console.log(m),warn:m=>console.warn(m)}}),{log:{warn:m=>console.warn(m)}}),a||await Li(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 m=an(Wi(),".codepipe",r?an("profiles",r,"context-config"):"context-config");Kn(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=go(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(`
|
|
739
|
-
[${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>d("SIGINT")),process.on("SIGTERM",()=>d("SIGTERM")),await new Promise(()=>{})}kr();ke();fe();async function Hp(t={profile:void 0}){let e=Te(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=lo(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 J(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=ge(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`)")}mn();import{readFileSync as Nk}from"node:fs";q();ke();nt();Io();Ut();wt();Lt();fe();re();function pe(t){throw new Error(t)}function de(t,e){return(typeof t!="string"||t.trim().length===0)&&pe(`config: '${e}' must be a non-empty string`),t.trim()}function hn(t,e){if(t==null)return;typeof t!="string"&&pe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Ok(t){(!t||typeof t!="object")&&pe("config: expected a JSON object");let e=t,r=de(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||pe("config: 'hubUrl' must start with http(s)://");let n=de(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&pe("config: 'project' is required");let i=o,s=de(i.id,"project.id");At.test(s)||pe("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=de(i.name,"project.name"),c=de(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&pe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||pe("config: 'project.repos' must be an array");let p=l.map((h,k)=>{(!h||typeof h!="object")&&pe(`config: project.repos[${k}] must be an object`);let C=h,G=de(C.host,`project.repos[${k}].host`);G!=="github"&&G!=="bitbucket"&&G!=="gitlab"&&pe(`config: project.repos[${k}].host must be 'github', 'bitbucket' or 'gitlab'`);let T={name:de(C.name,`project.repos[${k}].name`),host:G,owner:de(C.owner,`project.repos[${k}].owner`),repoName:de(C.repoName,`project.repos[${k}].repoName`)},_=hn(C.defaultBranch,`project.repos[${k}].defaultBranch`);_&&(T.defaultBranch=_);let F=hn(C.mountAs,`project.repos[${k}].mountAs`);return F&&(T.mountAs=F),T}),d=i.contextRepo;(!d||typeof d!="object")&&pe("config: 'project.contextRepo' is required");let u=d,m=hn(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&pe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:de(u.owner,"project.contextRepo.owner"),name:hn(u.name,"project.contextRepo.name")??et(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:f}},w=hn(i.youtrackProjectKey,"project.youtrackProjectKey");w&&(y.project.youtrackProjectKey=w),i.index!==void 0&&(typeof i.index!="boolean"&&pe("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&pe("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let $=e.secrets;if($!==void 0){(typeof $!="object"||$===null)&&pe("config: 'secrets' must be an object");let h=$,k={};if(h.github){let C=h.github;k.github={token:de(C.token,"secrets.github.token")}}if(h.bitbucket){let C=h.bitbucket;k.bitbucket={email:de(C.email,"secrets.bitbucket.email"),apiToken:de(C.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let C=h.gitlab;k.gitlab={token:de(C.token,"secrets.gitlab.token")}}if(h.youtrack){let C=h.youtrack;k.youtrack={url:de(C.url,"secrets.youtrack.url").replace(/\/$/,""),token:de(C.token,"secrets.youtrack.token")}}if(h.contextWrite){let C=h.contextWrite;k.contextWrite={token:de(C.token,"secrets.contextWrite.token")}}y.secrets=k}return y}async function Dk(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Uk(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await gt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await ht(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Jn(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(i)throw new Error(`Bitbucket: ${i}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await yt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await $t({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Ad(t){let e=!t.configPath||t.configPath==="-"?await Dk():Nk(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){pe(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=Ok(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 Uk(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 $r(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Qt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){pe(`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 vt(o,i,a)}catch(u){if(u instanceof O&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await J(o,i,s.id);else if(u instanceof O)pe(`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(X(d),rt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ye(s.id)}`),Ot(s.id,Ve(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 on(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`)}ke();re();import{cancel as _d,intro as Nd,isCancel as Od,log as ds,outro as Lk,password as Dd}from"@clack/prompts";async function Bk(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Ud(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Bk(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Nd("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),ds.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Dd({message:"Claude OAuth token"});Od(i)&&(_d("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Ka({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Bn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Te(t.profile);if(!e){Nd(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),ds.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Dd({message:"Claude OAuth token"});Od(i)&&(_d("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=M(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},X(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(ds.success("Claude OAuth token saved."),Lk("It will be sealed into job bundles when a SANDBOX (re)connects."))}q();ke();nt();Io();Ut();Co();fe();re();import{cancel as Mk,confirm as Gk,intro as Fk,isCancel as Ld,log as he,outro as Hk,select as Bd,text as Ct}from"@clack/prompts";function Md(t){Mk(t),process.exit(1)}function Cr(t){return Ld(t)&&Md("aborted"),t}function yn(t){return Ld(t)&&Md("aborted"),typeof t=="string"?t:""}async function Kk(t,e){let r=Cr(await Bd({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=yn(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=yn(await Ct({message:"Context Repo name",placeholder:et(t),initialValue:et(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Gd(t={profile:void 0}){let e=Te(t.profile);Fk(`codepipe project add \u2192 ${e.hubUrl}`);let r=Cr(await Ct({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>At.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Cr(await Ct({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=Cr(await Bd({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=Cr(await Ct({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Cr(await Gk({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=yn(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:$=>!$||!$.trim()||Ee($)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!u)break;let m=Ee(u);he.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=yn(await Ct({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:$=>$.trim().length>0?void 0:"required"})).trim(),y=yn(await Ct({message:"default branch (optional)",placeholder:"main"})).trim(),w={name:f,host:m.host,owner:m.owner,repoName:m.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 Kk(r,a),p=M(e.projectId);he.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let d;try{d=await $r(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??Qt(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>he.message(u),warn:u=>he.warn(u)}})}catch(u){he.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=d,he.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await vt(e.hubUrl,e.cliToken,c);he.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Ot(r,Ve(c,s,p?.youtrack?.url),{info:m=>he.message(m),warn:m=>he.warn(m)}),u.contextRepo&&(he.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),he.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&he.error(` error: ${u.provisioningError}`),Hk("done")}catch(u){u instanceof O?(he.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&he.message(JSON.stringify(u.payload,null,2))):he.error(u instanceof Error?u.message:String(u)),process.exit(1)}}kr();ke();fe();re();tt();mn();import{existsSync as Wk,rmSync as Yk}from"node:fs";import{confirm as qk,intro as Vk,isCancel as Jk,log as Pt,outro as zk,spinner as Xk}from"@clack/prompts";function ze(t){Pt.error(t),process.exit(1)}var Fd=t=>t.trim().replace(/\/+$/,"");async function Hd(t){Vk("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Re()?.spec.projectId??void 0;e||ze("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Oe(e);r||ze(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Fd(r.hubUrl),o=r.projectId,i=Fd(t.hub);i.startsWith("http")||ze("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&ze(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let $=Xk();$.start(`reading project ${o} from ${n}\u2026`);try{l=await J(n,r.cliToken,o),$.stop(`read project ${o} (${l.name})`)}catch(h){throw $.stop("could not read the source project",1),h instanceof O&&ze(`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||ze(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let p=M(o),d=(t.account??r.accountEmail??await Tr()).trim().toLowerCase();if(Pt.message(`move project '${o}'
|
|
743
|
+
`;return await ot(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:i.id}}async createIssue(e){let r=new Date().toISOString(),n=await Rc(this.contextDir,this.config.prefix,o=>this.renderNewIssueFiles(o,e,r),o=>`tracker(${o}): create issue`);return{id:n,key:n}}async editIssue(e,r){await this.mutateRecord(e,n=>({...n,...r.title!==void 0?{title:r.title}:{}}),r.body)}async applyLink(e,r,n){let o=r==="subtask_of"?"subtask":"depends_on";await this.mutateRecord(e,i=>{let s=i.links.filter(a=>!(a.type===o&&a.targetKey===n));return s.push({type:o,targetKey:n}),{...i,links:s}})}async fetchStateFields(e){return[{name:"Status",values:Qo.statusColumns}]}async mutateRecord(e,r,n){let o=Kr(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Wr(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Br(e),content:vi(i)},...no(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await ot(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:En,status:r.targetStatus,links:[],created:n,updated:n},i=Wr(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Br(e),content:vi(o)},...no(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function Bl(t,e){let r=ue(t,`tasks/${e}/comments.jsonl`);if(!$h(r))return[];let n=[];for(let o of vh(r,"utf-8").split(`
|
|
744
|
+
`)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}zn();function Ni(t){if(!t)return"youtrack";try{let e=Fl(t,"project.yaml");return Ml(e)&&Hl(Gl(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Je(t){let e=Ni(t.contextDir);if(e==="internal"){let n=t.contextDir;if(!n)return{ok:!1,kind:e,error:"internal tracker: no Context Repo clone on this CLI"};let o=vc(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Sh(n);return i?{ok:!0,kind:e,provider:new rn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=ol();return r?{ok:!0,kind:e,provider:new tn(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Sh(t){try{let e=Fl(t,"project.yaml");if(!Ml(e))return null;let r=Hl(Gl(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var io=new Map;async function so(t,e){let n=(io.get(t)??Promise.resolve()).catch(()=>{}).then(e);io.set(t,n);try{return await n}finally{io.get(t)===n&&io.delete(t)}}async function Kl(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;qr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return W("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return so(`${i}/${r.name}`,async()=>{let s=await Jr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{commit:c}=await Dc(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 ne({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 W("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return so(`${i}/${r.name}`,async()=>{let s=await Jr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{commit:c,pushed:l}=await Uc(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ne({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return W("no repo spec");let i=De(r),s=await i.createPullRequest(r,e);return ne({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return W("no repo spec");let i=De(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ne({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return W("no repo spec");let i=De(r);return await i.closePR(r,e.prNumber,e.comment),ne({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return W("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return so(`${i}/${r.name}`,async()=>{let s=await Jr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{mergedSha:c}=await Lc(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ne({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return W("no repo spec");let i=t.cloneUrlOverride??zr(r),a=(await Bc(i)).filter(p=>Mc(p,e.issueKey)),c=De(r),l=null;if(c.findOpenPrByBranch)for(let p of a){let f=await c.findOpenPrByBranch(r,p).catch(()=>null);if(f){l={number:f.number,url:f.url};break}}return ne({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return W("no repo spec");let i=De(r);return await i.addPRComment(r,e.prNumber,e.body),ne({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=Je({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ne({issueId:t.trackerIssueId,newStatus:e.newStatus})):W("no tracker_issue_id provided"):W(i.error)}case"tracker_comment":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);if(!t.trackerIssueId)return W("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ne({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);if(!e.projectKey)return W("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ne({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return W(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ne({applied:s})}case"set_project_setting":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=await Nl(t.contextDir,e.edits);return ne({files:i.files})}case"tracker_edit":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);if(!t.contextDir)return W("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await oo(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ne({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=await Ul(t.contextDir,e);return ne({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=await Dl(t.contextDir,e);return ne({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ne({reported:!0})):W("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return W("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ne({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return W("no project workspace on this CLI");if(!r)return W("no repo spec");if(!t.onRunActivity)return W("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Fn(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(d=>d.file===`actions/${e.actionId}.yml`);return W(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Vs(c,e.input);if(!l.ok)return W(l.error);let p=rc(t.contextDir),f=M(e.projectId),u={};return f?.github?.token&&(u.GH_TOKEN=f.github.token),f?.gitlab?.token&&(u.GITLAB_TOKEN=f.gitlab.token),f?.bitbucket&&(u.BITBUCKET_EMAIL=f.bitbucket.email,u.BITBUCKET_API_TOKEN=f.bitbucket.apiToken),f?.youtrack&&(u.YOUTRACK_URL=f.youtrack.url,u.YOUTRACK_TOKEN=f.youtrack.token),so(`${e.projectId}/${r.name}`,async()=>{await Jr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=Ie(e.projectId,r.name,t.baseDir),d=await El({cwd:m,def:c,input:l.values,variables:p,secrets:f?.secrets??{},credEnv:u,onEvent:h=>i(e.runId,h)});return ne({runId:e.runId,status:d.status,exitCode:d.exitCode,...d.failedStep?{failedStep:d.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=_l(t.contextDir,e.path);return ne({path:e.path,...i})}default:return W(`unsupported action type: ${e.type}`)}}catch(i){return W(i instanceof Error?i.message:String(i))}}function ne(t){return{status:"done",result:t}}function W(t){return{status:"failed",error:t}}Ce();Di();fe();re();import{existsSync as au,readFileSync as cu}from"node:fs";import{join as lu}from"node:path";async function uu(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=ye(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");co(e.farmId,e.farmPublicKey);let s=M(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await J(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=lu(r,"project.yaml"),m=lu(r,"regimen.yaml");au(u)&&au(m)?c={projectYaml:cu(u,"utf-8"),regimenYaml:cu(m,"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=it(e.farmPublicKey,JSON.stringify(l));ao(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await uo(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:p});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:o(f.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}Ce();Ne();Ce();import{homedir as Dh}from"node:os";import{existsSync as Uh,mkdirSync as Lh,readFileSync as Bh,writeFileSync as Mh}from"node:fs";import{dirname as Gh,join as Fh}from"node:path";function Bi(){return K("RUNNER_PINS")??Fh(Dh(),".codepipe","runner-pins.json")}function pu(){let t=Bi();if(!Uh(t))return{};try{return JSON.parse(Bh(t,"utf-8"))}catch{return{}}}function Hh(t){let e=Bi();Lh(Gh(e),{recursive:!0}),Mh(e,JSON.stringify(t,null,2)+`
|
|
745
|
+
`,{mode:384})}function Kh(t){return pu()[t]}function Mi(t,e){let r=pu();r[t]=e,Hh(r)}function du(t,e){let r=ye(e),n=Kh(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 ${Bi()}.`);return r}fe();re();var mu=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function fu(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:mu(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 Wh={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:mu(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)=>fu(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>fu(t,e,r,"remove-token")},gu={api:Wh,fetchProject:J,provisionOnRunner:ql,teardownOnRunner:Vl};async function hu(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(ye(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");du(e.runnerId,e.runnerPublicKey);let i=M(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 yu(t,e,r,n=gu){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 hu(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=it(e.runnerPublicKey,JSON.stringify(l));Mi(e.runnerId,e.fingerprint),r.info(`[ghr] ${c.length} registration token(s) sealed for runner host ${e.runnerName} \u2014 handing off`);let f=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:p});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:f.ok,...f.runners?{runners:f.runners}:{},...f.error?{error:f.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function wu(t,e,r,n=gu){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 hu(t,e,n),a=[];for(let f of s)try{a.push({owner:f.owner,repo:f.repoName,removeToken:await n.api.mintRemoveToken(i,f.owner,f.repoName)})}catch(u){r.warn(`[ghr] remove-token for ${f.owner}/${f.repoName} failed (${u instanceof Error?u.message:u}) \u2014 the runner host will force-remove`),a.push({owner:f.owner,repo:f.repoName})}let c={projectId:t.projectId,runners:a},l=it(e.runnerPublicKey,JSON.stringify(c));Mi(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))}}fe();q();Ce();re();var ku=16*1024;function Yh(t){return Se.test(t)?pt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Se}`}function bu(t,e,r,n){let o=Yh(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(ir(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>ku)return{ok:!1,detail:`secret value too large (max ${ku} chars)`};try{return Ga(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function $u(t,e){try{return Fa(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}re();wt();var fo=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=De(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 Dt){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=De(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=qh(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function qh(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}q();var mo=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 r=(this.options.resolveProvider??(()=>Je({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let k=e.stageField?{stageField:e.stageField}:{},C=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},T=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(T){let _=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[F,E]=await Promise.all([_.length>0?r.listIssues({projectKey:e.projectKey,columns:_,...k,...C}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...k})]),g=new Map;for(let N of[...F,...E])g.set(N.id,N);o=[...g.values()]}else{let _=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:_,...k,...C})}}catch(k){this.log.warn(`[yt-sync] listIssues failed: ${k instanceof Error?k.message:String(k)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let k of o){if(s.add(k.id),a.has(k.status))continue;let C=await xu(r,k.id,e.sinceMs,this.log);C&&i.set(k.id,C)}let c=[];for(let k of e.offBoardIssueIds){if(s.has(k))continue;let C=await xu(r,k,e.sinceMs,this.log);if(C&&C.length>0&&i.set(k,C),e.requireAssignee||C&&C.length>0){let G=await zh(r,k,e.stageField,this.log);if(G)c.push(G);else if(C&&C.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(k=>!a.has(k.status)),{attachmentsByIssue:p,attachmentKeys:f}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let u=[...l,...c].map(k=>({issue:k,comments:i.get(k.id)??[],attachments:p.get(k.id)??[]}));try{await oo(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let k of f)this.shippedAttachments.add(k)}catch(k){let C=k instanceof Error?k.message:String(k);this.abandonTick(`context task sync failed: ${C}`);return}let m=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[k,C]of i){let G=C.filter(_=>!m(_.id));if(G.length===0)continue;d.push({issueId:k,comments:G.map(Vh)});let T=G.flatMap(_=>{let F=qt(_.body);return F?[{commentId:_.id,author:_.author,name:F.name,args:F.args,createdAt:_.createdAt}]:[]});T.length>0&&h.push({issueId:k,commands:T})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(vu),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(vu)}:{},observedAtMs:n};this.send(y);let b=d.reduce((k,C)=>k+C.comments.length,0),w=h.reduce((k,C)=>k+C.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${b} commands=${w} (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 f=`${s.id}:${p.id}`;if(this.shippedAttachments.has(f))continue;let u;try{u=await n.downloadAttachment(p.url)}catch(d){this.log.warn(`[yt-sync] attachment ${p.name} (${s.id}) download failed: ${d instanceof Error?d.message:String(d)}`);continue}let m=Jh(p.name);l.has(m)&&(m=`${p.id}-${m}`),l.add(m),c.push({name:m,contentBase64:u.toString("base64")}),i.push(f)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function vu(t){let{description:e,...r}=t;return r}function Vh(t){let{body:e,...r}=t;return r}function Jh(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 zh(t,e,r,n){try{return await t.getIssue(e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function xu(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Gi="npm i -g @code-partner/codepipe@latest";function go(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${xe} (protocol ${Fe})`);let n=d=>e.onEvent?.(d),o=e.workspace;o?.contextDir&&ic(o.contextDir,r);let i=Su("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Su("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,l=!1,p=new Set,f=new Set,u=m();function m(){let d=lo(t.hubUrl,t.cliToken),h=null,y=new fo(i,$=>{d.readyState===d.OPEN&&d.send(JSON.stringify($))},r),b=new mo(s,$=>{d.readyState===d.OPEN&&d.send(JSON.stringify($))},r,{contextDir:o?.contextDir??null,isSelfComment:$=>f.has($)}),w=null,k=async()=>{try{let $={trackerProvider:Ni(o?.contextDir??null)};try{let j=await J(t.hubUrl,t.cliToken,t.projectId);$={...$,repos:j.repos,contextRepo:j.contextRepo}}catch(j){r.warn(`[readiness] could not fetch project summary for push checks: ${j instanceof Error?j.message:String(j)}`)}let P=await vl(t.projectId,$);if(d.readyState!==d.OPEN)return;let x={type:"cli_readiness",projectId:t.projectId,ready:P.ready,checks:P.checks,creds:P.creds,secretNames:Ha(t.projectId),checkedAt:P.checkedAt};if(d.send(JSON.stringify(x)),P.ready)r.info("[readiness] ready");else{let j=P.checks.filter(B=>!B.ok).map(B=>`${B.name}(${B.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${j.join(", ")}`)}}catch($){r.warn(`[readiness] check failed: ${$ instanceof Error?$.message:String($)}`)}},C=()=>{k(),w=setInterval(()=>void k(),a),typeof w.unref=="function"&&w.unref()},G=()=>{w&&(clearInterval(w),w=null)},T=150,_=new Map,F=$=>{let P=_.get($);if(!P||(P.timer&&clearTimeout(P.timer),_.delete($),P.events.length===0||d.readyState!==d.OPEN))return;let x={type:"run_activity",projectId:t.projectId,runId:$,events:P.events};d.send(JSON.stringify(x))},E=($,P)=>{let x=_.get($);if(x||(x={events:[],timer:null},_.set($,x)),x.events.push(P),P.kind==="result"){F($);return}x.timer||(x.timer=setTimeout(()=>F($),T),x.timer.unref?.())},g=o?.contextDir?new Hn(o.contextDir,t.projectId,$=>{d.readyState===d.OPEN&&d.send(JSON.stringify($))},r):null,N=async()=>{let $=o?.contextDir;if(!$)throw new Error("no context repo clone on this CLI");let P;try{P=(await J(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let x=await Ec($,t.projectId,P,r);return d.readyState===d.OPEN&&d.send(JSON.stringify(x)),x};return d.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let $=Xa(t.projectId),P=K("ORIGIN")==="farm"?"farm":"local",x=K("FARM_ID"),j=t.accountEmail??$.email,B;try{let S=Tl(t.projectId);S&&(B=S.publicKey,r.info(`[cred-channel] key fingerprint: ${S.fingerprint}`))}catch(S){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${S instanceof Error?S.message:String(S)}`)}let v={type:"register",projectId:t.projectId,platformVersion:xe,protocolVersion:Fe,accountId:$.accountId,accountLabel:$.label,origin:P,inFlightActionIds:[...p],...j?{accountEmail:j}:{},...P==="farm"&&x?{farmId:x}:{},...B?{sealPublicKey:B}:{}};d.send(JSON.stringify(v))}),d.on("message",async $=>{let P=$.toString("utf-8");if(P==="pong"||P==="ping")return;let x;try{x=JSON.parse(P)}catch{return}if(!x||typeof x!="object")return;let j=x.type;if(j==="registered"){let v=x;if(v.ok){if(r.info(`[ws] registered for project ${v.projectId}`),n({kind:"registered",projectId:v.projectId??t.projectId}),y.start(),g?.start(),C(),Fi(t,o,r),o?.contextDir)try{let S=qn(o.contextDir,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.outdated&&(r.warn(`[ctx] context format outdated: v${S.templateVersion} \u2192 v${S.currentVersion}`+(S.missingPaths.length>0?` (missing: ${S.missingPaths.join(", ")})`:"")),l||(l=!0,N().catch(()=>{})))}catch(S){r.warn(`[ctx] context-format detect failed (non-fatal): ${S instanceof Error?S.message:String(S)}`)}}else r.warn(`[ws] register rejected: ${v.reason??"unknown"}`),n({kind:"register_rejected",reason:v.reason??"unknown"}),c=!0,d.close();return}if(j==="hello"){let v=x;h=Tn(v.protocolVersion);let S=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${v.platformVersion} (protocol ${v.protocolVersion}) \u2014 ${S}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${xe}, protocol ${Fe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Gi}`),n({kind:"incompatible",hubVersion:typeof v.platformVersion=="string"?v.platformVersion:null,hubProtocol:typeof v.protocolVersion=="number"?v.protocolVersion:null,updateCommand:Gi}));return}if(j==="tracking_targets"){y.setTargets(x.targets);return}if(j==="youtrack_sync_request"){b.setRequest(x);return}if(j==="youtrack_force_sync"){b.forceSync();return}if(j==="sync_local"){await ty(x,o,d,r);return}if(j==="provision_repo"){let v=x;r.info(`[repo] provision_repo: ${v.repo.name} (${v.repo.host}:${v.repo.owner}/${v.repo.repoName})`),await Zh(t,o,v.repo,r),await Fi(t,o,r);return}if(j==="remove_repo"){let v=x;r.info(`[repo] remove_repo: ${v.repoName}${v.purge?" (purge)":""}`),await Fi(t,o,r),v.purge&&ey(t,o,v.repoName,r);return}if(j==="context_write"){await ry(x,o,d,r);return}if(j==="adr_promote"){await ny(x,o,d,r);return}if(j==="cred_update"){let v=x,S=M(t.projectId),H=S?.sealKey?await Il(t.projectId,v.kind,v.sealed,S.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},te={type:"cred_update_result",updateId:v.updateId,projectId:t.projectId,ok:H.ok,...H.detail?{detail:H.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(te)),H.ok?(r.info(`[cred] ${v.kind} replaced${H.detail?` \u2014 ${H.detail}`:""}`),k()):r.warn(`[cred] ${v.kind} replacement rejected: ${H.detail??"unknown"}`);return}if(j==="move_to_farm"){let v=x;r.info(`[farm-move] request to move ${t.projectId} onto farm ${v.farmName} (${v.farmId})`);let S=await uu(t,v,o?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.ok?r.info(`[farm-move] done \u2014 farm daemon ${S.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${S.error??"unknown error"}`);return}if(j==="gh_runner_setup"){let v=x;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let S=await yu(t,v,r);d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners connected on ${v.runnerName}`):r.warn(`[ghr] setup failed: ${S.error??"see per-repo statuses"}`);return}if(j==="gh_runner_teardown"){let v=x;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let S=await wu(t,v,r);d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners disconnected from ${v.runnerName}`):r.warn(`[ghr] teardown failed: ${S.error??"unknown error"}`);return}if(j==="tracker_fields_request"){let v=x,S={type:"tracker_fields_result",requestId:v.requestId,projectId:t.projectId,ok:!1},H=Je({contextDir:o?.contextDir??null});if(!H.ok)S.error=H.error;else try{S.fields=await H.provider.fetchStateFields(v.projectKey),S.ok=!0}catch(te){S.error=te instanceof Error?te.message:String(te)}d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.ok||r.warn(`[yt-fields] listing failed: ${S.error??"unknown"}`);return}if(j==="project_secret_update"||j==="project_secret_delete"){let v=x,S;if(v.type==="project_secret_update"){let te=M(t.projectId);S=te?.sealKey?bu(t.projectId,v.name,v.sealed,te.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else S=$u(t.projectId,v.name);let H={type:"project_secret_update_result",updateId:v.updateId,projectId:t.projectId,ok:S.ok,...S.detail?{detail:S.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(H)),S.ok?(r.info(`[secret] ${v.name} ${v.type==="project_secret_update"?"saved":"deleted"}`+(S.detail?` \u2014 ${S.detail}`:"")),k()):r.warn(`[secret] ${v.name} rejected: ${S.detail??"unknown"}`);return}if(j==="sandbox_keys"){let v=M(t.projectId);if(!v){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let S=Xt(t.projectId),H=Wc(x,v,S,r);for(let te of H)d.readyState===d.OPEN&&d.send(JSON.stringify(te));return}if(j!=="dispatch_action")return;let B=x;if(h===!1){let v=`refused: HUB protocol incompatible with CLI v${xe} (protocol ${Fe})`;d.send(JSON.stringify({type:"action_result",actionId:B.actionId,status:"failed",error:v})),r.warn(`[exec] ${B.actionId} (${B.action.type}) \u2192 REFUSED: ${v}`),r.warn(`[exec] update the CLI to clear this: ${Gi}`),n({kind:"action",actionId:B.actionId,actionType:B.action.type,ok:!1,error:v});return}p.add(B.actionId);try{let v=await Kl({action:B.action,repo:B.repo,trackerIssueId:B.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:g?()=>g.reportNow():void 0,refreshContextStatus:o?.contextDir?N:void 0,onRunActivity:E}).catch(te=>({status:"failed",error:te instanceof Error?te.message:String(te)}));B.action.type==="tracker_comment"&&v.status==="done"&&"result"in v&&typeof v.result?.commentId=="string"&&f.add(v.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:B.actionId,...v}));let S=v.status!=="failed",H=!S&&"error"in v?v.error:void 0;S?r.info(`[exec] ${B.actionId} (${B.action.type}) \u2192 done`):r.warn(`[exec] ${B.actionId} (${B.action.type}) \u2192 FAILED: ${H??"?"}`),n({kind:"action",actionId:B.actionId,actionType:B.action.type,ok:S,...H?{error:H}:{}})}finally{p.delete(B.actionId)}}),d.on("close",($,P)=>{let x=P?.toString("utf-8")??"";if(r.info(`[ws] closed code=${$}${x?` reason=${x}`:""}`),y.stop(),b.stop(),g?.stop(),G(),x==="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:$}),!c&&setTimeout(()=>{u=m()},2e3)}),d.on("error",$=>r.warn(`[ws] error: ${$.message}`)),d}return{stop(){c=!0,u.close()}}}async function Fi(t,e,r){try{let n=await J(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Yr(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 Zh(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?sn(e.root,o):Ie(t.projectId,r.name);if(Ru(sn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await Qh().clone(zr(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 ey(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?sn(e.root,o):Ie(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Ru(sn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Xh(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 ty(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=sn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Qa(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 ry(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 ot(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 ny(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 dc(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 Su(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}fe();re();nt();Ki();tt();eo();async function Uu(t={profile:void 0}){let{cfg:e,profile:r}=Un(t.profile),n=M(e.projectId);n&&Gr(n),Qr(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Zr(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),en(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=an(Wi(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Mn("CLI_LOG",i,o);if(s.enabled){let u=new Zt(s);Gn(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=On(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=an(Wi(),".codepipe",r?an("profiles",r,"context"):"context");if(await Li(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Ou(()=>yo({cfg:e,secrets:n,contextDir:u,log:{info:m=>console.log(m),warn:m=>console.warn(m)}}),{log:{warn:m=>console.warn(m)}}),a||await Li(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 m=an(Wi(),".codepipe",r?an("profiles",r,"context-config"):"context-config");Kn(a.contextDir,m,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=go(e,{...a?{workspace:a}:{},onEvent:u=>{u.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),p=!1;function f(u){p||(p=!0,console.log(`
|
|
746
|
+
[${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}kr();ke();fe();async function Hp(t={profile:void 0}){let e=Te(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=lo(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 f=JSON.parse(p);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,p)=>{s.push(`close:${l}:${p?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of 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 J(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=ge(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`)")}mn();import{readFileSync as Bk}from"node:fs";q();ke();nt();Io();Ut();wt();Lt();fe();re();function pe(t){throw new Error(t)}function de(t,e){return(typeof t!="string"||t.trim().length===0)&&pe(`config: '${e}' must be a non-empty string`),t.trim()}function hn(t,e){if(t==null)return;typeof t!="string"&&pe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Mk(t){(!t||typeof t!="object")&&pe("config: expected a JSON object");let e=t,r=de(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||pe("config: 'hubUrl' must start with http(s)://");let n=de(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&pe("config: 'project' is required");let i=o,s=de(i.id,"project.id");At.test(s)||pe("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=de(i.name,"project.name"),c=de(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&pe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||pe("config: 'project.repos' must be an array");let p=l.map((w,k)=>{(!w||typeof w!="object")&&pe(`config: project.repos[${k}] must be an object`);let C=w,G=de(C.host,`project.repos[${k}].host`);G!=="github"&&G!=="bitbucket"&&G!=="gitlab"&&pe(`config: project.repos[${k}].host must be 'github', 'bitbucket' or 'gitlab'`);let T={name:de(C.name,`project.repos[${k}].name`),host:G,owner:de(C.owner,`project.repos[${k}].owner`),repoName:de(C.repoName,`project.repos[${k}].repoName`)},_=hn(C.defaultBranch,`project.repos[${k}].defaultBranch`);_&&(T.defaultBranch=_);let F=hn(C.mountAs,`project.repos[${k}].mountAs`);return F&&(T.mountAs=F),T}),f=i.contextRepo;(!f||typeof f!="object")&&pe("config: 'project.contextRepo' is required");let u=f,m=hn(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&pe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:m,owner:de(u.owner,"project.contextRepo.owner"),name:hn(u.name,"project.contextRepo.name")??et(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:d}},y=hn(i.youtrackProjectKey,"project.youtrackProjectKey");y&&(h.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&pe("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&pe("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites);let b=e.secrets;if(b!==void 0){(typeof b!="object"||b===null)&&pe("config: 'secrets' must be an object");let w=b,k={};if(w.github){let C=w.github;k.github={token:de(C.token,"secrets.github.token")}}if(w.bitbucket){let C=w.bitbucket;k.bitbucket={email:de(C.email,"secrets.bitbucket.email"),apiToken:de(C.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let C=w.gitlab;k.gitlab={token:de(C.token,"secrets.gitlab.token")}}if(w.youtrack){let C=w.youtrack;k.youtrack={url:de(C.url,"secrets.youtrack.url").replace(/\/$/,""),token:de(C.token,"secrets.youtrack.token")}}if(w.contextWrite){let C=w.contextWrite;k.contextWrite={token:de(C.token,"secrets.contextWrite.token")}}h.secrets=k}return h}async function Gk(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Fk(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await gt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await ht(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Jn(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(i)throw new Error(`Bitbucket: ${i}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await yt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await $t({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Ad(t){let e=!t.configPath||t.configPath==="-"?await Gk():Bk(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){pe(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=Mk(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 Fk(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 $r(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Qt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){pe(`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 vt(o,i,a)}catch(u){if(u instanceof O&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await J(o,i,s.id);else if(u instanceof O)pe(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let f={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(X(f),rt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ye(s.id)}`),Ot(s.id,Ve(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 on(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`)}ke();re();import{cancel as _d,intro as Nd,isCancel as Od,log as ds,outro as Hk,password as Dd}from"@clack/prompts";async function Kk(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Ud(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Kk(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Nd("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),ds.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Dd({message:"Claude OAuth token"});Od(i)&&(_d("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Wa({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Bn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Te(t.profile);if(!e){Nd(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),ds.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Dd({message:"Claude OAuth token"});Od(i)&&(_d("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=M(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},X(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(ds.success("Claude OAuth token saved."),Hk("It will be sealed into job bundles when a SANDBOX (re)connects."))}q();ke();nt();Io();Ut();Co();fe();re();import{cancel as Wk,confirm as Yk,intro as qk,isCancel as Ld,log as he,outro as Vk,select as Bd,text as Ct}from"@clack/prompts";function Md(t){Wk(t),process.exit(1)}function Cr(t){return Ld(t)&&Md("aborted"),t}function yn(t){return Ld(t)&&Md("aborted"),typeof t=="string"?t:""}async function Jk(t,e){let r=Cr(await Bd({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=yn(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=yn(await Ct({message:"Context Repo name",placeholder:et(t),initialValue:et(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Gd(t={profile:void 0}){let e=Te(t.profile);qk(`codepipe project add \u2192 ${e.hubUrl}`);let r=Cr(await Ct({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>At.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Cr(await Ct({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=Cr(await Bd({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=Cr(await Ct({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Cr(await Yk({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=yn(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:b=>!b||!b.trim()||Ee(b)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!u)break;let m=Ee(u);he.message(`${m.host}: ${m.owner}/${m.repoName}`);let d=yn(await Ct({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:b=>b.trim().length>0?void 0:"required"})).trim(),h=yn(await Ct({message:"default branch (optional)",placeholder:"main"})).trim(),y={name:d,host:m.host,owner:m.owner,repoName:m.repoName};h&&(y.defaultBranch=h),a.push(y)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Jk(r,a),p=M(e.projectId);he.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await $r(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??Qt(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>he.message(u),warn:u=>he.warn(u)}})}catch(u){he.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=f,he.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await vt(e.hubUrl,e.cliToken,c);he.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Ot(r,Ve(c,s,p?.youtrack?.url),{info:m=>he.message(m),warn:m=>he.warn(m)}),u.contextRepo&&(he.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),he.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&he.error(` error: ${u.provisioningError}`),Vk("done")}catch(u){u instanceof O?(he.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&he.message(JSON.stringify(u.payload,null,2))):he.error(u instanceof Error?u.message:String(u)),process.exit(1)}}kr();ke();fe();re();tt();mn();import{existsSync as zk,rmSync as Xk}from"node:fs";import{confirm as Qk,intro as Zk,isCancel as eb,log as Pt,outro as tb,spinner as rb}from"@clack/prompts";function ze(t){Pt.error(t),process.exit(1)}var Fd=t=>t.trim().replace(/\/+$/,"");async function Hd(t){Zk("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Re()?.spec.projectId??void 0;e||ze("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Oe(e);r||ze(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Fd(r.hubUrl),o=r.projectId,i=Fd(t.hub);i.startsWith("http")||ze("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&ze(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let b=rb();b.start(`reading project ${o} from ${n}\u2026`);try{l=await J(n,r.cliToken,o),b.stop(`read project ${o} (${l.name})`)}catch(w){throw b.stop("could not read the source project",1),w instanceof O&&ze(`source HUB ${n} \u2192 ${w.status} ${w.message}. The source HUB must be reachable with a valid token to move a project.`),w}}l.contextRepo||ze(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let p=M(o),f=(t.account??r.accountEmail??await Tr()).trim().toLowerCase();if(Pt.message(`move project '${o}'
|
|
740
747
|
from : ${n} (profile ${e})
|
|
741
|
-
to : ${i} (profile ${s}, project ${a}, account ${
|
|
748
|
+
to : ${i} (profile ${s}, project ${a}, account ${f})
|
|
742
749
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
743
750
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
744
|
-
`+(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
|
|
745
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let
|
|
746
|
-
`)}async function ef(t,e,r,n,o){let i;try{i=await
|
|
747
|
-
${
|
|
748
|
-
or: /abort ${r} --reason "..."`}}function ys(t,e){let r=Pr(t);r[e]&&(delete r[e],Zd(t,r))}async function ms(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}: ${wn(n)} \u2014 check manually`)}}async function tf(t,e,r){let o=Pr(t.contextDir)[e];if(o){for(let i of o.repos){let s=kn(t.root,i.mountAs);if(!hs(kn(s,".git")))continue;let a=gs(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}: ${wn(p)} \u2014 check manually`)}}ys(t.contextDir,e)}}async function
|
|
751
|
+
`+(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 Qk({message:"Continue?",initialValue:!0});(eb(b)||!b)&&ze("aborted")}!c&&a===o&&Pt.warn(`source and destination share the same project id, so they share one secrets file (${Ye(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:m}=await Ir(i,f),d={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Pt.step(`registering project on ${i}\u2026`);let h;try{h=await vt(i,u,d)}catch(b){if(b instanceof O&&b.status===409){Pt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await J(i,u,a)}catch(w){throw w instanceof O&&ze(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if(b instanceof O&&b.status===403)ze(`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 O)ze(`target HUB \u2192 ${b.status} ${b.message}`);else throw b}Pt.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),rt({hubUrl:i,cliToken:u,projectId:a,accountEmail:m},s);let y={...p??{},hubUrl:i,cliToken:u,projectId:a};if(delete y.sandboxPins,X(y),Pt.success(`profile '${s}' \u2192 ${Ye(a)}`),c){let b=Be(s);zk(b)&&(Xk(b),Pt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}tb(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}ke();import{existsSync as fs,rmSync as nb,statSync as ob}from"node:fs";import{join as Oo,relative as ib,resolve as sb}from"node:path";import{cancel as ab,intro as Wd,isCancel as cb,log as ie,outro as Yd,text as Ht}from"@clack/prompts";import{simpleGit as qd}from"simple-git";Co();fe();re();tt();function $e(t){ab(t),process.exit(1)}function Kt(t){return cb(t)&&$e("aborted"),typeof t=="string"?t:""}async function Kd(t){try{let e=await qd(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function lb(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function ub(t,e){let r=M(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(lb(r,e)){ie.message(`reusing existing ${e} credentials`);return}if(ie.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Kt(await Ht({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Kt(await Ht({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Kt(await Ht({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}}X(r),ie.success(`saved ${e} credentials`)}async function Vd(t){let e=Te(t.profile);Wd(`codepipe repo add \u2192 project ${e.projectId}`);let r=Re()??void 0,n;try{n=(await J(e.hubUrl,e.cliToken,e.projectId)).repos}catch(w){$e(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await Kd(process.cwd());w?(o=process.cwd(),ie.message(`using the current directory (${w})`)):o=Kt(await Ht({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:k=>k.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(fs(o)&&ob(o).isDirectory()){i=sb(o);let w=await Kd(i);w||$e(`${i} is not a git repository (no origin remote)`);let k=Ee(w);k||$e(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=k,s=w,ie.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let w=Ee(o);w||$e(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,s=o,ie.message(`${a}: ${c}/${l}`)}let p=Kt(await Ht({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:w=>w.trim()?void 0:"required"})).trim();n.some(w=>w.name===p)&&$e(`a repo named "${p}" is already registered`);let f=Kt(await Ht({message:"default branch (optional)",placeholder:"main"})).trim(),u=p;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let w=ib(r.root,i);u=w===""?".":w}let m=Kt(await Ht({message:"mount_as (directory relative to the workspace root)",placeholder:u,initialValue:u})).trim()||u;n.some(w=>(w.mountAs??w.name)===m)&&$e(`mount_as "${m}" is already used by another repo`),await ub(e,a);let d={name:p,host:a,owner:c,repoName:l,mountAs:m,...f?{defaultBranch:f}:{}};if(!i){let w=r?Oo(r.root,m):Ie(e.projectId,p);if(fs(Oo(w,".git")))ie.message(`already cloned at ${w}`);else{ie.info(`cloning ${s} \u2192 ${w} \u2026`);try{await qd().clone(s,w),ie.success(`cloned into ${w}`)}catch(k){$e(`clone failed: ${k instanceof Error?k.message.trim():String(k)}
|
|
752
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await iu(e.hubUrl,e.cliToken,e.projectId,d)}catch(w){w instanceof O&&$e(`HUB \u2192 ${w.status} ${w.message}`),$e(w instanceof Error?w.message:String(w))}let{updated:y,errors:b}=Yr(e.projectId,h.repos,r?.contextDir);for(let w of y)ie.message(`updated ${w}`);for(let w of b)ie.warn(`could not update ${w.path}: ${w.error}`);ie.success(`added "${p}" \u2014 project now has ${h.repos.length} repo(s)`),Yd("done")}async function Jd(t){let e=Te(t.profile);Wd(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Re()??void 0,n;try{let c=(await J(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 su(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof O&&(a.status===404&&$e(`no repo named "${t.name}" in this project`),$e(`HUB \u2192 ${a.status} ${a.message}`)),$e(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Yr(e.projectId,o.repos,r?.contextDir);for(let a of i)ie.message(`updated ${a}`);for(let a of s)ie.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ie.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Oo(r.root,n):Ie(e.projectId,t.name);if(fs(Oo(a,".git")))try{nb(a,{recursive:!0,force:!0}),ie.message(`deleted local clone ${a}`)}catch(c){ie.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ie.message(`no local clone found to purge (${a})`)}ie.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Yd("done")}async function zd(t){let e=Te(t.profile),r;try{r=(await J(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}`)}}Eo();ss();import{existsSync as lf,mkdirSync as gb,readFileSync as hb,writeFileSync as yb}from"node:fs";import{homedir as wb}from"node:os";import{dirname as kb,join as uf}from"node:path";import*as Er from"node:readline";fe();re();tt();Eo();fe();import{existsSync as hs,readFileSync as pb,writeFileSync as db}from"node:fs";import{join as kn}from"node:path";import{simpleGit as gs}from"simple-git";var Xd=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],fb="apply-queue.json";function Qd(t){return kn(t,fb)}function Pr(t){let e=Qd(t);if(!hs(e))return{};try{return JSON.parse(pb(e,"utf-8"))}catch{return{}}}function Zd(t,e){db(Qd(t),JSON.stringify(e,null,2)+`
|
|
753
|
+
`)}async function ef(t,e,r,n,o){let i;try{i=await tu(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 m=t.spec.repos.find(b=>b.name===u.repoName);if(!m)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let d=kn(t.root,m.mountAs);if(!hs(kn(d,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await gs(d).status()).isClean())return{ok:!1,message:`${m.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:u,spec:m,dir:d})}let a=[];for(let u of s){let m=gs(u.dir),d=await mb(m),h=u.claimRepo;try{await m.fetch()}catch(w){return await ms(a,o),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${wn(w)}`}}let y=`origin/${h.baseRef}`,b;try{b=await Qn(m,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(w){return await ms(a,o),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${wn(w)}`}}a.push({git:m,dir:u.dir,mountAs:u.spec.mountAs,originalRef:d,branch:h.branchName,baseSha:y,deliveryCommit:b,startPoint:y})}let c=[];for(let u of a)try{if(n==="apply"){await u.git.checkout(["-B",u.branch,u.startPoint]),await u.git.raw([...Xd,"cherry-pick",u.deliveryCommit]);let m=(await u.git.revparse(["HEAD"])).trim();c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha,appliedSha:m})}else await u.git.checkout(["--detach",u.startPoint]),await u.git.raw([...Xd,"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(m){return await u.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await ms(a,o),{ok:!1,message:`apply failed in ${u.mountAs}: ${wn(m)} (rolled back all repos)`}}let l=Pr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Zd(t.contextDir,l);let p=c.map(u=>u.mountAs).join(", "),f=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${p}
|
|
754
|
+
${f}
|
|
755
|
+
or: /abort ${r} --reason "..."`}}function ys(t,e){let r=Pr(t);r[e]&&(delete r[e],Zd(t,r))}async function ms(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}: ${wn(n)} \u2014 check manually`)}}async function tf(t,e,r){let o=Pr(t.contextDir)[e];if(o){for(let i of o.repos){let s=kn(t.root,i.mountAs);if(!hs(kn(s,".git")))continue;let a=gs(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}: ${wn(p)} \u2014 check manually`)}}ys(t.contextDir,e)}}async function mb(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function wn(t){return t instanceof Error?t.message.trim():String(t)}var Do=uf(wb(),".codepipe","history"),rf=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],pf=500,nf=40;async function df(){let t=Re();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=M(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)),Gr(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=Pr(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
|
|
749
756
|
\u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
|
|
750
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=Er.createInterface({input:process.stdin,output:process.stdout,completer:
|
|
751
|
-
`))}async function
|
|
752
|
-
`)}`:" (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}
|
|
753
|
-
`),t.unread+=1,ks(t),t.rl.prompt(!0)}function ks(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var af=!1;function cf(t){af||(af=!0,
|
|
754
|
-
bye.`),setTimeout(()=>process.exit(0),150))}function
|
|
757
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=Er.createInterface({input:process.stdin,output:process.stdout,completer:bb,history:Mb(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};_c(s=>Wt(i,s)),i.daemon=go({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>Wt(i,s),warn:s=>Wt(i,s)},onEvent:s=>Nb(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),ks(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await $b(i,a)){cf(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,ks(i),o.prompt()}),o.on("close",()=>{cf(i)})}function bb(t){let e=rf.filter(r=>r.startsWith(t));return[e.length?e:rf,t]}async function $b(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return vb(),!1;case"/status":return await xb(t),!1;case"/tasks":return await Sb(t,n),!1;case"/task":return await Rb(t,n),!1;case"/sync":return await Tb(t),!1;case"/logs":return Ob(t,n),!1;case"/monitor":return Db(t),!1;case"/apply":return await of(t,n,"apply"),!1;case"/unstash":return await of(t,n,"unstash"),!1;case"/applied":return await Ib(t,n),!1;case"/abort":return await Cb(t,n),!1;case"/approve":return await sf(t,n,"approve"),!1;case"/merge":return await sf(t,n,"merge"),!1;case"/login":return Eb(t,n),!1;case"/secret":return jb(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function vb(){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(`
|
|
758
|
+
`))}async function xb(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=lf(uf(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function Sb(t,e){let r=Ub(e,"--phase");try{let n=await Zl(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){$n(n)}}async function Rb(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await eu(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){$n(n)}}async function Tb(t){let e=await fn(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 of(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await ef(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function Ib(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=Pr(t.ws.contextDir)[r],i=Lb(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),p,f;if(l>0?(p=c.slice(0,l),f=c.slice(l+1)):(f=c,p=o?.repos.length===1?Pb(t,o.repos[0].mountAs):s.length===1?s[0]:""),!p){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let u=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!u){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:p,url:f,number:Number(u[1])})}try{let c=await ru(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);ys(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){$n(c)}}async function sf(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await ou(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){$n(o)}}async function Cb(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=Bb(e,"--reason")||"local apply aborted";await tf(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await nu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){$n(o)}}function Pb(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Eb(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},X(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 jb(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(`
|
|
759
|
+
`)}`:" (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}Ab(t.secrets,n,i),X(t.secrets),Gr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}_b(t.secrets,n),X(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function Ab(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 _b(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 Nb(t,e){switch(e.kind){case"connected":t.connection="connecting",Wt(t,"[hub] connected");break;case"registered":t.connection="registered",Wt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",bn(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Wt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",bn(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":bn(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?Wt(t,`[hub] action ${e.actionType} done`):bn(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Wt(t,e){t.logBuffer.push(e),t.logBuffer.length>pf&&t.logBuffer.shift(),t.follow&&bn(t,e)}function Ob(t,e){let r=e[0];if(r==="follow"||r==="on"){ws(t,!0);return}if(r==="off"){ws(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(pf,Number(r)||nf)):nf,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 Db(t){ws(t,!t.follow)}function ws(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function bn(t,e){Er.cursorTo(process.stdout,0),Er.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
760
|
+
`),t.unread+=1,ks(t),t.rl.prompt(!0)}function ks(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var af=!1;function cf(t){af||(af=!0,Gb(t.rl),t.daemon.stop(),console.log(`
|
|
761
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function Ub(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Lb(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 Bb(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function $n(t){t instanceof O?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Mb(){if(!lf(Do))return[];try{return hb(Do,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Gb(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{gb(kb(Do),{recursive:!0}),yb(Do,r.slice().reverse().join(`
|
|
755
762
|
`)+`
|
|
756
|
-
`)}catch{}}kr();q();Ne();kr();ke();fe();mn();import{hostname as Ub}from"node:os";import{cancel as Lb,confirm as ff,intro as Bb,isCancel as hf,log as jr,multiselect as Mb,outro as mf,password as Gb,select as bs,text as $s}from"@clack/prompts";function vn(t){Lb(t),process.exit(1)}function Ar(t){return hf(t)&&vn("aborted"),t}function Uo(t){return hf(t)&&vn("aborted"),typeof t=="string"?t:""}function vs(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function gf(t,e){try{let{secret:r}=await po(t,e);return r}catch(r){throw r instanceof O&&r.status===404&&vn("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 Fb(t,e){if(Ar(await bs({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 Ui(t,e);if(o.length>0)return Ar(await Mb({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}));jr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){jr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Uo(await $s({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 xs(t){Bb("codepipe worker \u2014 set up this machine as a runner");let e=ge(t.profile);e&&(jr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Ar(await ff({message:"re-register this worker?",initialValue:!1}))||vn("keeping the existing registration"));let r=Oe(t.profile)??Oe(),n=Uo(await $s({message:"HUB URL",placeholder:Ge,initialValue:K("HUB_URL")??r?.hubUrl??Ge,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Ar(await bs({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 gf(n,a),jr.success("account-issued registration token minted");else if(i==="login"){let u=await Tr();a=(await Ir(n,u)).cliToken,s=await gf(n,a),jr.success("account-issued registration token minted")}else s=Uo(await Gb({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||vn("a registration token is required");let c=await Fb(n,a),l=Uo(await $s({message:"worker name",initialValue:Ub(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=Ar(await bs({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 Bt({hub:n,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),jr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Ar(await ff({message:"start the claim-loop now?",initialValue:!0}))){mf("registered. start later with `codepipe worker`.");return}mf("starting the claim-loop\u2026"),await pn(t.profile?{profile:t.profile}:{})}function Kb(){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 K("PROFILE")}var se=Kb();Pa(se);Aa();var ve=new Hb;ve.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(xe).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 df()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.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 Ad({configPath:t.config,skipVerify:t.skipVerify===!0}):await $d({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.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 Wa({...t,profile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.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 vd({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ve.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Du({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.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 dd({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.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 Ud({profile:se,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Hp({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.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 is({profile:se,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var yf=ve.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");yf.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??K("HUB_URL")??Oe(se)?.hubUrl??Ge,r=t.token??K("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&vs()){await xs({profile:se});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=K("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??K("WORKER_NAME"),i=t.llm??K("WORKER_LLM");await Bt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...se?{profile:se}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});yf.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ge(se)&&vs()){await xs({profile:se});return}await pn(se?{profile:se}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var wf=ve.command("project").description("Manage CodePipe projects");wf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Gd({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});wf.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 Hd({...t,cliProfile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Ss=ve.command("repo").description("Manage the project's git repositories");Ss.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 Vd({profile:se,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ss.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 Jd({profile:se,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ss.command("list").description("List the project's repos").action(async()=>{try{await zd({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.parseAsync();
|
|
763
|
+
`)}catch{}}kr();q();Ne();kr();ke();fe();mn();import{hostname as Fb}from"node:os";import{cancel as Hb,confirm as ff,intro as Kb,isCancel as hf,log as jr,multiselect as Wb,outro as mf,password as Yb,select as bs,text as $s}from"@clack/prompts";function vn(t){Hb(t),process.exit(1)}function Ar(t){return hf(t)&&vn("aborted"),t}function Uo(t){return hf(t)&&vn("aborted"),typeof t=="string"?t:""}function vs(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function gf(t,e){try{let{secret:r}=await po(t,e);return r}catch(r){throw r instanceof O&&r.status===404&&vn("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 qb(t,e){if(Ar(await bs({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 Ui(t,e);if(o.length>0)return Ar(await Wb({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}));jr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){jr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Uo(await $s({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 xs(t){Kb("codepipe worker \u2014 set up this machine as a runner");let e=ge(t.profile);e&&(jr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Ar(await ff({message:"re-register this worker?",initialValue:!1}))||vn("keeping the existing registration"));let r=Oe(t.profile)??Oe(),n=Uo(await $s({message:"HUB URL",placeholder:Ge,initialValue:K("HUB_URL")??r?.hubUrl??Ge,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Ar(await bs({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 gf(n,a),jr.success("account-issued registration token minted");else if(i==="login"){let u=await Tr();a=(await Ir(n,u)).cliToken,s=await gf(n,a),jr.success("account-issued registration token minted")}else s=Uo(await Yb({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||vn("a registration token is required");let c=await qb(n,a),l=Uo(await $s({message:"worker name",initialValue:Fb(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=Ar(await bs({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 Bt({hub:n,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),jr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Ar(await ff({message:"start the claim-loop now?",initialValue:!0}))){mf("registered. start later with `codepipe worker`.");return}mf("starting the claim-loop\u2026"),await pn(t.profile?{profile:t.profile}:{})}function Jb(){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 K("PROFILE")}var se=Jb();Ea(se);_a();var ve=new Vb;ve.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(xe).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 df()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.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 Ad({configPath:t.config,skipVerify:t.skipVerify===!0}):await $d({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.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 Ya({...t,profile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.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 vd({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ve.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Uu({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.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 dd({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.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 Ud({profile:se,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Hp({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.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 is({profile:se,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var yf=ve.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");yf.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??K("HUB_URL")??Oe(se)?.hubUrl??Ge,r=t.token??K("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&vs()){await xs({profile:se});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=K("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??K("WORKER_NAME"),i=t.llm??K("WORKER_LLM");await Bt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...se?{profile:se}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});yf.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ge(se)&&vs()){await xs({profile:se});return}await pn(se?{profile:se}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var wf=ve.command("project").description("Manage CodePipe projects");wf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Gd({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});wf.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 Hd({...t,cliProfile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Ss=ve.command("repo").description("Manage the project's git repositories");Ss.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 Vd({profile:se,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ss.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 Jd({profile:se,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ss.command("list").description("List the project's repos").action(async()=>{try{await zd({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.parseAsync();
|