@code-partner/codepipe 0.5.4-dev.159.g390b9fb → 0.5.4-dev.161.g4977c30
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 +134 -130
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var jf=Object.defineProperty;var R=(t,e)=>()=>(t&&(e=t(t=0)),e);var Af=(t,e)=>{for(var r in e)jf(t,r,{get:e[r],enumerable:!0})};var Te,Ge,Jo=R(()=>{"use strict";Te="0.5.4-dev.161.g4977c30",Ge="https://hub.dev.codepipe.dev"});function An(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=_f&&t<=Fe}var Fe,_f,Ds=R(()=>{"use strict";Jo();Fe=4,_f=4});var Us=R(()=>{"use strict";Jo()});function _n(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 Us(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 Ls(t,e=Ds){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 Bs(t,e=Ds){return e.filter(r=>r.version>t)}var He,Mr,Ds,Ms=I(()=>{"use strict";He=".codepipe-context.yaml",Mr=".devpipe-context.yaml",Ds=[{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 Gs=I(()=>{"use strict"});var Ef,u$,Fs=I(()=>{"use strict";Ef=[{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"]}],u$=Ef.flatMap(t=>t.phases)});function At(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Hs,Jo=I(()=>{"use strict";Hs=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});var Ke,_n,jf,zo,Ks,Xo=I(()=>{"use strict";Ke="opus",_n="sonnet",jf="haiku",zo=[Ke,_n,jf],Ks={analyze:Ke,implement:Ke,"resolve-conflict":Ke,rework:Ke,estimate:_n,build:_n,"code-review":Ke,draft:_n,index:Ke,backfill:Ke,analysis:Ke,chat:Ke}});function pt(t){return Af.has(t)?!0:_f.some(e=>t.startsWith(e))}function Nn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function _t(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Qo(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Js(t,e){let r=Nn(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=_t(r.id,"id")??n;if(!Ws.test(o))throw new Error(`id must match ${Ws} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=_t(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let f=Nn(r.env,"env");s={};for(let[u,m]of Object.entries(f)){if(!Re.test(u))throw new Error(`env name "${u}" must match ${Re}`);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>qs)throw new Error(`too many params (max ${qs})`);let f=new Set;a=c.map((u,m)=>Nf(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>Ys)throw new Error(`too many steps (max ${Ys})`);let p=l.map((f,u)=>{let m=Nn(f,`steps[${u}]`),d=_t(m.run,`steps[${u}].run`);if(!d||d.trim().length===0)throw new Error(`steps[${u}].run is required`);let h=_t(m.name,`steps[${u}].name`),y=Qo(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 Nf(t,e,r){let n=Nn(t,`params[${e}]`),o=_t(n.name,`params[${e}].name`);if(!o||!Re.test(o))throw new Error(`params[${e}].name must match ${Re}`);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=_t(n.label,`params[${e}].label`),c=_t(n.help,`params[${e}].help`),l=n.required===!0,p=Qo(n.min,`params[${e}].min`),f=Qo(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 zs(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 Re,Af,_f,Vs,Ws,qs,Ys,Zo=I(()=>{"use strict";Re=/^[A-Z][A-Z0-9_]*$/,Af=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),_f=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Vs=600,Ws=/^[a-z0-9-]+$/,qs=32,Ys=64});function ea(t=Of){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...ea(r.groups));return e}function Df(t,e){let r=JSON.stringify(e);return ea().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function ta(t){let e=Df(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>Xs)return{ok:!1,error:`${e.id} must have \u2264 ${Xs} entries`};let s={};for(let[a,c]of i){if(!Re.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Re}`};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>Qs)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Qs} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Xs,Qs,Zs,Of,ra=I(()=>{"use strict";Zo();Jo();Xo();Xs=64,Qs=2e3,Zs=2e3,Of=[{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:[...zo],help:"Overrides the recommended defaults for every role not listed below."},...Hs.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...zo],help:`recommended: ${Ks[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 na=I(()=>{"use strict"});var oa=I(()=>{"use strict"});var ia=I(()=>{"use strict"});var sa=I(()=>{"use strict"});function aa(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 tt(t){return`${t}${Uf}`}var Nt,Uf,ca=I(()=>{"use strict";Nt=/^[a-z][a-z0-9-]{1,30}$/,Uf="-codepipe-ctx"});var la=I(()=>{"use strict"});var ua=I(()=>{"use strict"});function Vt(t){for(let e of Lf){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Lf,pa=I(()=>{"use strict";Lf=[{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 da=I(()=>{"use strict"});var fa=I(()=>{"use strict"});var ma=I(()=>{"use strict"});function ga(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function ya(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=ga(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Jt.test(r))return r;let n=ga(t);return Jt.test(n)?n:ei}function wa(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 Fr(t){return`tasks/${t}/issue.yaml`}var ha,On,ei,Jt,ti,S$,Dn,Gr,ba=I(()=>{"use strict";ha=["bug","feature","epic"],On="feature",ei="TASK",Jt=/^[A-Z][A-Z0-9]{1,9}$/;ti={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},S$=ti.backlog,Dn="tracker/config.yaml",Gr="tracker/counter"});var ka=I(()=>{"use strict"});function zt(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 Un(t){switch(t){case Hr.gitlab:return"oauth2";case Hr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Hr,Ot,$a=I(()=>{"use strict";Hr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Ot="x-bitbucket-api-token-auth"});var va=I(()=>{"use strict"});var xa=I(()=>{"use strict";ka();$a();va()});var Sa,q=I(()=>{"use strict";Ns();Os();Ms();Gs();Fs();Jo();Xo();ra();Zo();na();oa();ia();sa();ca();la();ua();pa();da();fa();ma();ba();xa();Sa=20});function F(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Te=I(()=>{"use strict"});import{existsSync as Ra,renameSync as Bf}from"node:fs";function Dt(t,e,r=n=>console.error(n)){if(Ra(e)||!Ra(t))return!1;try{return Bf(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 Ln=I(()=>{"use strict"});import{existsSync as Bn,readFileSync as Ta,readdirSync as Mf,writeFileSync as Gf}from"node:fs";import{dirname as Ff,join as dt}from"node:path";import{parse as Hf}from"yaml";function Kf(t=process.cwd()){let e=t;for(;;){if(Bn(dt(e,We,"project.yaml")))return e;if(Bn(dt(e,ri,"project.yaml")))return Dt(dt(e,ri),dt(e,We))&&qf(e),e;let r=Ff(e);if(r===e)return null;e=r}}function Wf(t){let e=dt(t,We);return Bn(e)?e:dt(t,ri)}function qf(t){let e=dt(t,".gitignore");if(!Bn(e))return;let r=Ta(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&&
|
|
7
|
-
`,{mode:384})}function
|
|
8
|
-
`,{mode:384})}function
|
|
9
|
-
`,{mode:384})}function
|
|
5
|
+
`}function Bs(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 Ms(t,e=Ls){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 Gs(t,e=Ls){return e.filter(r=>r.version>t)}var He,Fr,Ls,Fs=R(()=>{"use strict";He=".codepipe-context.yaml",Fr=".devpipe-context.yaml",Ls=[{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 Hs=R(()=>{"use strict"});var Nf,m$,Ks=R(()=>{"use strict";Nf=[{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"]}],m$=Nf.flatMap(t=>t.phases)});function Nt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ws,zo=R(()=>{"use strict";Ws=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});var Xo,qs,Ke,Nn,Of,Qo,Ys,Zo=R(()=>{"use strict";Xo="claude",qs=[Xo],Ke="opus",Nn="sonnet",Of="haiku",Qo=[Ke,Nn,Of],Ys={analyze:Ke,implement:Ke,"resolve-conflict":Ke,rework:Ke,estimate:Nn,build:Nn,"code-review":Ke,draft:Nn,index:Ke,backfill:Ke,analysis:Ke,chat:Ke}});function ft(t){return Df.has(t)?!0:Uf.some(e=>t.startsWith(e))}function On(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ot(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ei(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=On(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Ot(r.id,"id")??n;if(!Vs.test(o))throw new Error(`id must match ${Vs} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Ot(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let f=On(r.env,"env");s={};for(let[u,m]of Object.entries(f)){if(!Ie.test(u))throw new Error(`env name "${u}" must match ${Ie}`);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>Js)throw new Error(`too many params (max ${Js})`);let f=new Set;a=c.map((u,m)=>Lf(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>zs)throw new Error(`too many steps (max ${zs})`);let p=l.map((f,u)=>{let m=On(f,`steps[${u}]`),d=Ot(m.run,`steps[${u}].run`);if(!d||d.trim().length===0)throw new Error(`steps[${u}].run is required`);let h=Ot(m.name,`steps[${u}].name`),y=ei(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 Lf(t,e,r){let n=On(t,`params[${e}]`),o=Ot(n.name,`params[${e}].name`);if(!o||!Ie.test(o))throw new Error(`params[${e}].name must match ${Ie}`);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=Ot(n.label,`params[${e}].label`),c=Ot(n.help,`params[${e}].help`),l=n.required===!0,p=ei(n.min,`params[${e}].min`),f=ei(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 Zs(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 Ie,Df,Uf,Xs,Vs,Js,zs,ti=R(()=>{"use strict";Ie=/^[A-Z][A-Z0-9_]*$/,Df=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Uf=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Xs=600,Vs=/^[a-z0-9-]+$/,Js=32,zs=64});function na(t=Bf){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...na(r.groups));return e}function Mf(t,e){let r=JSON.stringify(e);return na().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function oa(t){let e=Mf(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>ea)return{ok:!1,error:`${e.id} must have \u2264 ${ea} entries`};let s={};for(let[a,c]of i){if(!Ie.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Ie}`};if(ft(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>ta)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${ta} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var ea,ta,ra,Bf,ia=R(()=>{"use strict";ti();zo();Zo();ea=64,ta=2e3,ra=2e3,Bf=[{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:[{id:"llm.provider",file:"regimen.yaml",path:["llm","provider"],type:"enum",label:"Provider",nullable:!1,suggestions:[...qs],help:"LLM backend for this project. Currently only claude is available."}],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."},...Ws.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Qo],help:`recommended: ${Ys[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:ra,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:ra,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 (on by default; 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 (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{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 sa=R(()=>{"use strict"});var aa=R(()=>{"use strict"});var ca=R(()=>{"use strict"});var la=R(()=>{"use strict"});function ua(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 nt(t){return`${t}${Gf}`}var Dt,Gf,pa=R(()=>{"use strict";Dt=/^[a-z][a-z0-9-]{1,30}$/,Gf="-codepipe-ctx"});var da=R(()=>{"use strict"});var fa=R(()=>{"use strict"});function zt(t){for(let e of Ff){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Ff,ma=R(()=>{"use strict";Ff=[{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 ga=R(()=>{"use strict"});var ha=R(()=>{"use strict"});var ya=R(()=>{"use strict"});function wa(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function ka(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=wa(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Xt.test(r))return r;let n=wa(t);return Xt.test(n)?n:ri}function $a(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 Kr(t){return`tasks/${t}/issue.yaml`}var ba,Dn,ri,Xt,ni,C$,Un,Hr,va=R(()=>{"use strict";ba=["bug","feature","epic"],Dn="feature",ri="TASK",Xt=/^[A-Z][A-Z0-9]{1,9}$/;ni={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},C$=ni.backlog,Un="tracker/config.yaml",Hr="tracker/counter"});var xa=R(()=>{"use strict"});function Qt(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 Ln(t){switch(t){case Wr.gitlab:return"oauth2";case Wr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Wr,Ut,Sa=R(()=>{"use strict";Wr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Ut="x-bitbucket-api-token-auth"});var Ra=R(()=>{"use strict"});var Ta=R(()=>{"use strict";xa();Sa();Ra()});var Ia,F=R(()=>{"use strict";Ds();Us();Fs();Hs();Ks();zo();Zo();ia();ti();sa();aa();ca();la();pa();da();fa();ma();ga();ha();ya();va();Ta();Ia=20});function M(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ce=R(()=>{"use strict"});import{existsSync as Ca,renameSync as Hf}from"node:fs";function Lt(t,e,r=n=>console.error(n)){if(Ca(e)||!Ca(t))return!1;try{return Hf(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 Bn=R(()=>{"use strict"});import{existsSync as Mn,readFileSync as Ea,readdirSync as Kf,writeFileSync as Wf}from"node:fs";import{dirname as qf,join as mt}from"node:path";import{parse as Yf}from"yaml";function Vf(t=process.cwd()){let e=t;for(;;){if(Mn(mt(e,We,"project.yaml")))return e;if(Mn(mt(e,oi,"project.yaml")))return Lt(mt(e,oi),mt(e,We))&&zf(e),e;let r=qf(e);if(r===e)return null;e=r}}function Jf(t){let e=mt(t,We);return Mn(e)?e:mt(t,oi)}function zf(t){let e=mt(t,".gitignore");if(!Mn(e))return;let r=Ea(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&&Wf(e,n)}function Ee(t=process.cwd()){let e=Vf(t);if(!e)return null;let r=Jf(e),n=Xf(Ea(mt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Pa(t,e,r){return Kf(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 Gn(t,e=process.cwd()){try{let r=Ee(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Xf(t){let e=Yf(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 ja(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,oi,ot=R(()=>{"use strict";Bn();We=".codepipe",oi=".devpipe"});import{homedir as Aa}from"node:os";import{mkdirSync as Qf,readFileSync as Zf,writeFileSync as em,existsSync as ii}from"node:fs";import{dirname as Na,join as Fn,resolve as tm}from"node:path";import{fileURLToPath as rm}from"node:url";function Oa(t){let e=Fn(_a,".env");if(ii(e)&&process.loadEnvFile(e),t){let r=Fn(_a,"profiles",t,".env");ii(r)&&process.loadEnvFile(r)}}function Zt(t){let e=M("CONFIG");return e||(t?Fn(Aa(),".codepipe","profiles",t,"config.json"):Fn(Aa(),".codepipe","config.json"))}function De(t){let e=Zt(t);if(!ii(e))return null;let r=Zf(e,"utf-8");return JSON.parse(r)}function it(t,e){let r=Zt(e);Qf(Na(r),{recursive:!0}),em(r,JSON.stringify(t,null,2)+`
|
|
7
|
+
`,{mode:384})}function Hn(t){if(t)return{cfg:Pe(t),profile:t};let e;try{e=Ee()?.spec.projectId||void 0}catch{}if(e){let r=De(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:Pe(void 0),profile:void 0}}function Pe(t){let e=De(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 _a,ve=R(()=>{"use strict";Ce();ot();_a=tm(Na(rm(import.meta.url)),"..")});import{homedir as Ba}from"node:os";import{existsSync as Ma,mkdirSync as Ga,readFileSync as Fa,writeFileSync as Ha}from"node:fs";import{dirname as Ka,join as Wa}from"node:path";function qa(t,e,r){let n=U(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},X(n)}function Ya(t,e){let r=U(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],X(r),!0)}function Va(t){return Object.keys(U(t)?.secrets??{}).sort()}function Kn(t,e,r){let n=U(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,X(n),"pinned")}function Ja(t,e){let r=U(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],X(r),!0):!1}function qe(t){return Wa(Ba(),".codepipe","secrets",`${t}.json`)}function U(t){let e=qe(t);return Ma(e)?JSON.parse(Fa(e,"utf-8")):null}function X(t){let e=qe(t.projectId);Ga(Ka(e),{recursive:!0}),Ha(e,JSON.stringify(t,null,2)+`
|
|
8
|
+
`,{mode:384})}function Wn(){return Wa(Ba(),".codepipe","shared.json")}function si(){let t=Wn();return Ma(t)?JSON.parse(Fa(t,"utf-8")):null}function za(t){let e=Wn();Ga(Ka(e),{recursive:!0}),Ha(e,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function er(t){let e=U(t)?.claude?.oauthToken;return e||si()?.claude?.oauthToken}function qr(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 tr(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var te=R(()=>{"use strict"});import{appendFileSync as nm,existsSync as Qa,mkdirSync as om,renameSync as Za,statSync as im,unlinkSync as sm}from"node:fs";import{Writable as am}from"node:stream";import{join as cm}from"node:path";function qn(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=lm(process.env[`${t}_MAX_BYTES`]??String(ec.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):ec.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function lm(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 Yn(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(um(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 um(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:pm(o)).join(" ");return`${r} ${t} ${n}`}function pm(t){try{return JSON.stringify(t)}catch{return String(t)}}var ec,rr,ai=R(()=>{"use strict";ec={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},rr=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&om(e.dir,{recursive:!0}),this.currentPath=cm(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
|
-
`;
|
|
11
|
+
`;nm(this.currentPath,r,"utf-8")}asWritable(){return new am({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)||im(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?sm(n):Za(n,`${this.currentPath}.${r+1}`))}Za(this.currentPath,`${this.currentPath}.1`)}}}});import{existsSync as gt,mkdirSync as lc,readFileSync as pi,writeFileSync as nr}from"node:fs";import{homedir as Tm}from"node:os";import{join as Ye}from"node:path";import{simpleGit as Im}from"simple-git";function Vr(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Ye(t,o);gt(s)||(nr(s,i),r.push(o))}return r}function Bt(t,e,r){let n=Ye(Tm(),".codepipe","profiles",t,"context-config");return lc(n,{recursive:!0}),nr(Ye(n,"project.yaml"),e.projectYaml),nr(Ye(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function zn(t,e,r){if(gt(e))for(let n of or){let o=Ye(e,n),i=Ye(t,n);if(!(!gt(o)||gt(i)))try{nr(i,pi(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 ir(t){let e=Ye(t,".gitignore"),r=gt(e)?pi(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(or.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
12
12
|
`)?"":`
|
|
13
|
-
`;return
|
|
13
|
+
`;return nr(e,r+i+Cm.join(`
|
|
14
14
|
`)+`
|
|
15
|
-
`),!0}async function
|
|
16
|
-
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;
|
|
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);
|
|
15
|
+
`),!0}async function uc(t,e){try{if(!gt(Ye(t,".git")))return;let r=Im(t),n=(await r.raw(["ls-files","--",...or])).split(`
|
|
16
|
+
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;ir(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 mi(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 di(t){let e=new Map;for(let r of or){let n=Ye(t,r);gt(n)&&e.set(r,pi(n))}return e}function fi(t,e){lc(t,{recursive:!0});for(let[r,n]of e){let o=Ye(t,r);gt(o)||nr(o,n)}}var or,Cm,st=R(()=>{"use strict";ht();or=["project.yaml","regimen.yaml"];Cm=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Em,mkdirSync as Pm,rmSync as jm,writeFileSync as gi}from"node:fs";import{dirname as Am,isAbsolute as _m,join as fc,normalize as Zn}from"node:path";import{simpleGit as mc}from"simple-git";async function hi(t,e){let r=Zn(t),o=(Qn.get(r)??Promise.resolve()).catch(()=>{}).then(e);Qn.set(r,o);try{return await o}finally{Qn.get(r)===o&&Qn.delete(r)}}async function at(t,e,r){return hi(t,()=>yi(t,e,r))}async function yi(t,e,r){if(!Em(fc(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=ae(t,a.path);if(a.deleted){jm(c,{force:!0});continue}Pm(Am(c),{recursive:!0}),a.encoding==="base64"?gi(c,Buffer.from(a.content,"base64")):gi(c,a.content)}let n=mc(t),o=e.filter(a=>!a.deleted).map(a=>a.path),i=e.filter(a=>a.deleted).map(a=>a.path);for(let a=0;a<o.length;a+=Xn)await n.raw(["add","-A","-f","--",...o.slice(a,a+Xn)]);for(let a=0;a<i.length;a+=Xn)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+Xn)]);await n.raw(["reset","-q","--",...or]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await mi(t))}async function mi(t){let e=mc(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=pc;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 Dm(e);if(i.length>0&&i.every(a=>Nm.has(a)||dc.test(a))){for(let a of i)dc.test(a)?await Om(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 ${pc} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Om(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
|
+
`)){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);gi(ae(e,r),i.join(`
|
|
18
18
|
`)+(i.length>0?`
|
|
19
|
-
`:""))}async function
|
|
20
|
-
`).map(r=>r.trim()).filter(Boolean)}function
|
|
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 eo(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 Wm(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 Wm(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function to(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=wc.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: ${wc.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 bc(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 qm(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 yi(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 bi(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new wi(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new ki(e)}return new $i}var Lt,wc,wi,bi,ki,$i,wt=I(()=>{"use strict";Lt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};wc=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];wi=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 Lt(`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()}`)}},bi=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 Lt(`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}
|
|
19
|
+
`:""))}async function Dm(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
20
|
+
`).map(r=>r.trim()).filter(Boolean)}function ae(t,e){if(_m(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Zn(fc(t,e)),n=Zn(t+"/");if(r!==Zn(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var pc,Nm,dc,Xn,Qn,ht=R(()=>{"use strict";st();pc=3,Nm=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),dc=/^tasks\/[^/]+\/comments\.jsonl$/,Xn=500,Qn=new Map});function kc(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
21
|
+
`+t.slice(t.length-e)}async function yt(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 to(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 wt(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 Jm(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 Jm(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ro(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=$c.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: ${$c.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function bt(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 vc(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 zm(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 bi(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 Ue(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new $i(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new ki(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new vi(e)}return new xi}var Mt,$c,ki,$i,vi,xi,kt=R(()=>{"use strict";Mt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};$c=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];ki=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 Mt(`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()}`)}},$i=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 Mt(`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
|
+
${kc(y,8e3)}`)}}return p.length===0?void 0:kc(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()}`)}},
|
|
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()}`)}},vi=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 Mt(`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=zm(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()}`)}};xi=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(bi(e,r,"merge"))}async closePR(e,r,n){throw new Error(bi(e,r,"close"))}async addPRComment(e,r,n){throw new Error(bi(e,r,"comment"))}}});import{existsSync as $t,readFileSync as sr,readdirSync as Sc}from"node:fs";import{join as Si}from"node:path";import{simpleGit as Rc}from"simple-git";import{parse as Tc}from"yaml";function Ic(t){try{let e=ae(t,Un);if(!$t(e))return null;let r=Tc(sr(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Xt.test(n)?null:{prefix:n}}catch{return null}}function Cc(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}
|
|
@@ -30,15 +30,15 @@ prefix: ${t}
|
|
|
30
30
|
# Statuses are the built-in default set for now:
|
|
31
31
|
# Backlog | To Do | In Progress | Review | Done | Rejected
|
|
32
32
|
# A configurable status set / pipeline mapping is a planned extension.
|
|
33
|
-
`}function
|
|
34
|
-
`}function
|
|
33
|
+
`}function Ri(t=0){return`${t}
|
|
34
|
+
`}function Xm(t){return t==="depends_on"||t==="subtask"}function Qm(t){let e;try{e=Tc(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=ba.includes(r.type)?r.type:Dn,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;Xm(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 Ti(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
|
|
36
|
+
`}function zr(t,e){let r=ae(t,Kr(e));return $t(r)?Qm(sr(r,"utf-8")):null}function Ec(t){let e=Si(t,"tasks");if(!$t(e))return[];let r=[];for(let n of Sc(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=zr(t,n.name);o&&r.push(o)}return r}function Zm(t,e){let r=ae(t,`tasks/${e}/task.md`);if(!$t(r))return;let n=sr(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
|
|
38
|
+
`).trim();if(!(!a||a==="_(no description)_"))return a}function Xr(t,e,r={}){let n=r.withDescription?Zm(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:eg(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function eg(t){return t.charAt(0).toUpperCase()+t.slice(1)}function tg(t){let e=ae(t,Hr);if(!$t(e))return 0;let r=Number.parseInt(sr(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function rg(t,e){let r=Si(t,"tasks");if(!$t(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of Sc(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 ng(t,e){return Math.max(tg(t),rg(t,e))+1}async function Pc(t,e,r,n){return hi(t,()=>og(t,e,r,n))}async function og(t,e,r,n){if(!$t(Si(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Jr(t);let o=null;for(let i=0;i<xc;i++){let s=ng(t,e),a=`${e}-${s}`,c=[...r(a),{path:Hr,content:Ri(s)}];try{return await yi(t,c,n(a)),a}catch(l){if(o=l,await sg(t,n(a)),await Jr(t),ig(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${xc} attempts: ${o instanceof Error?o.message:String(o)}`)}function ig(t,e){for(let r of e){let n=ae(t,r.path);if(!$t(n)||(r.encoding==="base64"?sr(n).toString("base64"):sr(n,"utf-8"))!==r.content)return!1}return!0}async function Jr(t){let e=Rc(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 sg(t,e){let r=Rc(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 xc,no=R(()=>{"use strict";F();ht();xc=5});function ar(t,e,r,n){return[{path:"README.md",content:yg(t,e)},{path:".gitignore",content:pg()},{path:"CLAUDE.md",content:fg(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:dg()},{path:"knowledge/README.md",content:mg()},{path:"knowledge/build.yaml",content:hg()},{path:"actions/README.md",content:gg()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:ug()},{path:"adr/README.md",content:ag()},{path:"adr/0000-template.md",content:cg()},{path:"adr/INDEX.md",content:lg()},{path:He,content:_n()},...t.trackerProvider==="internal"?[{path:Un,content:Cc(t.youtrackProjectKey??ri)},{path:Hr,content:Ri()}]:[]]}function ag(){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
|
|
@@ -66,7 +66,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
66
66
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
67
67
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
68
68
|
open a PR to this repository.
|
|
69
|
-
`}function
|
|
69
|
+
`}function cg(){return`# ADR-NNNN: <title>
|
|
70
70
|
|
|
71
71
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
72
72
|
- **Date:** YYYY-MM-DD
|
|
@@ -88,12 +88,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
88
88
|
## Alternatives considered
|
|
89
89
|
|
|
90
90
|
- **<alternative>** \u2014 why it was rejected.
|
|
91
|
-
`}function
|
|
91
|
+
`}function lg(){return`# ADR index
|
|
92
92
|
|
|
93
93
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
94
94
|
|
|
95
95
|
(no accepted ADRs yet)
|
|
96
|
-
`}function
|
|
96
|
+
`}function ug(){return`# Audit
|
|
97
97
|
|
|
98
98
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
99
99
|
project appends only to its own file \u2014
|
|
@@ -102,14 +102,14 @@ project appends only to its own file \u2014
|
|
|
102
102
|
|
|
103
103
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
104
104
|
shared aggregate here.
|
|
105
|
-
`}function Ve(t,e,r,n,o="auto"){let i=t.trackerProvider==="internal";return{projectYaml:i?
|
|
105
|
+
`}function Ve(t,e,r,n,o="auto"){let i=t.trackerProvider==="internal";return{projectYaml:i?wg(t,o):bg(t,r,n,o),regimenYaml:kg(t.automationLevel,i?!0:e,i)}}function pg(){return`# codepipe project config is local to each member's workspace
|
|
106
106
|
project.yaml
|
|
107
107
|
regimen.yaml
|
|
108
108
|
|
|
109
109
|
# codepipe runtime
|
|
110
110
|
session.log
|
|
111
111
|
apply-queue.json
|
|
112
|
-
`}function
|
|
112
|
+
`}function dg(){return`# Index prompt
|
|
113
113
|
|
|
114
114
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
115
115
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -166,7 +166,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
166
166
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
167
167
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
168
168
|
empty or unavailable, say so briefly rather than inventing content.
|
|
169
|
-
`}function
|
|
169
|
+
`}function fg(t){return`# Project context for the CodePipe agent
|
|
170
170
|
|
|
171
171
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
172
172
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -194,7 +194,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
194
194
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
195
195
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
196
196
|
only after the analysis is approved.
|
|
197
|
-
`}function
|
|
197
|
+
`}function mg(){return`# Knowledge
|
|
198
198
|
|
|
199
199
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
200
200
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -211,7 +211,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
211
211
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
212
212
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
213
213
|
any merge conflict in it as noise (either side converges on the next run).
|
|
214
|
-
`}function
|
|
214
|
+
`}function gg(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
|
|
215
215
|
|
|
216
216
|
One \`<id>.yml\` per action. Every file here appears as a button on the
|
|
217
217
|
project's **RUN** tab; an action with \`params\` opens a small wizard first.
|
|
@@ -250,7 +250,7 @@ steps:
|
|
|
250
250
|
Parameter values are passed to the commands **only as env vars** \u2014 reference
|
|
251
251
|
them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
|
|
252
252
|
command text itself.
|
|
253
|
-
`}function
|
|
253
|
+
`}function hg(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
254
254
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
255
255
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
256
256
|
#
|
|
@@ -266,7 +266,7 @@ command text itself.
|
|
|
266
266
|
# - name: test
|
|
267
267
|
# run: npm test
|
|
268
268
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
269
|
-
`}function
|
|
269
|
+
`}function yg(t,e){return`# ${e.name}
|
|
270
270
|
|
|
271
271
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
272
272
|
|
|
@@ -292,7 +292,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
292
292
|
pipeline \u2014 don't edit them by hand.
|
|
293
293
|
|
|
294
294
|
Automation level: **${t.automationLevel}**.
|
|
295
|
-
`}function
|
|
295
|
+
`}function wg(t,e="auto"){return`# Project description for CodePipe.
|
|
296
296
|
id: ${t.projectId}
|
|
297
297
|
name: ${t.name}
|
|
298
298
|
|
|
@@ -315,15 +315,15 @@ branch:
|
|
|
315
315
|
pattern: codepipe/<TASK_ID>
|
|
316
316
|
|
|
317
317
|
repos:
|
|
318
|
-
${
|
|
319
|
-
`}function
|
|
318
|
+
${jc(t)}
|
|
319
|
+
`}function jc(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}
|
|
323
323
|
repo: ${e.repoName}
|
|
324
324
|
mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
|
|
325
325
|
default_branch: ${e.defaultBranch}`:"")).join(`
|
|
326
|
-
`)}function
|
|
326
|
+
`)}function bg(t,e,r,n="auto"){let o=e?`
|
|
327
327
|
tracker_url: ${e}`:`
|
|
328
328
|
# tracker_url: https://your.youtrack.cloud`,i=r?`require_assignee: true
|
|
329
329
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -371,7 +371,7 @@ ${Cc(t)}
|
|
|
371
371
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
372
372
|
${i}`:` # project_key: \u2026
|
|
373
373
|
# tracker_url: https://your.youtrack.cloud
|
|
374
|
-
poll_interval_sec: 60`,a=
|
|
374
|
+
poll_interval_sec: 60`,a=jc(t);return`# Project description for CodePipe.
|
|
375
375
|
id: ${t.projectId}
|
|
376
376
|
name: ${t.name}
|
|
377
377
|
|
|
@@ -402,7 +402,7 @@ branch:
|
|
|
402
402
|
|
|
403
403
|
repos:
|
|
404
404
|
${a}
|
|
405
|
-
`}function
|
|
405
|
+
`}function kg(t,e,r=!1){let n=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
|
|
406
406
|
automation:
|
|
407
407
|
level: ${t}
|
|
408
408
|
|
|
@@ -437,12 +437,13 @@ gates:
|
|
|
437
437
|
G2_solution: { mode: ${n?"never":"always"} }
|
|
438
438
|
G3_implementation: { mode: ${n?"never":"always"} }
|
|
439
439
|
G4_apply: { mode: ${n?"never":"always"} }
|
|
440
|
-
# The first ACTUALLY consumed key of the gates block. When true
|
|
441
|
-
#
|
|
442
|
-
#
|
|
443
|
-
#
|
|
444
|
-
#
|
|
445
|
-
|
|
440
|
+
# The first ACTUALLY consumed key of the gates block. When true (the
|
|
441
|
+
# default), a task taken from a source stage lands in the QUEUE section
|
|
442
|
+
# (QUEUED) and waits for a single Confirm; the Confirm pulls in the
|
|
443
|
+
# dependency closure (depends on) and topologically orders the queue, then
|
|
444
|
+
# the whole queue enters the pipeline. Set false for conveyor mode: each
|
|
445
|
+
# task starts the pipeline immediately. Orthogonal to automation.level.
|
|
446
|
+
require_approval: true
|
|
446
447
|
|
|
447
448
|
estimate:
|
|
448
449
|
# Optional ESTIMATING phase (runs after ANALYZING). Informational only \u2014
|
|
@@ -498,6 +499,9 @@ rework:
|
|
|
498
499
|
archive_window_days: 14
|
|
499
500
|
|
|
500
501
|
llm:
|
|
502
|
+
# LLM backend for this project. Currently only \`claude\` is supported;
|
|
503
|
+
# this line is the anchor for future providers.
|
|
504
|
+
provider: claude
|
|
501
505
|
# Per-role model selection (Claude cost optimization). Run cheap,
|
|
502
506
|
# mechanical roles on a smaller model and architectural / code roles on the
|
|
503
507
|
# capable one. Values are aliases (opus | sonnet | haiku) \u2014 Claude Code
|
|
@@ -537,19 +541,19 @@ llm:
|
|
|
537
541
|
# # the previous task's branch (auto-merge without reworking the
|
|
538
542
|
# # tail of the chain).
|
|
539
543
|
# mode: parallel
|
|
540
|
-
`}var
|
|
541
|
-
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Kg(t,e,r){return new Promise((n,o)=>{let i=kt.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 Xc(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Pi(t,e,r){return new Promise(n=>{let o=kt.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 Wg(t){try{let e=await fetch(t);return e.ok?new Xc(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function rl(t,e=443,r=Zc){let n=`${t}:${e}`,o=zc.get(n);if(o)return o;let i=qg(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return zc.set(n,i),i}async function qg(t,e,r){if(!Qc)return!1;let n=8e3;if(await Pi(t,e,n))return!0;let o=await Kg(t,e,n),i=kt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Hg(o);if(!c)break;let l=await Wg(c);if(!l)break;if(s.push(l.toString()),kt.setDefaultCACertificates([...i,...s]),await Pi(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 Pi(t,e,n)}var Qc,Jc,zc,Zc,nl=I(()=>{"use strict";Te();Qc=typeof kt.getCACertificates=="function"&&typeof kt.setDefaultCACertificates=="function",Jc=!1,zc=new Map,Zc=t=>console.warn(t)});function al(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Ee(t,e,r){el();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(tl(s)&&await rl(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Yg(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Vg(){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 Ei(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Vg(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Ee(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&&Yg(l.status,p)){await ol(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<o){await ol(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 Ee(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 cl(t){try{let e=await Ee(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Jg(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=il.get(o);if(i)return i;let s=await Ee(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 il.set(o,l.id),l.id}async function ll(t,e,r,n=en){let o=await Jg(t,e,r,n);await Ei(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 ul(t,e,r){return await(await Ei(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function pl(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Ei(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function dl(t,e){let r=sl.get(e);if(r)return r;let n=await Ee(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 sl.set(e,i.id),i.id}async function fl(t,e,r,n,o,i=en){let s=await dl(t,e),a=await Ee(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 ml(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Ee(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 yl(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 wl(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 bl(t,e){let r=e.stageField??en,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=${hl}&$top=200`,s=await Ee(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>vl(c,r))}async function kl(t,e,r=en){let n=`/api/issues/${encodeURIComponent(e)}?fields=${hl}`,o=await Ee(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return vl(await o.json(),r)}async function $l(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Xg}&$top=500`,o=await Ee(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=yl(s.attachments);return c&&(a.attachments=c),a})}function Qg(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 vl(t,e=en){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=yl(t.attachments);a&&(s.attachments=a);let c=Qg(t.links);return c&&(s.links=c),s}async function xl(t,e){let r=await Zg(t,e);return r.length>0?r:eh(t,e)}async function Zg(t,e){let r=await dl(t,e),n=await Ee(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:Sl(s.bundle)});return i}async function eh(t,e){let r=`project: ${e}`,n=await Ee(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:Sl(s.projectCustomField?.bundle)});return i}function Sl(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var ol,en,il,sl,gl,zg,hl,Xg,Mt=I(()=>{"use strict";nl();ol=t=>new Promise(e=>setTimeout(e,t));en="Stage",il=new Map;sl=new Map;gl="attachments(id,name,url,size,mimeType)",zg="links(direction,linkType(name),issues(idReadable))",hl=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${gl},${zg}`,Xg=`id,text,created,author(login),${gl}`});function tn(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 rn(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 nn(t,e=process.env){if(!t)return!1;let r=`https://${Ot}:${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 Ai(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 Tl(t,e=process.env){return Ai(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>tn(t,e),e)}function Il(t,e=process.env){return Ai(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>rn(t,e),e)}function Cl(t,e=process.env){return Ai(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Ot}:${encodeURIComponent(t)}@bitbucket.org/`,()=>nn(t,e),e)}var so=I(()=>{"use strict";q()});import{homedir as Ph}from"node:os";import{existsSync as Eh,mkdirSync as jh,readFileSync as Ah,writeFileSync as _h}from"node:fs";import{dirname as Nh,join as Oh}from"node:path";function Ui(){return F("FARM_PINS")??Oh(Ph(),".codepipe","farm-pins.json")}function Vl(){let t=Ui();if(!Eh(t))return{};try{return JSON.parse(Ah(t,"utf-8"))}catch{return{}}}function Dh(t){let e=Ui();jh(Nh(e),{recursive:!0}),_h(e,JSON.stringify(t,null,2)+`
|
|
542
|
-
`,{mode:384})}function
|
|
544
|
+
`}var Gt=R(()=>{"use strict";F();no()});import{createCipheriv as Bg,createDecipheriv as Mg,createHash as Gg,createPrivateKey as Fg,createPublicKey as Pi,diffieHellman as Yc,generateKeyPairSync as Vc,hkdfSync as Jc,randomBytes as Hg}from"node:crypto";function so(){let{publicKey:t,privateKey:e}=Vc("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function we(t){let e=Buffer.from(t,"base64");return(Gg("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function ct(t,e){let r=Pi({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Vc("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Yc({privateKey:o,publicKey:r}),c=Buffer.from(Jc("sha256",a,Buffer.concat([i,s]),zc,32)),l=Hg(12),p=Bg("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 lr(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=Fg({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Pi({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Pi(n).export({type:"spki",format:"der"}),a=Yc({privateKey:n,publicKey:o}),c=Buffer.from(Jc("sha256",a,Buffer.concat([i,s]),zc,32)),l=Mg("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 zc,je=R(()=>{"use strict";zc=Buffer.from("devpipe-sealedbox-v1","utf-8")});import{X509Certificate as el}from"node:crypto";import{readFileSync as Wg}from"node:fs";import vt from"node:tls";function qg(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function nl(t=rl){if(Qc)return;Qc=!0;let e=M("EXTRA_CA_FILE");if(!(!e||!tl))try{let r=qg(Wg(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}vt.setDefaultCACertificates([...vt.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 ol(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 Yg(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
545
|
+
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Vg(t,e,r){return new Promise((n,o)=>{let i=vt.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 el(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function ji(t,e,r){return new Promise(n=>{let o=vt.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 Jg(t){try{let e=await fetch(t);return e.ok?new el(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function il(t,e=443,r=rl){let n=`${t}:${e}`,o=Zc.get(n);if(o)return o;let i=zg(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Zc.set(n,i),i}async function zg(t,e,r){if(!tl)return!1;let n=8e3;if(await ji(t,e,n))return!0;let o=await Vg(t,e,n),i=vt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Yg(o);if(!c)break;let l=await Jg(c);if(!l)break;if(s.push(l.toString()),vt.setDefaultCACertificates([...i,...s]),await ji(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 ji(t,e,n)}var tl,Qc,Zc,rl,sl=R(()=>{"use strict";Ce();tl=typeof vt.getCACertificates=="function"&&typeof vt.setDefaultCACertificates=="function",Qc=!1,Zc=new Map,rl=t=>console.warn(t)});function ul(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Ae(t,e,r){nl();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(ol(s)&&await il(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Xg(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Qg(){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 Ai(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Qg(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Ae(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&&Xg(l.status,p)){await al(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<o){await al(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function xt(t){let e;try{e=await Ae(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 pl(t){try{let e=await Ae(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Zg(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=cl.get(o);if(i)return i;let s=await Ae(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 cl.set(o,l.id),l.id}async function dl(t,e,r,n=rn){let o=await Zg(t,e,r,n);await Ai(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 fl(t,e,r){return await(await Ai(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function ml(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Ai(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function gl(t,e){let r=ll.get(e);if(r)return r;let n=await Ae(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 ll.set(e,i.id),i.id}async function hl(t,e,r,n,o,i=rn){let s=await gl(t,e),a=await Ae(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 yl(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Ae(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 kl(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 $l(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 vl(t,e){let r=e.stageField??rn,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=${bl}&$top=200`,s=await Ae(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Rl(c,r))}async function xl(t,e,r=rn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${bl}`,o=await Ae(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Rl(await o.json(),r)}async function Sl(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${th}&$top=500`,o=await Ae(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=kl(s.attachments);return c&&(a.attachments=c),a})}function rh(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 Rl(t,e=rn){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=kl(t.attachments);a&&(s.attachments=a);let c=rh(t.links);return c&&(s.links=c),s}async function Tl(t,e){let r=await nh(t,e);return r.length>0?r:oh(t,e)}async function nh(t,e){let r=await gl(t,e),n=await Ae(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:Il(s.bundle)});return i}async function oh(t,e){let r=`project: ${e}`,n=await Ae(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:Il(s.projectCustomField?.bundle)});return i}function Il(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var al,rn,cl,ll,wl,eh,bl,th,Ft=R(()=>{"use strict";sl();al=t=>new Promise(e=>setTimeout(e,t));rn="Stage",cl=new Map;ll=new Map;wl="attachments(id,name,url,size,mimeType)",eh="links(direction,linkType(name),issues(idReadable))",bl=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${wl},${eh}`,th=`id,text,created,author(login),${wl}`});function nn(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 on(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 sn(t,e=process.env){if(!t)return!1;let r=`https://${Ut}:${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 Ni(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 El(t,e=process.env){return Ni(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>nn(t,e),e)}function Pl(t,e=process.env){return Ni(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>on(t,e),e)}function jl(t,e=process.env){return Ni(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Ut}:${encodeURIComponent(t)}@bitbucket.org/`,()=>sn(t,e),e)}var ao=R(()=>{"use strict";F()});import{homedir as _h}from"node:os";import{existsSync as Nh,mkdirSync as Oh,readFileSync as Dh,writeFileSync as Uh}from"node:fs";import{dirname as Lh,join as Bh}from"node:path";function Bi(){return M("FARM_PINS")??Bh(_h(),".codepipe","farm-pins.json")}function Xl(){let t=Bi();if(!Nh(t))return{};try{return JSON.parse(Dh(t,"utf-8"))}catch{return{}}}function Mh(t){let e=Bi();Oh(Lh(e),{recursive:!0}),Uh(e,JSON.stringify(t,null,2)+`
|
|
546
|
+
`,{mode:384})}function Gh(t){return Xl()[t]}function mo(t,e){let r=Xl();r[t]=e,Mh(r)}function go(t,e){let r=we(e),n=Gh(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 ${Bi()}.`);return r}var Mi=R(()=>{"use strict";Ce();je()});import{setTimeout as Fh}from"node:timers/promises";import Hh from"ws";function ho(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Hh(r)}async function St(t,e,r){return Be(t,e,"/projects",r)}async function Ql(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function yo(t,e,r,n){return Be(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Zl(t,e,r,n){return Be(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function eu(t,e,r,n){return Be(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function tu(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new N(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function wo(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Gi(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function ru(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Gi(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 Fh(r.delayMs??1500)}throw o}async function nu(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 un(e)}if(!r.ok)throw new N(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function ou(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new N(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function iu(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function su(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new N(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function au(t,e,r,n){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function cu(t,e,r,n,o){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function lu(t,e,r,n,o){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function uu(t,e,r,n,o){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function pn(t,e,r,n){return Be(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Fi(t,e,r,n){await Be(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function pu(t,e,r,n){return Be(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function du(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 N(o.status,s,a)}return s}async function V(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function Be(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new N(o.status,s,a)}return s}var N,un,fe=R(()=>{"use strict";N=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};un=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{execFileSync as dy}from"node:child_process";import{mkdtempSync as fy,mkdirSync as my,readFileSync as Au,rmSync as gy,writeFileSync as hy}from"node:fs";import{tmpdir as yy}from"node:os";import{dirname as wy,join as _u}from"node:path";function Nu(t="codepipe-context"){let e=fy(_u(yy(),"codepipe-ssh-")),r=_u(e,"id_ed25519");try{return dy("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Au(r,"utf-8"),publicKey:Au(`${r}.pub`,"utf-8").trim()}}finally{gy(e,{recursive:!0,force:!0})}}async function Ou(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 Du(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 Uu(t,e){my(wy(t),{recursive:!0});let r=e.endsWith(`
|
|
543
547
|
`)?e:e+`
|
|
544
|
-
`;return
|
|
545
|
-
`,{mode:384})}var
|
|
546
|
-
`}async function
|
|
547
|
-
`))!==-1;){let
|
|
548
|
-
`)){let
|
|
548
|
+
`;return hy(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Yi=R(()=>{"use strict"});import{existsSync as Lu,mkdirSync as Bu}from"node:fs";import{dirname as Mu}from"node:path";import{simpleGit as pr}from"simple-git";function by(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 ky(t,e){return e?.contextWrite?.token?{user:Ln(t),secret:e.contextWrite.token}:t===Wr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Wr.bitbucket?e?.bitbucket?.apiToken?{user:Ut,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Gu(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 vo))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 xo(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await V(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new vo(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=ky(Qt(s.cloneUrl),r);if(a){let c=await $y({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 vy({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 $y(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=by(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(Lu(`${r}/.git`)){let l=pr(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let p=di(r);await l.reset(["--hard",`origin/${s}`]),fi(r,p),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Bu(Mu(r),{recursive:!0}),await pr().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Fu(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 vy(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Uu(i,n),a=Du(e.cloneUrl),c=e.branch;try{if(Lu(`${r}/.git`)){let l=pr(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=di(r);await l.reset(["--hard",`origin/${c}`]),fi(r,p),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Bu(Mu(r),{recursive:!0}),await pr().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await pr(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Fu(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 Fu(t){let e=pr(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 vo,Vi=R(()=>{"use strict";F();fe();st();Yi();vo=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as xy}from"node:child_process";function Sy(){try{return xy("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Ku(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Sy(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Wu=R(()=>{"use strict"});import{homedir as dr}from"node:os";import{mkdirSync as Ry,readFileSync as qu,writeFileSync as Ty,existsSync as zi}from"node:fs";import{dirname as Iy,join as Rt}from"node:path";function Cy(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Me(t){let e=M("SANDBOX_CONFIG");if(e)return e;let r=Rt(dr(),".codepipe","worker");return t?Rt(r,"profiles",t,"config.json"):Rt(r,"config.json")}function Yu(){return Rt(dr(),".devpipe-sandbox","config.json")}function So(){Lt(Rt(dr(),".devpipe"),Rt(dr(),".codepipe")),M("SANDBOX_CONFIG")||Lt(Rt(dr(),".devpipe-sandbox"),Rt(dr(),".codepipe-sandbox"))}function Vu(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function ge(t){let e=Me(t),r=null;return zi(e)?r=JSON.parse(qu(e,"utf-8")):!t&&!M("SANDBOX_CONFIG")&&zi(Yu())&&(r=JSON.parse(qu(Yu(),"utf-8"))),r?(r.planningLane=Cy(),r):null}function Ju(t,e){let r=Me(e);Ry(Iy(r),{recursive:!0}),Ty(r,JSON.stringify(t,null,2)+`
|
|
549
|
+
`,{mode:384})}var Ro=R(()=>{"use strict";Ce();Bn();zi(".env")&&process.loadEnvFile(".env")});import Ey from"ws";var fr,Xi=R(()=>{"use strict";fr=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 Ey(e)}}});import{hostname as Py}from"node:os";async function Ht(t){So();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 ${Me(t.profile)}.`),process.exit(1));let r=t.name??Py(),n=Ku({projects:t.projects??[],llm:t.llm??null}),o=new fr(t.hub.replace(/\/$/,"")),i=so(),s=we(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Ju({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 ${Me(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 zu=R(()=>{"use strict";je();Wu();Ro();Xi()});import{spawn as jy}from"node:child_process";function Qi(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function _y(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 Ny(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Kt(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Zi(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
|
|
550
|
+
`}async function ep(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new lt;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:Qi(d,Xu)})}else if(m==="tool_use"){let d=String(u.name??""),h=u.input?.file_path??u.input?.path,y=_y(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?Qi(Ny(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=jy(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"),Qu)};e.signal?.addEventListener("abort",d,{once:!0});let h=null,y=()=>{h&&clearTimeout(h),h=setTimeout(()=>{u=!0,console.warn(`[claude:chat] idle for ${Zu}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Qu)},Zu)},$=()=>{m&&clearTimeout(m),h&&clearTimeout(h),e.signal?.removeEventListener("abort",d)},w=!0,v=E=>{if(!(!w||p.stdin.destroyed))try{p.stdin.write(E)}catch{}};v(Zi(e.prompt)),y(),(async()=>{try{for await(let E of e.interactive.inbox){if(f||!w)break;if(y(),E.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:Qi(E.text,Xu)}),v(Zi(E.text));else{v(Zi(Ay)),w=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let x="",L=E=>{let j;try{j=JSON.parse(E)}catch{return}a(j)};p.stdout.on("data",E=>{i.push(E),y(),x+=E;let j;for(;(j=x.indexOf(`
|
|
551
|
+
`))!==-1;){let B=x.slice(0,j).trim();x=x.slice(j+1),B&&L(B)}}),p.stderr.on("data",E=>{i.push(E);for(let j of E.split(`
|
|
552
|
+
`)){let B=j.trim();B&&console.warn(`[claude:chat:stderr] ${B}`)}}),p.on("error",E=>{$(),l(E)}),p.on("close",E=>{if($(),f){l(new lt);return}if(u){l(new Error("chat session ended: idle for too long without a reply"));return}x.trim()&&L(x.trim()),console.log(`[claude:chat] exit code=${E}`),c({artifactPaths:[],log:i.join(""),usage:Oy(s)})})})}function Oy(t){let e=Nt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Kt(r.input_tokens),e.outputTokens=Kt(r.output_tokens),e.cacheReadInputTokens=Kt(r.cache_read_input_tokens),e.cacheCreationInputTokens=Kt(r.cache_creation_input_tokens)),e.totalCostUsd=Kt(t.total_cost_usd),e.numTurns=Kt(t.num_turns),e.durationMs=Kt(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Xu,Qu,Zu,Ay,tp=R(()=>{"use strict";F();mr();Xu=16e3,Qu=5e3,Zu=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Ay="\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 Dy}from"node:child_process";import{existsSync as Uy}from"node:fs";function By(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function rp(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: ${Tt(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=Fy(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=op(o.content);console.log(`[claude] tool_result (error)${i?`: ${Tt(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)} ${Tt(JSON.stringify(e),200)}`),e}function My(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(Tt(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(Tt(r.trim().split(`
|
|
549
553
|
`).slice(-5).join(`
|
|
550
|
-
`),500)),n.join(" \u2014 ")}function
|
|
551
|
-
`))!==-1;){let
|
|
552
|
-
`)){let
|
|
554
|
+
`),500)),n.join(" \u2014 ")}function Gy(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 op(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Fy(t,e){if(!e)return"";if(t==="Write"||t==="Edit"||t==="Read"){let r=e.file_path??e.path;if(typeof r=="string")return`path=${r}`}if(t==="Bash"){let r=e.command;if(typeof r=="string")return`cmd=${Tt(r,80)}`}return""}function Tt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function be(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Hy(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=be(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:be(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 Ky(t,e,r,n){let o=Nt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=be(i.input_tokens),o.outputTokens=be(i.output_tokens),o.cacheReadInputTokens=be(i.cache_read_input_tokens),o.cacheCreationInputTokens=be(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=be(t?.total_cost_usd),o.numTurns=t&&be(t.num_turns)>0?be(t.num_turns):r,o.durationMs=be(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function Wy(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:Tt(c,np)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,p=l?.file_path??l?.path??l?.notebook_path,f=qy(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?Tt(op(s.content),np):"";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 qy(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 gr,lt,Ly,mn,np,mr=R(()=>{"use strict";F();tp();gr=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},lt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Ly=5e3;mn=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return ep(this.binary,e);if(e.signal?.aborted)throw new lt;let r=["-p",By(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=Hy(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+=be(y.input_tokens),s.output+=be(y.output_tokens),s.cacheRead+=be(y.cache_read_input_tokens),s.cacheCreate+=be(y.cache_creation_input_tokens))}}},f=e.role,u=e.onActivity,m=d=>{if(u)for(let h of Wy(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=Dy(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 $=!1,w=null,v=()=>{$=!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")},Ly)};e.signal?.addEventListener("abort",v,{once:!0});let x=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",v)},L="";y.stdout.on("data",E=>{n.push(E),L+=E;let j;for(;(j=L.indexOf(`
|
|
555
|
+
`))!==-1;){let B=L.slice(0,j).trim();if(L=L.slice(j+1),B){let pe=rp(B);p(pe),pe&&m(pe)}}}),y.stderr.on("data",E=>{n.push(E),o.push(E);for(let j of E.split(`
|
|
556
|
+
`)){let B=j.trim();B&&console.warn(`[claude:stderr] ${B}`)}}),y.on("error",E=>{x(),h(E)}),y.on("close",E=>{if(x(),$){h(new lt);return}if(L.trim()){let B=rp(L.trim());p(B),B&&m(B)}let j=i?.is_error===!0;if(E!==0||j){let B=typeof i?.api_error_status=="number"?i.api_error_status:void 0,pe=typeof i?.subtype=="string"?i.subtype:void 0,ye=typeof i?.result=="string"?i.result:void 0;h(new gr(My(E,i,o.join("")),{code:E,apiErrorStatus:B,subtype:pe,resultText:ye,retryAfterMs:Gy(i)}));return}console.log("[claude] exit code=0"),d({artifactPaths:[],log:n.join(""),usage:Ky(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("/")&&Uy(n))}};np=200});import{mkdirSync as Yy,writeFileSync as hr}from"node:fs";import{dirname as Vy,join as yr}from"node:path";function ip(t,e,r){let n=yr(t,e);Yy(Vy(n),{recursive:!0}),hr(n,r)}function Jy(t,e,r){return`# ${t} \u2014 Estimate
|
|
553
557
|
|
|
554
558
|
**Title:** ${e}
|
|
555
559
|
|
|
@@ -570,7 +574,7 @@ production-grade estimates.)
|
|
|
570
574
|
${r.split(`
|
|
571
575
|
`).slice(0,8).join(`
|
|
572
576
|
`).trim()||"(empty)"}
|
|
573
|
-
`}function
|
|
577
|
+
`}function zy(t,e,r,n){let o=n?`
|
|
574
578
|
## Reviewer rework instruction
|
|
575
579
|
|
|
576
580
|
> ${n.split(`
|
|
@@ -599,10 +603,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
599
603
|
${r.split(`
|
|
600
604
|
`).slice(0,8).join(`
|
|
601
605
|
`).trim()||"(empty)"}
|
|
602
|
-
`}function
|
|
606
|
+
`}function Xy(t){return`# ${t} \u2014 Open questions
|
|
603
607
|
|
|
604
608
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
605
|
-
`}function
|
|
609
|
+
`}function Qy(t,e,r){let n=r?` (rework: ${r.split(`
|
|
606
610
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
607
611
|
index 0000000..1111111 100644
|
|
608
612
|
--- a/CHANGELOG.md
|
|
@@ -613,7 +617,7 @@ index 0000000..1111111 100644
|
|
|
613
617
|
+- mock-runner placeholder change for slice 5 testing.
|
|
614
618
|
+
|
|
615
619
|
# Changelog
|
|
616
|
-
`}function
|
|
620
|
+
`}function Zy(t,e,r){return`# ${t} \u2014 Diff summary
|
|
617
621
|
|
|
618
622
|
**Title:** ${e}
|
|
619
623
|
${r?`
|
|
@@ -624,140 +628,140 @@ ${r?`
|
|
|
624
628
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
625
629
|
|
|
626
630
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
627
|
-
`}var
|
|
628
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:
|
|
631
|
+
`}var gn,es=R(()=>{"use strict";F();mr();gn=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=Jy(n,o,i);hr(yr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;hr(yr(e.workspaceDir,"SOLUTION.md"),zy(n,o,i,a)),s.push("SOLUTION.md"),hr(yr(e.workspaceDir,"QUESTIONS.md"),Xy(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;ip(e.workspaceDir,"changes/sample.patch",Qy(n,o,a)),s.push("changes/sample.patch"),ip(e.workspaceDir,"diff-summary.md",Zy(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(hr(yr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
632
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:Nt()}}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 lt;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 hr(yr(e.workspaceDir,"DRAFT.md"),`${o}
|
|
629
633
|
|
|
630
634
|
\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:
|
|
635
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Nt()}}}});function sp(t){switch(t){case"mock":return new gn;case"claude-headless":return new mn;default:return null}}function ap(t,e){let r=e&&e.trim().length>0?e.trim():Xo;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var cp=R(()=>{"use strict";F();mr();es();mr();es()});function pp(t=process.env){return{maxAttempts:To(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:To(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:To(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:To(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function nw(t){if(t instanceof gr){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return tw.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&rw.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:ew.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:lp.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 lp.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function dp(t){if(t instanceof gr){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&up.test(n)}let e=t instanceof Error?t.message:String(t);return up.test(e)}function ow(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 fp(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=nw(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=ow(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 To(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var ew,lp,tw,rw,up,mp=R(()=>{"use strict";mr();ew=new Set([429,500,502,503,529]),lp=/(\bETIMEDOUT\b|\bECONNRESET\b|\bECONNREFUSED\b|\bEAI_AGAIN\b|\bEPIPE\b|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,tw=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,rw=new Set(["error_max_turns"]);up=/(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 iw,rmSync as sw,writeFileSync as gp}from"node:fs";import{tmpdir as aw}from"node:os";import{join as ts}from"node:path";function Io(t){return`[url "https://${t}/"]
|
|
632
636
|
insteadOf = git@${t}:
|
|
633
637
|
insteadOf = ssh://git@${t}/
|
|
634
|
-
`}function
|
|
638
|
+
`}function hp(t,e){if(t.length===0)return null;let r=iw(ts(aw(),"devpipe-gitcreds-")),n=ts(r,"credentials"),o=ts(r,"gitconfig");return gp(n,t.join(`
|
|
635
639
|
`)+`
|
|
636
|
-
`,{mode:384}),
|
|
640
|
+
`,{mode:384}),gp(o,`[credential]
|
|
637
641
|
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{
|
|
639
|
-
`).map(d=>d.trim()).filter(d=>d.length>0);if(u&&m.length===0)throw await
|
|
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
|
|
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=
|
|
644
|
-
`+e.subarray(e.length-
|
|
645
|
-
\u2026 [${r.length-e} bytes elided]`}var
|
|
642
|
+
`+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{sw(r,{recursive:!0,force:!0})}catch{}}}}function rs(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(cw)),t.bitbucket?.apiToken&&(e.push(`https://${Ut}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(lw)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(uw)),hp(e,r)}function yp(t,e){if(t.contextWrite?.token){let r=Qt(e)??"github.com",n=Ln(r);return hp([`https://${n}:${t.contextWrite.token}@${r}`],[Io(r)])}return rs(t)}var cw,lw,uw,wp=R(()=>{"use strict";F();cw=Io("github.com"),lw=Io("bitbucket.org"),uw=Io("gitlab.com")});import{spawn as kp}from"node:child_process";import{existsSync as Co,mkdirSync as hn,readFileSync as pw,rmSync as ns,symlinkSync as dw}from"node:fs";import{homedir as fw}from"node:os";import{dirname as br,join as It}from"node:path";function $p(t){let e=It(fw(),".codepipe-sandbox","repos");return t?It(e,t):e}function vp(t,e){let n=(wr.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{wr.get(t)===o&&wr.delete(t)},()=>{wr.get(t)===o&&wr.delete(t)});return wr.set(t,o),n}function bp(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 mw(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 xp(t,e,r,n,o){let i=async c=>{await J(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await J(t,["reset","--hard",`origin/${c}`],o),await J(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!bp(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Co(t)&&ns(t,{recursive:!0,force:!0}),hn(br(t),{recursive:!0});try{return await J(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!bp(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Co(t)&&ns(t,{recursive:!0,force:!0}),hn(br(t),{recursive:!0}),await J(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Co(It(t,".git")))try{return await s()}catch(c){if(!mw(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 Sp(t){await J(t.workspacePath,["reset","--hard",t.baseSha]),await J(t.workspacePath,["clean","-fdx"])}async function Rp(t,e){let r=t.workspacePath;await J(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:kr,GIT_AUTHOR_EMAIL:$r,GIT_COMMITTER_NAME:kr,GIT_COMMITTER_EMAIL:$r};return(await me(r,["commit-tree",n,"-m",e],i)).trim()}async function Tp(t,e,r,n,o){try{await J(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Qt(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 Ip(t,e){return me(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Cp(t,e,r,n,o){await J(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await J(t.workspacePath,["checkout","--force",r])}async function Ep(t,e,r,n,o,i){let s=t.workspacePath;await J(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 J(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 J(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:kr,GIT_AUTHOR_EMAIL:$r,GIT_COMMITTER_NAME:kr,GIT_COMMITTER_EMAIL:$r},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 J(s,["cherry-pick","--quit"],l).catch(()=>{});let u=null;try{await J(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(`
|
|
643
|
+
`).map(d=>d.trim()).filter(d=>d.length>0);if(u&&m.length===0)throw await J(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 os(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:kr,GIT_AUTHOR_EMAIL:$r,GIT_COMMITTER_NAME:kr,GIT_COMMITTER_EMAIL:$r};(await me(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await J(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 J(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await J(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(`
|
|
644
|
+
`).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 J(t,e,r){return new Promise((n,o)=>{let i=kp("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}):
|
|
645
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function me(t,e,r){return new Promise((n,o)=>{let i=kp("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}):
|
|
646
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function Pp(t,e){Co(t)&&ns(t,{recursive:!0,force:!0}),hn(br(t),{recursive:!0}),dw(e,t,"dir")}async function jp(t,e,r){await J(t,["worktree","prune"]).catch(()=>{}),hn(br(r),{recursive:!0}),await J(t,["worktree","add","--detach",r,`origin/${e}`])}async function gw(t,e,r){hn(br(r),{recursive:!0}),await J(br(r),["clone","--quiet","--no-checkout",t,r]),await J(r,["checkout","--force","--detach",e])}async function Ap(t,e,r,n="worktree",o,i){return r.length===0?[]:vp(e,async()=>{let s=[];for(let a of r){let c=It($p(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await xp(c,a.cloneUrl,a.ref,a.defaultBranch,o)}catch(u){throw new Error(`failed to materialize project repo "${a.name}" (${a.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let p=(await me(c,["rev-parse","HEAD"])).trim(),f=It(t,"code",a.name);n==="direct"?(Pp(f,c),console.log(`[git] code: linked ${f} \u2192 ${c} @ ${p.slice(0,10)}`)):n==="clone"?(await gw(c,p,f),console.log(`[git] code: clone ${f} \u2190 ${c} @ ${p.slice(0,10)}`)):(await jp(c,l,f),console.log(`[git] code: worktree ${f} \u2190 ${c} @ ${p.slice(0,10)}`)),s.push({name:a.name,workspacePath:f,cachePath:c,ref:l,baseSha:p})}return s})}async function _p(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return vp(e,async()=>{let a=It($p(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await xp(a,s.cloneUrl,s.ref,void 0,o)}catch(p){throw new Error(`failed to materialize context repo (${s.cloneUrl}): `+(p instanceof Error?p.message:String(p)))}let c=It(t,"context");n==="direct"?(Pp(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await jp(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await me(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function Np(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await J(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(`
|
|
647
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=pw(It(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var wr,kr,$r,Op=R(()=>{"use strict";F();wr=new Map;kr="CodePipe Agent",$r="codepipe@codepartner.ee"});import{readFileSync as hw}from"node:fs";import{join as yw}from"node:path";function Dp(t){let e=yw(t,yn),r;try{r=hw(e,"utf-8")}catch{throw new Ct(`BUILD produced no ${yn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(p){throw new Ct(`${yn} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!n||typeof n!="object")throw new Ct(`${yn} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Ct(`${yn}: "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"?ww(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 ww(t){let e=Buffer.from(t,"utf-8");return e.length<=is?t:`\u2026 [${e.length-is} bytes elided] \u2026
|
|
648
|
+
`+e.subarray(e.length-is).toString("utf-8")}var is,Ct,yn,Up=R(()=>{"use strict";is=8*1024,Ct=class extends Error{},yn="meta/build-result.json"});import{readFileSync as bw}from"node:fs";import{join as kw}from"node:path";function Bp(t){let e=kw(t,vr),r;try{r=bw(e,"utf-8")}catch{throw new ut(`code review produced no ${vr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new ut(`${vr} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new ut(`${vr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new ut(`${vr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?Lp(o.remarks,$w):"";if(!i&&s.trim().length===0)throw new ut(`${vr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?Lp(o.summary,vw):"";return{approved:i,remarks:s,summary:a}}function Lp(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
|
|
649
|
+
\u2026 [${r.length-e} bytes elided]`}var $w,vw,ut,vr,Mp=R(()=>{"use strict";$w=16*1024,vw=4*1024,ut=class extends Error{},vr="meta/review-result.json"});import{readFileSync as xw,statSync as Sw}from"node:fs";import{join as Gp}from"node:path";function jw(t){return t.startsWith("meta/")||Pw.has(t)}function Aw(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 _w(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Fp(t,e,r){let n=r?.maxBytes??Rw,o=r?.totalBytes??Tw,i=r?.maxCount??Iw,s=e.map((d,h)=>{let y=null;try{y=Sw(Gp(t,d)).size}catch{}return{path:d,index:h,size:y}}),a=[...s].sort((d,h)=>{let y=$=>jw($.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=xw(Gp(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?_w(d.path):Aw(d.path,d.size,n,o),$=Buffer.from(y,"utf-8");u+=$.length,p[d.index]={path:d.path,contentBase64:$.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,Ew),h=`# Artifacts omitted from upload
|
|
646
650
|
|
|
647
651
|
${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
652
|
|
|
649
653
|
`+d.map(y=>`- ${y}
|
|
650
654
|
`).join("")+(l.length>d.length?`
|
|
651
655
|
\u2026and ${l.length-d.length} more.
|
|
652
|
-
`:"");m.push({path:
|
|
656
|
+
`:"");m.push({path:Cw,contentBase64:Buffer.from(h,"utf-8").toString("base64")})}return{artifacts:m,omitted:f,dropped:l}}var Rw,Tw,Iw,Cw,Ew,Pw,Hp=R(()=>{"use strict";Rw=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),Tw=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),Iw=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),Cw="artifacts-omitted.md",Ew=500,Pw=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 Nw,mkdtempSync as Ow,readFileSync as Dw,readdirSync as Wp,rmSync as Kp}from"node:fs";import{tmpdir as Uw}from"node:os";import{join as Eo,relative as Lw}from"node:path";function qp(t){let e=Ow(Eo(Uw(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Kp(e,{recursive:!0,force:!0}),listFiles:()=>Yp(e,e),readFile:r=>Dw(Eo(e,r),"utf-8"),clean:()=>{for(let r of Wp(e))Mw.has(r)||Kp(Eo(e,r),{recursive:!0,force:!0})}}}function Yp(t,e){let r=[];for(let n of Wp(e)){let o=Eo(e,n),i=Nw(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Bw.has(n))continue;r.push(...Yp(t,o))}else r.push(Lw(t,o))}return r}var Bw,Mw,Vp=R(()=>{"use strict";Bw=new Set(["code","context","scratch"]),Mw=new Set(["code","context"])});import{mkdirSync as Gw,readFileSync as Jp,readdirSync as Fw,writeFileSync as Hw}from"node:fs";import{homedir as Kw}from"node:os";import{dirname as Ww,join as xr}from"node:path";function Yw(t){let e=Buffer.from(t,"utf-8");if(e.length<=Po)return t;let r=Math.floor(Po/4),n=Po-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}
|
|
653
657
|
|
|
654
658
|
\u2026 [${s} bytes elided \u2014 log capped at ${Po} bytes for upload] \u2026
|
|
655
659
|
|
|
656
|
-
${i}`}function
|
|
660
|
+
${i}`}function Vw(){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 wn(t={}){So();let e=ge(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,i=Vu(t.profile,e.sandboxId,!!M("SANDBOX_CONFIG")),s=xr(Kw(),".codepipe","logs"),a=qn("SANDBOX_LOG",i,s);if(a.enabled){let A=new rr(a);Yn(A),console.log(`[log] file logging \u2192 ${A.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Te} (protocol ${Fe})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=sp(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=pp();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let p=new fr(e.hubUrl,e.token),f=!1,u=new AbortController,m=new Map,d=null,h=null,y=!1,$=()=>{let A=p.openControlSocket();return d=A,A.on("open",()=>{console.log("[ws] connected");let g={type:"sandbox_hello",platformVersion:Te,protocolVersion:Fe};A.send(JSON.stringify(g))}),A.on("message",g=>{let I=g.toString("utf-8"),k=null;try{let T=JSON.parse(I);T&&typeof T=="object"&&(k=T)}catch{}if(k&&k.type==="hello"){let T=k;h=An(T.protocolVersion);let P=h?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${T.platformVersion} (protocol ${T.protocolVersion}) \u2014 ${P}`),h&&(y=!1);return}if(k&&k.type==="pause_job"){let T=typeof k.jobId=="string"?k.jobId:"",P=T?m.get(T):void 0;P?(console.warn(`[ws] pause_job ${T} \u2014 aborting agent`),P.paused=!0,P.abort.abort()):console.log(`[ws] pause_job ${T} \u2014 not a running job, ignoring`),T&&A.send(JSON.stringify({type:"job_paused",jobId:T}));return}if(k&&(k.type==="chat_user_message"||k.type==="chat_finalize")){let T=typeof k.jobId=="string"?k.jobId:"",P=T?m.get(T):void 0;if(P?.chatInbox)if(k.type==="chat_user_message"){let b=typeof k.text=="string"?k.text:"";b.trim()&&P.chatInbox.push({kind:"user",text:b})}else P.chatInbox.finalize();else console.log(`[ws] ${String(k.type)} ${T} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${I}`)}),A.on("close",(g,I)=>{console.log(`[ws] closed code=${g} reason=${I?.toString()||""}`),d===A&&(d=null),!f&&setTimeout($,2e3)}),A.on("error",g=>console.warn(`[ws] error: ${g.message}`)),A},w=$(),v=async A=>{for(;!f;){if(h===!1){y||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Te}, protocol ${Fe}) \u2014 not claiming jobs until versions align.`),y=!0),await new Promise(g=>setTimeout(g,5e3));continue}try{let g=await p.claim(u.signal,A);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,f=!0;break}if(!g.ok){console.warn(`[claim:${A}] ${g.status} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3));continue}let I=await g.json();await x(p,I)}catch(g){if(u.signal.aborted)break;let I=g instanceof Error?g.message:String(g);console.warn(`[claim:${A}] error: ${I} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3))}}};async function x(A,g){let I={abort:new AbortController,paused:!1};g.role==="chat"&&(I.chatInbox=Vw()),m.set(g.jobId,I);let k=!1,T=null,P=null,b=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),S=async()=>{try{await A.heartbeat(g.jobId)==="claim_lost"&&(k=!0,console.warn(`[job] ${g.jobId} claim lost \u2014 HUB sweeper took it`))}catch(q){let Ne=q instanceof Error?q.message:String(q);console.warn(`[job] ${g.jobId} heartbeat error: ${Ne}`)}};S();let W=setInterval(()=>{S()},b),H=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(E(g.prompt," \u2502 "));let Qe=[],pt=null,Fo=400,_=25,de=500,$e=()=>{if(pt&&(clearTimeout(pt),pt=null),Qe.length===0)return;let q=Qe.splice(0,Qe.length),Ne=d;if(!Ne||Ne.readyState!==Ne.OPEN)return;let et={type:"agent_activity",jobId:g.jobId,taskId:g.taskId,projectId:g.projectId,role:g.role,phase:g.phase,events:q};try{Ne.send(JSON.stringify(et))}catch{}},Ze=q=>{Qe.push(q),Qe.length>de&&Qe.shift(),Qe.length>=_?$e():pt||(pt=setTimeout($e,Fo))},_t=g.role==="analysis"&&g.taskId.startsWith("draft::")?g.taskId.slice(7):null,dt=new Set,le=null;try{if(!c){k||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:H,finishedAt:new Date().toISOString()});return}if(!ap(o,g.provider??null)){k||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${g.provider??"claude"}"`},startedAt:H,finishedAt:new Date().toISOString()});return}let q=qp(g.jobId);console.log(`[job] ${g.jobId} workspace=${q.dir}`);let Ne=L(g,r);T=Ne.gitCreds,P=Ne.contextGitCreds;let et=T?.env,Es=Ne.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Ne.claudeOauthToken}:void 0,tt=[],Lr=null,Ho=null;try{let O=g.role==="build"?"clone":"worktree";tt=await Ap(q.dir,g.projectId,g.projectRepos,O,et,n);let D=await _p(q.dir,g.projectId,g.contextRepo,"worktree",et,n);Ho=D,Lr=D?.workspacePath??null}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} materialize failed: ${D}`),k||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${D}`},startedAt:H,finishedAt:new Date().toISOString()}),q.dispose();return}let Ps=async()=>{if(!g.deliveries||g.deliveries.length===0)return[];let O=g.contextRepo?.cloneUrl;if(!O||!et)throw new Error(O?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let D=[];for(let Y of g.deliveries){let K=tt.find(ie=>ie.name===Y.name);if(K){if(g.role==="implement"&&Y.baseSha&&Y.baseSha!==K.baseSha){let ie=await Ep(K,Y.deliveryRef,Y.deliverySha,Y.baseSha,O,et);console.log(`[job] ${g.jobId} ${K.name}: base moved ${Y.baseSha.slice(0,10)} \u2192 ${K.baseSha.slice(0,10)} \u2014 re-applied delivery ${Y.deliverySha.slice(0,10)} (${ie.length} conflicted file(s))`),ie.length>0&&D.push(`- **${K.name}**:`,...ie.map(Br=>` - \`${Br}\``));continue}await Cp(K,Y.deliveryRef,Y.deliverySha,O,et),console.log(`[job] ${g.jobId} ${K.name}: checked out delivery ${Y.deliverySha.slice(0,10)} for ${g.role}`)}}return D},Ko=[];if(g.role==="build"||g.role==="implement"||g.role==="code-review")try{Ko=await Ps()}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} delivery checkout failed: ${D}`),k||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${D}`},startedAt:H,finishedAt:new Date().toISOString()}),q.dispose();return}let Wo=g.role==="resolve-conflict"?g.metadata?.taskBranchByRepo??{}:{},js="";if(g.role==="resolve-conflict"){if(!tt.some(O=>Wo[O.name])){let O="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${g.jobId} ${O}`),k||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:H,finishedAt:new Date().toISOString()}),q.dispose();return}try{let O=[];for(let D of tt){let Y=Wo[D.name];if(!Y)continue;let K=await os(D,Y,et);console.log(`[job] ${g.jobId} ${D.name}: merged ${Y} into ${D.ref} \u2014 ${K.length} conflicted file(s)`),K.length>0?O.push(`- **${D.name}**:`,...K.map(ie=>` - \`${ie}\``)):O.push(`- **${D.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}js=`
|
|
657
661
|
|
|
658
662
|
## Conflicts to resolve
|
|
659
663
|
|
|
660
|
-
`+(
|
|
664
|
+
`+(O.length>0?O.join(`
|
|
661
665
|
`):"(no task branches to merge)")+`
|
|
662
|
-
`}catch(
|
|
666
|
+
`}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} conflict merge failed: ${D}`),k||await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${D}`},startedAt:H,finishedAt:new Date().toISOString()}),q.dispose();return}}let If=Ko.length>0?`
|
|
663
667
|
|
|
664
668
|
## Base branch moved \u2014 conflicts to resolve
|
|
665
669
|
|
|
666
670
|
The base branch advanced since the previous iteration; its delivery was re-applied on top of the fresh base. These files now contain git conflict markers (\`<<<<<<<\`) \u2014 resolve them (keep both the base branch's changes and this task's changes) as part of this job:
|
|
667
671
|
|
|
668
|
-
`+
|
|
672
|
+
`+Ko.join(`
|
|
669
673
|
`)+`
|
|
670
|
-
`:"",
|
|
671
|
-
`).map(
|
|
672
|
-
`)}function
|
|
673
|
-
[${A}] shutting down`),f.abort();let g=[...u.keys()];for(let v of u.values())v.abort.abort();let S=new AbortController,x=setTimeout(()=>S.abort(),3e3);(async()=>(await Promise.all(g.map(async v=>{try{await l.releaseJob(v,`sandbox ${A}`,S.signal),console.log(`[${A}] released job ${v}`)}catch(E){let _=E instanceof Error?E.message:String(E);console.warn(`[${A}] release failed: ${_} (sweeper will reclaim)`)}})),clearTimeout(x),b.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>G("SIGINT")),process.on("SIGTERM",()=>G("SIGTERM"));let de=[w("implementation")];e.planningLane!==!1?de.push(w("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(de)}var Po,Fw,qp=I(()=>{"use strict";q();Pe();ii();op();up();Te();So();mp();Ji();jp();_p();Dp();Bp();Kp();Po=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Fw=new Set(["implement","resolve-conflict"])});var vr=I(()=>{"use strict";Yu();qp();So()});async function Sr(t,e,r){return e.host==="github"?qw(t,e,r):e.host==="gitlab"?Zw(t,e,r):tb(t,e,r)}async function Vp(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 Ct(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Jp(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await It(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await zp(e.gitlabToken,t):o}}return e.bitbucket?(await xr(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Xp(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 Jp(t,e){let r=!1;try{r=(await Ct(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 zp(t,e){let r=!1;try{r=(await It(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function Xp(t,e){let r=!1;try{r=(await xr(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 Ct(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(Ww+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 qw(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 Yw(n,e,r),i=await Jw(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=ir(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await zw(n,o.owner,o.name,a.path,i)||await Xw(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 Yw(t,e,r){let n=await Ct(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 Jp(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Vw(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 Ct(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 Vw(t,e){let{status:r,data:n}=await Ct(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Jw(t,e,r){let{data:n}=await Ct(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function zw(t,e,r,n,o){let{status:i,data:s}=await Ct(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Xw(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 Ct(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function It(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(Qw+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 Zw(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await It(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await zp(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await It(n,"GET","/user"),u={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let d=await It(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 It(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=ir(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let m=(await It(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 It(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function xr(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(eb+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 tb(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 xr(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 Xp(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 xr(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=ir(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await xr(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 xr(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 Ww,Qw,eb,Eo=I(()=>{"use strict";Bt();Ww="https://api.github.com";Qw="https://gitlab.com/api/v4";eb="https://api.bitbucket.org/2.0"});function je(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=rb[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 rb,jo=I(()=>{"use strict";rb={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as nb}from"node:crypto";import{existsSync as Qp,mkdirSync as ob,readFileSync as Zp,readdirSync as ib,rmSync as Ao,writeFileSync as sb}from"node:fs";import{homedir as ab}from"node:os";import{dirname as cb,join as os}from"node:path";function ed(){return os(ab(),".codepipe","init-drafts")}function is(t){let e=nb("sha256").update(t).digest("hex").slice(0,16);return os(ed(),`${e}.json`)}function td(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=lb)}function rd(t){let e=is(t);if(!Qp(e))return null;try{let r=JSON.parse(Zp(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:td(r.savedAt)?(Ao(e,{force:!0}),null):r}catch{return null}}function ss(t){Ao(is(t),{force:!0})}function nd(){let t=ed();if(Qp(t))for(let e of ib(t)){let r=os(t,e);try{let n=JSON.parse(Zp(r,"utf-8"));td(n.savedAt)&&Ao(r,{force:!0})}catch{Ao(r,{force:!0})}}}var lb,Rr,od=I(()=>{"use strict";lb=24*60*60*1e3;Rr=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(){ss(this.cwd)}persist(){let e=is(this.cwd);ob(cb(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};sb(e,JSON.stringify(r,null,2)+`
|
|
674
|
-
`,{mode:384})}}});function
|
|
675
|
-
`).map(n=>n.trim()).filter(Boolean);return
|
|
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`),
|
|
674
|
+
`:"",Cf=B(j(g.prompt,tt,Lr),Lr,g.taskId)+js+If,qo=[...tt.map(O=>O.workspacePath),...Lr?[Lr]:[]];qo.length>0&&console.log(`[job] ${g.jobId} --add-dir: ${qo.join(", ")}`),_t&&(le=setInterval(()=>{let D=d;if(!D||D.readyState!==D.OPEN)return;let Y;try{Y=Fw(xr(q.dir,"drafts")).filter(K=>K.endsWith(".json")).sort()}catch{return}for(let K of Y){if(dt.has(K))continue;if(dt.size>=Ia)break;let ie;try{let Oe=JSON.parse(Jp(xr(q.dir,"drafts",K),"utf-8")),Jt=typeof Oe.localRef=="string"?Oe.localRef:"",Pn=typeof Oe.title=="string"?Oe.title:"",Yo=typeof Oe.body=="string"?Oe.body:"";if(!Jt||!Pn)continue;ie={localRef:Jt,title:Pn,body:Yo,...Oe.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Oe.links)?{links:Oe.links}:{}}}catch{continue}dt.add(K);let Br={type:"child_draft",jobId:g.jobId,projectId:g.projectId,draftId:_t,child:ie};try{D.send(JSON.stringify(Br))}catch{}}},1500));try{let O={workspaceDir:q.dir,role:g.role,prompt:Cf,addDirs:qo,metadata:g.metadata??{},...g.model?{model:g.model}:{},...Es?{env:Es}:{},signal:I.abort.signal,onActivity:Ze},D=I.chatInbox?await c.run({...O,interactive:{inbox:I.chatInbox.iterable}}):await fp(c,O,{jobId:g.jobId,policy:l,onBeforeRetry:async()=>{q.clean();for(let Q of tt)try{await Sp(Q);let se=Wo[Q.name];g.role==="resolve-conflict"&&se&&await os(Q,se,et)}catch(se){let Mr=se instanceof Error?se.message:String(se);console.warn(`[job] ${g.jobId} worktree reset failed (${Q.name}): ${Mr}`)}try{await Ps()}catch(Q){let se=Q instanceof Error?Q.message:String(Q);console.warn(`[job] ${g.jobId} delivery re-checkout failed: ${se}`)}},aborted:()=>k||I.paused}),Y=[];if(qw.has(g.role)&&tt.length>0){let Q=g.metadata??{},se=typeof Q.commitMessage=="string"?Q.commitMessage:`${g.taskId}: changes`,Mr=g.contextRepo?.cloneUrl,_s=P?.env;if(!Mr||!_s)throw new Error("delivery requested but "+(Mr?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Ef=g.taskId.includes(":")?g.taskId.slice(g.taskId.indexOf(":")+1):g.taskId;for(let rt of tt){let Gr=await Rp(rt,se);if(!Gr){console.log(`[job] ${g.jobId} ${rt.name}: no changes \u2014 no delivery`);continue}let Vo=`codepipe/deliveries/${Ef}/${g.jobId}/${rt.name}`;await Tp(rt,Gr,Vo,Mr,_s),Y.push({name:rt.name,deliveryRef:Vo,deliverySha:Gr,baseSha:rt.baseSha}),console.log(`[job] ${g.jobId} ${rt.name}: delivered ${Gr.slice(0,10)} \u2192 ${Vo}`);let Ns=await Ip(rt,Gr);if(Ns.trim().length>0){let Pf=xr("display",`${rt.name}.diff`),Os=xr(q.dir,Pf);Gw(Ww(Os),{recursive:!0}),Hw(Os,Ns)}}}if(g.role==="resolve-conflict"&&Y.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 K;g.role==="build"&&(K=Dp(q.dir),console.log(`[job] ${g.jobId} build verdict: ok=${K.ok}`+(K.failedStep?` failedStep=${K.failedStep}`:"")));let ie;g.role==="code-review"&&(ie=Bp(q.dir),console.log(`[job] ${g.jobId} review verdict: approved=${ie.approved}`));let Br=D.artifactPaths.length>0?D.artifactPaths:q.listFiles(),Oe=Array.from(new Set(Br)),Jt;if(Ho)try{let Q=g.role==="index"?["adr/SOURCES.md"]:g.role==="backfill"?["adr"]:[],se=await Np(Ho,Q);se.length>0&&(Jt=se,console.log(`[job] ${g.jobId} captured ${se.length} knowledge file(s) for Context Repo`))}catch(Q){let se=Q instanceof Error?Q.message:String(Q);console.warn(`[job] ${g.jobId} knowledge capture failed (non-fatal): ${se}`)}let{artifacts:Pn,omitted:Yo,dropped:As}=Fp(q.dir,Oe);for(let Q of Yo)console.warn(`[job] ${g.jobId} artifact ${Q.path} (${Q.bytes} bytes) exceeded upload budget \u2014 content omitted`);As.length>0&&console.warn(`[job] ${g.jobId} artifact listing truncated: ${As.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let jn={jobId:g.jobId,status:"succeeded",artifacts:Pn,...Jt?{contextWrites:Jt}:{},...Y.length>0?{deliveries:Y}:{},log:Yw(D.log),startedAt:H,finishedAt:new Date().toISOString(),usage:D.usage,...D.rateLimit?{rateLimit:D.rateLimit}:{},...K?{build:K}:{},...ie?{review:ie}:{}};if(k||I.paused)console.warn(`[job] ${g.jobId} skipping result upload \u2014 ${I.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await A.submitResult(jn),console.log(`[job] ${g.jobId} done \u2014 uploaded ${jn.artifacts.length} artifact(s):`);for(let Q of jn.artifacts){let se=Buffer.from(Q.contentBase64,"base64").length;console.log(` \xB7 ${Q.path} (${se} bytes)`)}jn.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(O){let D=O instanceof Error?O.message:String(O);if(I.paused)console.log(`[job] ${g.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(k)console.warn(`[job] ${g.jobId} failed after claim lost (${D}) \u2014 skipping result upload`);else{let Y=dp(O),K=O instanceof Ct,ie=O instanceof ut;console.warn(Y?`[job] ${g.jobId} failed: ${D} (Claude auth \u2014 token invalid/expired)`:K?`[job] ${g.jobId} failed: ${D} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:ie?`[job] ${g.jobId} failed: ${D} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${g.jobId} failed: ${D}`),await A.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:D},startedAt:H,finishedAt:new Date().toISOString(),...Y?{authError:!0}:{},...K?{buildInconclusive:!0}:{},...ie?{reviewInconclusive:!0}:{}})}}finally{q.dispose()}}finally{clearInterval(W),le&&clearInterval(le),$e(),I.chatInbox?.close(),m.delete(g.jobId),T?.cleanup(),P?.cleanup()}}function L(A,g){if(!A.credBundle)return{gitCreds:null,contextGitCreds:null};if(!g)return console.warn(`[job] ${A.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let I;try{I=JSON.parse(lr(g,A.credBundle).toString("utf-8"))}catch(b){return console.warn(`[job] ${A.jobId} failed to open credBundle: ${b instanceof Error?b.message:String(b)}`),{gitCreds:null,contextGitCreds:null}}let k=rs(I);k&&console.log(`[job] ${A.jobId} cred bundle opened \u2014 git creds configured`);let T=yp(I,A.contextRepo.cloneUrl),P={gitCreds:k,contextGitCreds:T};return I.claudeOauthToken&&(P.claudeOauthToken=I.claudeOauthToken),P}function E(A,g){return A.split(`
|
|
675
|
+
`).map(I=>g+I).join(`
|
|
676
|
+
`)}function j(A,g,I){let k=g[0]?.workspacePath??"";return A.replace(/\{\{codeDir\}\}/g,k).replace(/\{\{codeRoot\}\}/g,k?k.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,I??"")}function B(A,g,I){let k=A,T=I.includes("::")?"":I.split(":",2)[1]??"",P=b=>{if(!g||!T)return"";try{return Jp(xr(g,"tasks",T,b),"utf-8").trim()}catch{return""}};if(k.includes("{{solutionMd}}")){let b=P("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";k=k.replace(/\{\{solutionMd\}\}/g,()=>b)}if(k.includes("{{taskDescription}}")){let b=P("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";k=k.replace(/\{\{taskDescription\}\}/g,()=>b)}return k}let pe=A=>{if(f)return;f=!0,console.log(`
|
|
677
|
+
[${A}] shutting down`),u.abort();let g=[...m.keys()];for(let T of m.values())T.abort.abort();let I=new AbortController,k=setTimeout(()=>I.abort(),3e3);(async()=>(await Promise.all(g.map(async T=>{try{await p.releaseJob(T,`sandbox ${A}`,I.signal),console.log(`[${A}] released job ${T}`)}catch(P){let b=P instanceof Error?P.message:String(P);console.warn(`[${A}] release failed: ${b} (sweeper will reclaim)`)}})),clearTimeout(k),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>pe("SIGINT")),process.on("SIGTERM",()=>pe("SIGTERM"));let ye=[v("implementation")];e.planningLane!==!1?ye.push(v("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(ye)}var Po,qw,zp=R(()=>{"use strict";F();je();ai();cp();mp();Ce();Ro();wp();Xi();Op();Up();Mp();Hp();Vp();Po=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),qw=new Set(["implement","resolve-conflict"])});var Sr=R(()=>{"use strict";zu();zp();Ro()});async function Tr(t,e,r){return e.host==="github"?zw(t,e,r):e.host==="gitlab"?nb(t,e,r):ib(t,e,r)}async function Qp(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 Pt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Zp(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 Et(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await ed(e.gitlabToken,t):o}}return e.bitbucket?(await Rr(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await td(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 Zp(t,e){let r=!1;try{r=(await Pt(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 ed(t,e){let r=!1;try{r=(await Et(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 td(t,e){let r=!1;try{r=(await Rr(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 Pt(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(Jw+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 zw(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 Xw(n,e,r),i=await Zw(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=ar(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await eb(n,o.owner,o.name,a.path,i)||await tb(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 Xw(t,e,r){let n=await Pt(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 Zp(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Qw(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 Pt(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 Qw(t,e){let{status:r,data:n}=await Pt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Zw(t,e,r){let{data:n}=await Pt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function eb(t,e,r,n,o){let{status:i,data:s}=await Pt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function tb(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 Pt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Et(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(rb+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 nb(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 Et(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 ed(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Et(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 Et(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 Et(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=ar(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let m=(await Et(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 Et(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 Rr(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(ob+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 ib(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 Rr(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 td(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 Rr(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=ar(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await Rr(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 Rr(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 Jw,rb,ob,jo=R(()=>{"use strict";Gt();Jw="https://api.github.com";rb="https://gitlab.com/api/v4";ob="https://api.bitbucket.org/2.0"});function _e(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=sb[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 sb,Ao=R(()=>{"use strict";sb={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as ab}from"node:crypto";import{existsSync as rd,mkdirSync as cb,readFileSync as nd,readdirSync as lb,rmSync as _o,writeFileSync as ub}from"node:fs";import{homedir as pb}from"node:os";import{dirname as db,join as ss}from"node:path";function od(){return ss(pb(),".codepipe","init-drafts")}function as(t){let e=ab("sha256").update(t).digest("hex").slice(0,16);return ss(od(),`${e}.json`)}function id(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=fb)}function sd(t){let e=as(t);if(!rd(e))return null;try{let r=JSON.parse(nd(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:id(r.savedAt)?(_o(e,{force:!0}),null):r}catch{return null}}function cs(t){_o(as(t),{force:!0})}function ad(){let t=od();if(rd(t))for(let e of lb(t)){let r=ss(t,e);try{let n=JSON.parse(nd(r,"utf-8"));id(n.savedAt)&&_o(r,{force:!0})}catch{_o(r,{force:!0})}}}var fb,Ir,cd=R(()=>{"use strict";fb=24*60*60*1e3;Ir=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(){cs(this.cwd)}persist(){let e=as(this.cwd);cb(db(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};ub(e,JSON.stringify(r,null,2)+`
|
|
678
|
+
`,{mode:384})}}});function ld(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 ud(){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 pd(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 dd=R(()=>{"use strict"});import{existsSync as mb}from"node:fs";import{join as gb}from"node:path";import{simpleGit as hb}from"simple-git";function kb(t){let e=t.split("/");return e[e.length-1]??t}function fd(t){if(t.filter(r=>!wb.test(kb(r))).length>yb)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(bb.has(n))return!0}return!1}async function $b(t){try{let r=(await hb(t).raw(["ls-files"])).split(`
|
|
679
|
+
`).map(n=>n.trim()).filter(Boolean);return fd(r)}catch{return!1}}async function vb(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)?fd(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function md(t,e){for(let r of t)try{let n=e.localRoot!=null?gb(e.localRoot,r.mountAs??r.name):null;if(n&&mb(n)?await $b(n):await vb(r,e.tokens))return!0}catch{}return!1}var yb,wb,bb,gd=R(()=>{"use strict";yb=3,wb=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,bb=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as hd}from"node:fs";import{join as yd}from"node:path";import{simpleGit as wd}from"simple-git";async function kn(t,e,r={}){let n=r.log??xb,o=[];for(let i of e){let s=yd(t,i.mountAs),a=ja(i);if(!hd(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 wd().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(p){let f=bn(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(!hd(yd(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=wd(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Sb(l,a)){n.warn(`${i.mountAs}/ origin (${bn(l)||"none"}) != expected (${bn(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:bn(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=bn(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 Sb(t,e){return bd(t)===bd(e)}function bd(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function bn(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function kd(t={}){let e=Ee();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 kn(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 xb,No=R(()=>{"use strict";ot();xb={info:t=>console.log(t),warn:t=>console.warn(t)}});var vd={};Af(vd,{upCommand:()=>ls});import{spawn as Rb}from"node:child_process";import{existsSync as $d}from"node:fs";import{homedir as Tb,hostname as Ib}from"node:os";import{join as Oo}from"node:path";async function Cb(t,e,r){let n=ge(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Me(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 tu(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 ${Me(e)} still holds its token.
|
|
680
|
+
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`),Ja(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function Eb(t,e,r){let n=ge(e)!==null;if(!await Cb(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 wo(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof N&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof N&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof N?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await Ht({hub:t.hubUrl,token:o,name:r.name??`${Ib()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function Pb(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=we(r.sealPublicKey);if(!U(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Kn(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 jb(t,e){let r=process.cwd(),n=Oo(r,We);if(Gn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if($d(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 V(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 ps(r);if(!Pa(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=U(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await xo({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=Oo(Tb(),".codepipe",e?Oo("profiles",e,"context-config"):"context-config");if(zn(c.contextDir,l,a),!$d(Oo(c.contextDir,"project.yaml"))){ir(c.contextDir);let p={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Vr(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 ls(t){let{cfg:e,profile:r}=Hn(t.profile);await jb(e,r),await Eb(e,r,t),Pb(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=>$=>{for(let w of $.toString("utf-8").split(`
|
|
677
681
|
`))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
|
|
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
|
|
680
|
-
${
|
|
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:
|
|
682
|
+
`)};m.stdout?.on("data",h(process.stdout)),m.stderr?.on("data",h(process.stderr))},i=(m,d)=>{let h=Rb(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(`
|
|
683
|
+
[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,$)=>h({name:m,code:y??($?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 us=R(()=>{"use strict";je();Sr();ve();st();Vi();Gt();fe();te();ot();$n()});import{spawn as Ab}from"node:child_process";import{existsSync as Cr,mkdirSync as Sd,readFileSync as Rd,readdirSync as _b,writeFileSync as Td}from"node:fs";import{join as Wt,resolve as Id}from"node:path";import{setTimeout as ds}from"node:timers/promises";import{cancel as Nb,confirm as Er,intro as Cd,isCancel as Do,log as C,outro as fs,password as Pr,select as ze,spinner as gs,text as re}from"@clack/prompts";import{simpleGit as Lo}from"simple-git";function Z(t){Nb(t),process.exit(1)}function ke(t){return Do(t)&&Z("aborted"),t}function z(t){return Do(t)&&Z("aborted"),typeof t=="string"?t:""}async function Ed(t={}){Cd("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();ad();let r=sd(e),n,o=!1;r&&Object.keys(r.answers).length>0?ke(await Er({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(C.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Ir(e,r),o=!0):(cs(e),n=new Ir(e)):n=new Ir(e);let i=t.force===!0?null:await ps(e),s=await n.ask("target",async()=>ke(await ze({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?C.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||jd(e,t.force===!0));let c=await n.ask("hubUrl",async()=>z(await re({message:"HUB URL",placeholder:Ge,initialValue:M("HUB_URL")??Ge,validate:_=>_.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>jr()),{cliToken:p,accountEmail:f}=await n.ask("bootstrap",()=>Ar(c,l)),u=null;s==="farm"&&(u=await Ob(c,p));let m=a?Ub(a.parsed.repoName):"",d=await n.ask("projectId",async()=>z(await re({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:_=>Dt.test(_.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await n.ask("projectName",async()=>z(await re({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:_=>_.trim().length>0?void 0:"required"})).trim()),y=await n.ask("automationLevel",async()=>ke(await ze({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),$=s==="farm"?"auto":await n.ask("applyMode",async()=>ke(await ze({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),w=await n.ask("trackerProvider",async()=>ke(await ze({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"}))),v=w==="internal",x=null,L,E=!0;if(v){let _,de=gs();de.start("checking task-key prefixes on your account\u2026");try{_=await ru(c,p,{excludeProjectId:d}),de.stop("prefixes checked")}catch{de.stop("could not reach the HUB",1),Z("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 $e=$a(ka(h),_);L=await n.ask("trackerPrefix",async()=>z(await re({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:$e,initialValue:$e,validate:Ze=>{let _t=Ze.trim();if(!Xt.test(_t))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(_.has(_t.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else x=await n.ask("youtrack",()=>Bd()),L=await n.ask("youtrackProjectKey",async()=>z(await re({message:"YouTrack project key",placeholder:"DEV",validate:_=>_.trim().length>0?void 0:"required"})).trim()),E=await n.ask("youtrackWrites",async()=>ke(await Er({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let j=n.get("tokens")??{},B=()=>n.set("tokens",j),pe=await n.ask("repos",()=>Mb(j,l,a,{onCred:B,initial:n.get("reposPartial")??[],onProgress:_=>n.set("reposPartial",_)}));n.delete("reposPartial");let ye=await Gb(await n.ask("contextRepo",()=>Dd(d,pe,j,l)),d,pe,j,l,B,_=>n.set("contextRepo",_)),{spec:A,mode:g}=ye,I;v||(C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),I=await n.ask("assigneeLogin",async()=>z(await re({message:"your YouTrack login (the assignee value)",...x?.login?{initialValue:x.login}:{},validate:_=>_.trim().length>0?void 0:"required"})).trim()));let k=await n.ask("claudeToken",()=>Vb(s==="farm")),T={projectId:d,name:h,automationLevel:y,repos:pe,trackerProvider:w,youtrackProjectKey:L};C.step(`${g==="attach"?"attaching to":"provisioning"} Context Repo ${A.owner}/${A.name} (${A.host})\u2026`);let P;try{P=await Tr(T,A,{...Ud(j),youtrackWrites:E,...x?{trackerUrl:x.url}:{},mode:g,log:{info:_=>C.message(_),warn:_=>C.warn(_)}})}catch(_){Z(`Context Repo provisioning failed: ${_ instanceof Error?_.message:String(_)}`)}T.contextRepo=P,C.success(`Context Repo ready: ${P.owner}/${P.name}@${P.branch}`),C.step(`registering project on ${c}\u2026`);let b;try{b=await St(c,p,T)}catch(_){if(_ instanceof N&&_.status===409){C.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{b=await V(c,p,d)}catch(de){throw de instanceof N&&Z(`HUB \u2192 ${de.status} ${de.message}`),de}}else if(_ instanceof N&&_.status===401)n.delete("cliToken"),Z("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(_ instanceof N)Z(`HUB \u2192 ${_.status} ${_.message}`);else throw _}let S=b.contextRepo??P;C.success(`project ${b.projectId} ready (${b.provisioningStatus})`);let W=await qb(S),H=x?{url:x.url,token:x.token}:void 0;if(s==="farm"){let _=u,de={...j,...W?{contextWrite:W}:{},...k?{claude:{oauthToken:k}}:{},...H?{youtrack:H}:{}},$e=j.github?.token;if(S.host==="github"&&$e)try{let le=Nu(`devpipe-${d}`);await Ou(S,$e,le.publicKey,`devpipe-${d}`),de.contextSsh={privateKey:le.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(le){C.warn(`could not set up Context Repo SSH deploy key (${le instanceof Error?le.message:String(le)}); the farm will fall back to the token path.`)}let Ze={projectId:d,config:{hubUrl:c,cliToken:p,projectId:d},secrets:de,contextRepo:S,projectConfig:Ve(T,E,x?.url,I||void 0,"auto")},_t=ct(_.farm.publicKey,JSON.stringify(Ze));C.step(`handing project ${d} to farm ${_.farm.name}\u2026`);let dt;try{dt=await yo(c,p,_.farm.farmId,{projectId:d,sealedBundle:_t})}catch(le){throw le instanceof N&&Z(le.status===409?`farm ${_.farm.name} is offline \u2014 start it and re-run.`:le.status===504?`farm ${_.farm.name} did not respond in time.`:`HUB \u2192 ${le.status} ${le.message}`),le}dt.ok||Z(`farm rejected provisioning: ${dt.error??"unknown error"}`),await ms(c,p,d,S,$e,b.repos,null,j),n.clear(),fs(`done. project ${d} is now hosted on farm ${_.farm.name} (daemon ${dt.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Ld(j),await _d(e,S.cloneUrl,S.branch),Od(e),a&&await Bb(e);{let _=Wt(e,We);ir(_);let de=Ve(T,E,x?.url,I||void 0,$),$e=Vr(_,de);$e.length>0&&C.success(`local project config \u2192 .codepipe/{${$e.join(", ")}}`),Bt(d,de,{info:Ze=>C.message(Ze),warn:Ze=>C.warn(Ze)})}await Nd(e,b.repos);let Qe={hubUrl:c,cliToken:p,projectId:d,...j,...W?{contextWrite:W}:{},...k?{claude:{oauthToken:k}}:{},...H?{youtrack:H}:{}};X(Qe),it({hubUrl:c,cliToken:p,projectId:d,accountEmail:f},d),C.success(`secrets \u2192 ${qe(d)}`),await ms(c,p,d,S,j.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,b.repos,e,j),n.clear();let pt=`${c}/?project=${encodeURIComponent(d)}`;Ad(pt),fs(`done. your project on the dashboard (sign in there to work with it):
|
|
684
|
+
${pt}
|
|
685
|
+
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:Fo}=await Promise.resolve().then(()=>(us(),vd));await Fo({profile:void 0})}async function ms(t,e,r,n,o,i=[],s=null,a={}){let c=await pd(n,o);if(!c){let f=!1;try{f=await md(i,{localRoot:s,tokens:a})}catch{f=!1}if(f){let u=ud(),m=await ze({message:u.message,options:u.options,initialValue:u.initialValue});if(!Do(m)&&m===u.proceedValue)try{let{jobId:d}=await pn(t,e,r,{reindex:!1,backfill:!0});C.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){C.warn(`could not start the retrospective analysis: ${d instanceof Error?d.message:String(d)}. Registration is not affected.`)}}}let l=ld(c),p=await ze({message:l.message,options:l.options,initialValue:l.initialValue});if(!(Do(p)||p!==l.proceedValue))try{let{jobId:f}=await pn(t,e,r,{reindex:l.reindex});C.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){C.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function Ob(t,e){let r;try{r=await Ql(t,e)}catch(c){throw c instanceof N&&Z(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&Z("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=ke(await ze({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=go(i.farmId,i.publicKey)}catch(c){Z(c instanceof Error?c.message:String(c))}return ke(await Er({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
682
686
|
${s}
|
|
683
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||
|
|
687
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||Z("farm fingerprint not confirmed \u2014 aborting."),mo(i.farmId,s),{farm:i,fingerprint:s}}async function Pd(t){Cd(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();jd(e,t.force===!0);let r=z(await re({message:"HUB URL",initialValue:M("HUB_URL")??Ge,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await jr(),{cliToken:o,accountEmail:i}=await Ar(r,n);C.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await V(r,o,t.projectId)}catch(u){throw u instanceof N&&Z(`HUB \u2192 ${u.status} ${u.message}`),u}s.contextRepo||Z(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Bd(),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 Uo(u,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}Ld(l),await _d(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Od(e);{let u=Wt(e,We);ir(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=Vr(u,d);h.length>0&&C.success(`local project config \u2192 .codepipe/{${h.join(", ")}} (defaults \u2014 review and adjust)`),Bt(t.projectId,d,{info:y=>C.message(y),warn:y=>C.warn(y)})}await Nd(e,s.repos);let f={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};X(f),it({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),C.success(`secrets \u2192 ${qe(t.projectId)}`),await ms(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),fs("done.")}function jd(t,e){if(!Cr(t)){Sd(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=_b(t).filter(o=>!r.has(o));n.length!==0&&(e||Z(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function ps(t){if(!Cr(Wt(t,".git")))return null;try{let r=(await Lo(t).remote(["get-url","origin"])||"").toString().trim(),n=r?_e(r):null;return n?{parsed:n,defaultBranch:await Db(t)}:null}catch{return null}}async function Db(t){let e=Lo(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 Ub(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Dt.test(e)?e:""}function Lb(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Bb(t){let e=Wt(t,".gitignore"),r=Cr(e)?Rd(e,"utf-8"):"";if(Lb(r))return;if(!ke(await Er({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){C.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
|
|
684
688
|
`)?"":`
|
|
685
|
-
`;
|
|
689
|
+
`;Td(e,r+o+`
|
|
686
690
|
# codepipe workspace (added by \`codepipe init\`)
|
|
687
691
|
.codepipe/
|
|
688
|
-
`),C.success(`.codepipe/ added to ${
|
|
692
|
+
`),C.success(`.codepipe/ added to ${Id(e)}`)}function Ad(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Ab(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function jr(){let t="";try{t=(await Lo().raw(["config","--global","user.email"])||"").trim()}catch{}return z(await re({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Ar(t,e){C.step(`connecting account ${e}`);let r;try{r=await nu(t,e)}catch(s){throw s instanceof un&&Z(`${e} is not authorized on this HUB yet.
|
|
689
693
|
Sign up at ${t} (registration form on the login screen),
|
|
690
694
|
wait for the operator to approve it by email, then re-run
|
|
691
|
-
\`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(
|
|
695
|
+
\`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Ad(r.authorizeUrl),C.message(`a browser tab was opened to confirm this CLI:
|
|
692
696
|
${r.authorizeUrl}
|
|
693
697
|
`+(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
|
|
694
|
-
otherwise use the emailed link the page offers.`))),r.approvalRequired&&C.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),C.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await
|
|
695
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
698
|
+
otherwise use the emailed link the page offers.`))),r.approvalRequired&&C.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),C.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await ou(t,r.requestId)}catch(a){C.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await ds(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&C.message(`connected as ${a} (the account confirmed in the browser).`),C.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&Z("the HUB rejected this account"),s.status==="expired"&&Z("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,C.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
699
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await ds(5e3);continue}await ds(2e3)}Z("bootstrap timed out")}async function _d(t,e,r){let n=Wt(t,We);if(Cr(Wt(n,".git"))){C.message(`${n} already cloned \u2014 skipping`);return}Cr(n)&&Z(`${n} exists but is not a git repo \u2014 remove it and re-run`),Sd(n,{recursive:!0}),C.step(`cloning Context Repo \u2192 ${n}`);try{await Lo().clone(e,n,["--branch",r]),C.success(`cloned ${e}`)}catch(o){Z(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function Nd(t,e){if(e.length===0)return;C.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await kn(t,r,{log:{info:o=>C.message(o),warn:o=>C.warn(o)}});for(let o of n)C.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Od(t){let e=Wt(t,We,".gitignore"),r="";if(Cr(e)&&(r=Rd(e,"utf-8")),xd.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
|
|
696
700
|
`)||r.length===0?"":`
|
|
697
|
-
`,i=
|
|
701
|
+
`,i=xd.join(`
|
|
698
702
|
`)+`
|
|
699
|
-
`;
|
|
700
|
-
`:"")+i),C.message(`appended runtime entries to ${
|
|
703
|
+
`;Td(e,r+o+(r?`
|
|
704
|
+
`:"")+i),C.message(`appended runtime entries to ${Id(e)}`)}async function Mb(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;C.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Uo(s.host,t,s.owner,e,s.repoName),i?.();let c=z(await re({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 re({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(;ke(await Er({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=z(await re({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||_e(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=_e(a);C.message(`${c.host}: ${c.owner}/${c.repoName}`),await Uo(c.host,t,c.owner,e,c.repoName),i?.();let l=z(await re({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 re({message:"default branch (optional)",placeholder:"main"})).trim(),f=z(await re({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 Dd(t,e,r,n){C.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=ke(await ze({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&C.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=z(await re({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:nt(t),validate:p=>{let f=(p??"").trim();if(!f)return"required";if(!_e(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=_e(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Fb(),l=z(await re({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),p=z(await re({message:"Context Repo name",placeholder:nt(t),initialValue:nt(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:p}}return{spec:a,mode:o}}function Ud(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??tr()}}async function Gb(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Uo(c.host,n,c.owner,o),i?.();let p=gs();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await Qp(c,Ud(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=ke(await ze({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"&&Z("aborted"),u==="create")return a={spec:c,mode:"create"},s(a),a;a=await Dd(e,r,n,o),s(a)}}async function Fb(){return ke(await ze({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function vn(t,e){let r=gs();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 Ld(t){nn(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),on(t.gitlab?.token??process.env.GITLAB_TOKEN),sn(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Uo(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await Hb(r);i?e.github=i:C.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await Kb(r,n,o);i?e.bitbucket=i:C.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await Wb();i?e.gitlab=i:C.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Hb(t){for(;;){let e=z(await Pr({message:`GitHub PAT \u2014 blank to skip
|
|
701
705
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
702
706
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
703
707
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
704
708
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
705
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await
|
|
709
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await vn("GitHub",()=>yt(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Kb(t,e,r){for(C.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
706
710
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
707
711
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
|
|
708
712
|
read:repository:bitbucket + write:repository:bitbucket +
|
|
709
713
|
read:pullrequest:bitbucket + write:pullrequest:bitbucket
|
|
710
714
|
\u2014 write scopes do NOT include read: pick BOTH scopes of each pair
|
|
711
715
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
712
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let n=
|
|
713
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
716
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let n=z(await re({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 Pr({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){C.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await vn("Bitbucket",async()=>{let i=await wt(n,o,t);if(t&&r){let s=await ro(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};C.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Wb(){for(;;){let t=z(await Pr({message:`GitLab PAT \u2014 blank to skip
|
|
717
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await vn("GitLab",()=>bt(t))){let e=await vc(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function qb(t){if(ke(await Er({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
714
718
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
715
719
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
716
720
|
your trusted network.`,initialValue:!1})))for(t.host==="github"?C.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
717
721
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
718
722
|
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):C.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
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=
|
|
720
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=
|
|
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
|
|
722
|
-
`),a=s.findIndex(
|
|
723
|
+
(${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 Pr({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await vn("contextWrite",()=>Yb(r,t)))return{token:r};C.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Yb(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 Vb(t){if(si()?.claude?.oauthToken&&!t)return C.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";C.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t?`
|
|
724
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=z(await Pr({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||C.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),r):(C.warn(t?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}async function Bd(){for(;;){let t=z(await re({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 Pr({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await vn("YouTrack",()=>xt({baseUrl:t,token:e}))){let r=await pl({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}var xd,$n=R(()=>{"use strict";Ce();F();je();ve();st();Gt();jo();Yi();Ao();kt();Ft();cd();fe();dd();gd();Mi();ao();te();No();ot();xd=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});F();Ce();ve();import{Command as o$}from"commander";Bn();import{homedir as Da}from"node:os";import{join as Ua}from"node:path";function La(){Lt(Ua(Da(),".devpipe"),Ua(Da(),".codepipe"))}ve();te();async function Xa(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=De(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(/\/$/,"");it({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...U(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};X(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Zt(e)}`)}ai();ve();import{homedir as Ji}from"node:os";import{join as fn}from"node:path";Ce();F();import{existsSync as ju,rmSync as iy}from"node:fs";import{join as dn}from"node:path";import{simpleGit as sy}from"simple-git";import"ws";Ce();te();import{createHash as dm}from"node:crypto";import{existsSync as fm,readFileSync as mm}from"node:fs";import{homedir as gm,hostname as ci}from"node:os";import{join as hm}from"node:path";function tc(t){return dm("sha256").update(t).digest("hex").slice(0,12)}function ym(){let t=M("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=hm(gm(),".claude","credentials.json");if(!fm(e))return;let r=JSON.parse(mm(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 rc(t){let e=ym(),r=M("ACCOUNT_ID")?.trim(),n=M("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=er(t);return o?{accountId:`acct-${tc(o)}`,label:n||ci(),...e?{email:e}:{}}:{accountId:`acct-${tc(`host:${ci()}`)}`,label:n||ci(),...e?{email:e}:{}}}import{existsSync as wm}from"node:fs";import{join as bm}from"node:path";import{simpleGit as km}from"simple-git";async function nc(t,e){if(!wm(bm(t,".git")))return{status:"skipped"};let r=km(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${$m(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 $m(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as ui,readFileSync as cc,readdirSync as Sm,watch as Rm}from"node:fs";import{join as Yr}from"node:path";F();import{existsSync as oc,readFileSync as ic,readdirSync as vm,statSync as xm}from"node:fs";import{join as li}from"node:path";import{parse as sc}from"yaml";function Vn(t){let e=li(t,"actions"),r=[],n=[];if(!oc(e))return{defs:r,errors:n};let o;try{o=vm(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=li(e,s);try{if(!xm(a).isFile())continue;let c=Qs(s,sc(ic(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 ac(t){let e={},r=li(t,"project.yaml");if(!oc(r))return e;let n;try{n=sc(ic(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))!Ie.test(i)||ft(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var Jn=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;watchers=[];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(){this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[]}installWatcher(){let e=()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()},r=[this.contextDir,Yr(this.contextDir,"prompts"),Yr(this.contextDir,"actions")];for(let n of r)if(ui(n))try{let o=Rm(n,e);o.on("error",i=>{this.log.warn(`[config] fs.watch failed on ${n} \u2014 falling back to periodic reporting: ${i instanceof Error?i.message:String(i)}`);try{o.close()}catch{}}),this.watchers.push(o)}catch{}}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=Vn(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=Yr(this.contextDir,e);if(!ui(r))return null;try{return cc(r,"utf-8")}catch{return null}}readPrompts(){let e=Yr(this.contextDir,"prompts"),r={};if(!ui(e))return r;let n;try{n=Sm(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=cc(Yr(e,o),"utf-8")}catch{}}return r}};ht();import{existsSync as wi,readFileSync as gc,readdirSync as Um}from"node:fs";import{join as hc}from"node:path";import{simpleGit as Lm}from"simple-git";var Bm=/^(\d{4})-(.+)\.md$/,Mm="0000-template.md";function Gm(t){let e=t.split(`
|
|
725
|
+
`),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 Fm(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
726
|
+
`),a=s.findIndex($=>$.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 $=m;$<s.length;$++){let w=(s[$]??"").trim();if(w===""){m=$+1;continue}let v=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!v)break;let x=(v[1]??"").trim().toLowerCase(),L=(v[2]??"").trim(),E=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(w);E&&(u=parseInt(E[1]??"",10)),x==="tasks"&&(f=L),l.has(x)||p.push(w),m=$+1}let d=f?f.includes(n)?f:`${f}, ${n}`:n,h=s.slice(m).join(`
|
|
723
727
|
`).replace(/^\n+/,""),y=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${d}`,...p,"",h].join(`
|
|
724
728
|
`);return{content:y.endsWith(`
|
|
725
729
|
`)?y:y+`
|
|
726
|
-
`,supersedes:u}}function
|
|
730
|
+
`,supersedes:u}}function Hm(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
|
|
727
731
|
|
|
728
|
-
- **Status:** superseded by ADR-${r}`):n}function
|
|
732
|
+
- **Status:** superseded by ADR-${r}`):n}function Km(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(`
|
|
729
733
|
`)+`
|
|
730
|
-
`}async function
|
|
731
|
-
`)}async function
|
|
732
|
-
${l.trim()}`)}}let i=
|
|
733
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function
|
|
734
|
-
${w.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),y=r.push!==!1;if(y){let
|
|
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
|
|
736
|
-
`,o.length>
|
|
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?
|
|
738
|
-
`)}function
|
|
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=
|
|
734
|
+
`}async function yc(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Lm(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 $=ae(t,i(y));if(!wi($)){a.push(y);continue}s.push({slug:y,content:gc($,"utf-8")})}let c=hc(t,"adr"),l=new Map;if(wi(c))for(let y of Um(c)){let $=Bm.exec(y);!$||y===Mm||l.set(y,{num:parseInt($[1]??"",10),slug:$[2]??"",content:gc(hc(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(([,E])=>E.slug===y.slug&&E.content.includes(e))){m.push(y.slug);continue}let w=p++,v=`${String(w).padStart(4,"0")}-${y.slug}.md`,{content:x,supersedes:L}=Fm(y.content,w,y.slug,e,n);if(f.set(v,x),l.set(v,{num:w,slug:y.slug,content:x}),u.push(`adr/${v}`),L!==null){let E=[...l.keys()].find(j=>j.startsWith(`${String(L).padStart(4,"0")}-`));if(E&&E!==v){let j=Hm(f.get(E)??l.get(E).content,w);f.set(E,j),l.set(E,{...l.get(E),content:j})}}}let d=[];if(o==="staging")for(let y of s)wi(ae(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(([$,w])=>({num:w.num,file:$,header:Gm(w.content)}));f.set("INDEX.md",Km(y))}for(let[y,$]of f.entries())d.push({path:`adr/${y}`,content:$});let h=u.length>0?`adr(${e}): promote ${s.map(y=>y.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await at(t,d,h),{promoted:u,skipped:m,missing:a}}ht();st();F();import{existsSync as wc,readFileSync as qm}from"node:fs";import{join as bc}from"node:path";function Ym(t){for(let e of[He,Fr]){let r=bc(t,e);if(wc(r))try{return Bs(qm(r,"utf-8"))}catch{return 0}}return 0}function Vm(t,e,r,n=3){let o=e<n,i=o?Ms(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function eo(t,e){return Vm(e,Ym(t),r=>wc(bc(t,r)))}F();kt();import{existsSync as Ac,mkdirSync as $g,mkdtempSync as vg,rmSync as _c,writeFileSync as Nc}from"node:fs";import{tmpdir as xg}from"node:os";import{dirname as Sg,join as oo}from"node:path";import{simpleGit as Ii}from"simple-git";Gt();function Rg(t){return`codepipe/context-migration-v${t}`}function Tg(t){let e=Gs(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 \`${Fr}\``,"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(`
|
|
735
|
+
`)}async function Oc(t,e,r,n){let o=Ii(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=eo(t,e);if(!i.outdated)return i;let s=Rg(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 Ig(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=Ue(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:Tg(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 Ig(t,e,r,n,o,i,s){let a=Ii(t),c=vg(oo(xg(),"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(ar(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 $=oo(c,h);Ac($)||($g(Sg($),{recursive:!0}),Nc($,y),u++)}Nc(oo(c,He),_n(n.currentVersion)),u++;let m=oo(c,Fr);Ac(m)&&(_c(m,{force:!0}),u++);let d=Ii(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(()=>{}),_c(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as Cg,readFileSync as Eg,writeFileSync as Pg}from"node:fs";import{homedir as jg}from"node:os";import{join as Dc}from"node:path";import{parseDocument as Ag}from"yaml";function _g(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 Ng(t,e){let r=Ag(t);return r.set("repos",e.map(_g)),r.toString()}function Og(t,e){let r=[Dc(jg(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Dc(e,"project.yaml")),r}function Qr(t,e,r){let n=[],o=[];for(let i of Og(t,r))if(Cg(i))try{let s=Eg(i,"utf-8"),a=Ng(s,e);a!==s&&(Pg(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 Dg}from"node:os";import{existsSync as Ug,mkdirSync as Lg}from"node:fs";import{join as Ci}from"node:path";import{simpleGit as Ei}from"simple-git";var Uc=t=>console.log(t);function Lc(t){Uc=t}function Zr(t,e="info"){Uc(t,e)}function xe(t,e,r){let n=r??Ci(Dg(),".codepipe","repos");return Ci(n,t,e)}async function cr(t,e,r={}){let n=xe(t,e.name,r.baseDir),o=r.cloneUrlOverride??tn(e);if(!Ug(Ci(n,".git"))){Lg(n,{recursive:!0});let a=Ei();Zr(`[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}
|
|
736
|
+
${l.trim()}`)}}let i=Ei(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
|
|
737
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function en(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var Bc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function io(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&&Zr(`[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 en(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await en(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([...Bc,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Mc(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await en(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await en(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 Gc(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 Mc(t,i,()=>io(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 en(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([...Bc,"cherry-pick",u])}catch($){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let w=$ instanceof Error?$.message:String($);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
738
|
+
${w.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),y=r.push!==!1;if(y){let $=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push($)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:h,pushed:y}}async function Fc(t,e,r){let n=r.force?["--force-with-lease","-u","origin",r.branchName]:["-u","origin",r.branchName];return await t.push(n),{pushed:!0}}async function Hc(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,p=await Mc(t,i,()=>io(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 Kc(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 tn(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 Wc(t){return(await Ei().listRemote(["--heads",t])).split(`
|
|
739
|
+
`).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 qc(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}je();te();function Kg(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 Xc(t,e,r,n){let o=Kg(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=Kn(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=ct(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}je();te();kt();Ft();te();kt();Ft();function Le(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Cl(t,e){let r=U(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 xt({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:Le(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Le(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 yt(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:Le(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Le(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 wt(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:Le(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Le(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await bt(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:Le(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Le(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 to(c,p.owner,p.repoName),n.push({name:`repo:${p.name}`,ok:!0})}catch(f){n.push({name:`repo:${p.name}`,ok:!1,detail:Le(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await to(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(p){n.push({name:"context-repo",ok:!1,detail:Le(p)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await to(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:Le(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=er(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 _i(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 _i(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)}}ao();function Al(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=so();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},X(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:we(e.sealKey.publicKey)}}async function _l(t,e,r,n){let o;try{o=JSON.parse(lr(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=U(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await yt(o.token);return i.github={token:o.token},ur(i,()=>{process.env.GH_TOKEN=o.token,El(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await bt(o.token);return i.gitlab={token:o.token},ur(i,()=>{process.env.GITLAB_TOKEN=o.token,Pl(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 wt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},ur(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,jl(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 xt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},ur(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 _i(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},ur(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},ur(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 ur(t,e){X(t),e()}F();F();import{spawn as ih}from"node:child_process";var sh=124,Nl=16*1024,Ol=4e3;function ah(t,e,r,n,o,i){let s={...t},a=(c,l)=>{ft(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 Dl(t){let{def:e,onEvent:r}=t,n=ah(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
740
|
+
`,o.length>Nl&&(o=o.slice(o.length-Nl))},s=(a,c)=>{let l=c.length>Ol?c.slice(0,Ol)+"\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 ch(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 ch(t,e,r,n,o){return new Promise(i=>{let s=ih("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Xs)*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(`
|
|
741
|
+
`))!==-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?sh:m??(d?1:0))})})}ht();import{existsSync as lh,readFileSync as uh,statSync as Ul}from"node:fs";var Ll=2*1024*1024;function ph(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Bl(t,e){let r=ae(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!lh(r)||!Ul(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Ul(r);if(n>Ll)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Ll})`);let o=uh(r);return ph(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}te();F();import{existsSync as dh,readFileSync as fh,writeFileSync as mh}from"node:fs";import{join as gh}from"node:path";import{parseDocument as hh}from"yaml";async function Ml(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=oa(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=gh(t,o);if(!dh(s))throw new Error(`${o} not found in context repo (${t})`);let a=hh(fh(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);mh(s,a.toString()),n.push(o)}return{files:n}}F();import{existsSync as yh,readFileSync as wh,writeFileSync as bh}from"node:fs";import{join as kh}from"node:path";import{isMap as Gl,parseDocument as $h}from"yaml";async function Fl(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||!ua(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=kh(t,"project.yaml");if(!yh(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=$h(wh(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Gl(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Gl(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),bh(o,i.toString()),{repoName:r,defaultBranch:n}}import{existsSync as Oi,readFileSync as Di,writeFileSync as vh}from"node:fs";import{join as co}from"node:path";import{parseDocument as Ui}from"yaml";async function Hl(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=co(t,"project.yaml");if(!Oi(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Ui(Di(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=co(t,"regimen.yaml");if(!Oi(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Ui(Di(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)vh(co(t,i.path),i.content);return{files:r.map(i=>i.path)}}function lo(t){if(!t)return"Stage";try{let e=co(t,"project.yaml");if(!Oi(e))return"Stage";let n=Ui(Di(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}kt();Ft();import{existsSync as ql,readFileSync as Yl}from"node:fs";import{join as Vl}from"node:path";import{parseDocument as Jl}from"yaml";Ft();var an=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return vl(this.cfg,e)}getIssue(e,r){return xl(this.cfg,e,r??lo(this.contextDir))}listComments(e,r){return Sl(this.cfg,e,r)}downloadAttachment(e){return $l(this.cfg,e)}updateStatus(e,r){return dl(this.cfg,e,r,lo(this.contextDir))}addComment(e,r,n){return fl(this.cfg,e,r)}createIssue(e){return hl(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,lo(this.contextDir))}editIssue(e,r){return ml(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return yl(this.cfg,e,r,n)}fetchStateFields(e){return Tl(this.cfg,e)}};F();ht();import{existsSync as Eh,readFileSync as Ph}from"node:fs";import{randomBytes as jh}from"node:crypto";import{existsSync as Kl,readFileSync as xh,readdirSync as Sh}from"node:fs";F();ht();function uo(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Ch(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Rh(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Ih(Th(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 po(t,e,r){if(r.length===0)return;let n=uo(t,e,r),o=r.map(i=>i.issue.key);await at(t,n,`sync(${o.join(", ")}): task data`)}function Rh(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(`
|
|
742
|
+
`)}function Th(t,e,r){let n=new Map,o=ae(t,`tasks/${e}/comments.jsonl`);if(Kl(o))for(let i of xh(o,"utf-8").split(`
|
|
743
|
+
`)){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=zt(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Ih(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
740
744
|
`)+(t.length>0?`
|
|
741
|
-
`:"")}function
|
|
745
|
+
`:"")}function Ch(t,e,r){let n=[],o=ae(t,`tasks/${e}/attachments`);if(Kl(o))for(let i of Sh(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}no();var cn=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Jr(this.contextDir);let r=e.columns??[];return Ec(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Xr(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=zr(this.contextDir,e);return r?Xr(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Wl(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 Jr(this.contextDir),!zr(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${jh(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=zt(r);s&&(i.parsedCommand=s);let c=[...Wl(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
|
|
742
746
|
`)+`
|
|
743
|
-
`;return await
|
|
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}ro();function Di(t){if(!t)return"youtrack";try{let e=Wl(t,"project.yaml");return Hl(e)&&ql(Kl(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Je(t){let e=Di(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=Sc(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Ch(n);return i?{ok:!0,kind:e,provider:new sn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=al();return r?{ok:!0,kind:e,provider:new on(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Ch(t){try{let e=Wl(t,"project.yaml");if(!Hl(e))return null;let r=ql(Kl(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var po=new Map;async function an(t,e){let n=(po.get(t)??Promise.resolve()).catch(()=>{}).then(e);po.set(t,n);try{return await n}finally{po.get(t)===n&&po.delete(t)}}async function Yl(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;Xr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return an(`${i}/${r.name}`,async()=>{let s=await sr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{commit:c,pushed:l}=await Lc(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,push:e.push});return te({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return an(`${i}/${r.name}`,async()=>{let s=await sr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir);return await Bc(s,a,{branchName:e.branchName,force:e.force}),te({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return an(`${i}/${r.name}`,async()=>{let s=await sr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{commit:c,pushed:l}=await Mc(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return te({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return K("no repo spec");let i=De(r),s=await i.createPullRequest(r,e);return te({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return K("no repo spec");let i=De(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return te({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return K("no repo spec");let i=De(r);return await i.closePR(r,e.prNumber,e.comment),te({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return an(`${i}/${r.name}`,async()=>{let s=await sr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{mergedSha:c}=await Gc(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return te({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return K("no repo spec");let i=t.cloneUrlOverride??Zr(r),a=(await Fc(i)).filter(p=>Hc(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 te({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return K("no repo spec");let i=De(r);return await i.addPRComment(r,e.prNumber,e.body),te({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),te({issueId:t.trackerIssueId,newStatus:e.newStatus})):K("no tracker_issue_id provided"):K(i.error)}case"tracker_comment":{let i=Je({contextDir:t.contextDir});if(!i.ok)return K(i.error);if(!t.trackerIssueId)return K("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return te({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Je({contextDir:t.contextDir});if(!i.ok)return K(i.error);if(!e.projectKey)return K("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 te({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Je({contextDir:t.contextDir});if(!i.ok)return K(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 K(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return te({applied:s})}case"set_project_setting":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await Ul(t.contextDir,e.edits);return te({files:i.files})}case"tracker_edit":{let i=Je({contextDir:t.contextDir});if(!i.ok)return K(i.error);if(!t.contextDir)return K("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 uo(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),te({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await Ml(t.contextDir,e);return te({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await Bl(t.contextDir,e);return te({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),te({reported:!0})):K("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return K("no context repo clone on this CLI");let i=await t.refreshContextStatus();return te({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return K("no project workspace on this CLI");if(!r)return K("no repo spec");if(!t.onRunActivity)return K("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Yn(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(d=>d.file===`actions/${e.actionId}.yml`);return K(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=zs(c,e.input);if(!l.ok)return K(l.error);let p=oc(t.contextDir),f=B(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),an(`${e.projectId}/${r.name}`,async()=>{await sr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=$e(e.projectId,r.name,t.baseDir),d=await _l({cwd:m,def:c,input:l.values,variables:p,secrets:f?.secrets??{},credEnv:u,onEvent:h=>i(e.runId,h)});return te({runId:e.runId,status:d.status,exitCode:d.exitCode,...d.failedStep?{failedStep:d.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=Dl(t.contextDir,e.path);return te({path:e.path,...i})}default:return K(`unsupported action type: ${e.type}`)}}catch(i){return K(i instanceof Error?i.message:String(i))}}function te(t){return{status:"done",result:t}}function K(t){return{status:"failed",error:t}}Pe();Li();fe();re();import{existsSync as uu,readFileSync as pu}from"node:fs";import{join as du}from"node:path";async function fu(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)");mo(e.farmId,e.farmPublicKey);let s=B(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await J(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=du(r,"project.yaml"),m=du(r,"regimen.yaml");uu(u)&&uu(m)?c={projectYaml:pu(u,"utf-8"),regimenYaml:pu(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=st(e.farmPublicKey,JSON.stringify(l));fo(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await ho(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))}}Pe();Te();Pe();import{homedir as Mh}from"node:os";import{existsSync as Gh,mkdirSync as Fh,readFileSync as Hh,writeFileSync as Kh}from"node:fs";import{dirname as Wh,join as qh}from"node:path";function Gi(){return F("RUNNER_PINS")??qh(Mh(),".codepipe","runner-pins.json")}function mu(){let t=Gi();if(!Gh(t))return{};try{return JSON.parse(Hh(t,"utf-8"))}catch{return{}}}function Yh(t){let e=Gi();Fh(Wh(e),{recursive:!0}),Kh(e,JSON.stringify(t,null,2)+`
|
|
745
|
-
`,{mode:384})}function Vh(t){return mu()[t]}function Fi(t,e){let r=mu();r[t]=e,Yh(r)}function gu(t,e){let r=ye(e),n=Vh(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 ${Gi()}.`);return r}fe();re();var yu=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function hu(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:yu(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 Jh={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:yu(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)=>hu(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>hu(t,e,r,"remove-token")},wu={api:Jh,fetchProject:J,provisionOnRunner:zl,teardownOnRunner:Xl};async function bu(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)");gu(e.runnerId,e.runnerPublicKey);let i=B(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 ku(t,e,r,n=wu){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 bu(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=st(e.runnerPublicKey,JSON.stringify(l));Fi(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 $u(t,e,r,n=wu){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 bu(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=st(e.runnerPublicKey,JSON.stringify(c));Fi(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();Pe();re();var vu=16*1024;function zh(t){return Re.test(t)?pt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Re}`}function xu(t,e,r,n){let o=zh(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(ar(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>vu)return{ok:!1,detail:`secret value too large (max ${vu} chars)`};try{return Ha(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Su(t,e){try{return Ka(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 wo=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 Lt){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=Xh(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function Xh(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 bo=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}:{},R=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},P=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(P){let j=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[G,de]=await Promise.all([j.length>0?r.listIssues({projectKey:e.projectKey,columns:j,...k,...R}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...k})]),A=new Map;for(let g of[...G,...de])A.set(g.id,g);o=[...A.values()]}else{let j=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:j,...k,...R})}}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 R=await Tu(r,k.id,e.sinceMs,this.log);R&&i.set(k.id,R)}let c=[];for(let k of e.offBoardIssueIds){if(s.has(k))continue;let R=await Tu(r,k,e.sinceMs,this.log);if(R&&R.length>0&&i.set(k,R),e.requireAssignee||R&&R.length>0){let M=await ey(r,k,e.stageField,this.log);if(M)c.push(M);else if(R&&R.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 uo(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let k of f)this.shippedAttachments.add(k)}catch(k){let R=k instanceof Error?k.message:String(k);this.abandonTick(`context task sync failed: ${R}`);return}let m=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[k,R]of i){let M=R.filter(j=>!m(j.id));if(M.length===0)continue;d.push({issueId:k,comments:M.map(Qh)});let P=M.flatMap(j=>{let G=Vt(j.body);return G?[{commentId:j.id,author:j.author,name:G.name,args:G.args,createdAt:j.createdAt}]:[]});P.length>0&&h.push({issueId:k,commands:P})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Ru),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Ru)}:{},observedAtMs:n};this.send(y);let b=d.reduce((k,R)=>k+R.comments.length,0),w=h.reduce((k,R)=>k+R.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=Zh(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 Ru(t){let{description:e,...r}=t;return r}function Qh(t){let{body:e,...r}=t;return r}function Zh(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 ey(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 Tu(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 Hi="npm i -g @code-partner/codepipe@latest";function ko(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${Se} (protocol ${Fe})`);let n=d=>e.onEvent?.(d),o=e.workspace;o?.contextDir&&ac(o.contextDir,r);let i=Iu("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Iu("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=go(t.hubUrl,t.cliToken),h=null,y=new wo(i,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r),b=new bo(s,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r,{contextDir:o?.contextDir??null,isSelfComment:S=>f.has(S)}),w=null,k=async()=>{try{let S={trackerProvider:Di(o?.contextDir??null)};try{let E=await J(t.hubUrl,t.cliToken,t.projectId);S={...S,repos:E.repos,contextRepo:E.contextRepo}}catch(E){r.warn(`[readiness] could not fetch project summary for push checks: ${E instanceof Error?E.message:String(E)}`)}let x=await Rl(t.projectId,S);if(d.readyState!==d.OPEN)return;let v={type:"cli_readiness",projectId:t.projectId,ready:x.ready,checks:x.checks,creds:x.creds,secretNames:Wa(t.projectId),checkedAt:x.checkedAt};if(d.send(JSON.stringify(v)),x.ready)r.info("[readiness] ready");else{let E=x.checks.filter(_=>!_.ok).map(_=>`${_.name}(${_.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${E.join(", ")}`)}}catch(S){r.warn(`[readiness] check failed: ${S instanceof Error?S.message:String(S)}`)}},R=()=>{k(),w=setInterval(()=>void k(),a),typeof w.unref=="function"&&w.unref()},M=()=>{w&&(clearInterval(w),w=null)},P=150,j=new Map,G=S=>{let x=j.get(S);if(!x||(x.timer&&clearTimeout(x.timer),j.delete(S),x.events.length===0||d.readyState!==d.OPEN))return;let v={type:"run_activity",projectId:t.projectId,runId:S,events:x.events};d.send(JSON.stringify(v))},de=(S,x)=>{let v=j.get(S);if(v||(v={events:[],timer:null},j.set(S,v)),v.events.push(x),x.kind==="result"){G(S);return}v.timer||(v.timer=setTimeout(()=>G(S),P),v.timer.unref?.())},A=o?.contextDir?new Vn(o.contextDir,t.projectId,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r):null,g=async()=>{let S=o?.contextDir;if(!S)throw new Error("no context repo clone on this CLI");let x;try{x=(await J(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let v=await Ac(S,t.projectId,x,r);return d.readyState===d.OPEN&&d.send(JSON.stringify(v)),v};return d.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let S=Za(t.projectId),x=F("ORIGIN")==="farm"?"farm":"local",v=F("FARM_ID"),E=t.accountEmail??S.email,_;try{let T=Pl(t.projectId);T&&(_=T.publicKey,r.info(`[cred-channel] key fingerprint: ${T.fingerprint}`))}catch(T){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${T instanceof Error?T.message:String(T)}`)}let $={type:"register",projectId:t.projectId,platformVersion:Se,protocolVersion:Fe,accountId:S.accountId,accountLabel:S.label,origin:x,inFlightActionIds:[...p],...E?{accountEmail:E}:{},...x==="farm"&&v?{farmId:v}:{},..._?{sealPublicKey:_}:{}};d.send(JSON.stringify($))}),d.on("message",async S=>{let x=S.toString("utf-8");if(x==="pong"||x==="ping")return;let v;try{v=JSON.parse(x)}catch{return}if(!v||typeof v!="object")return;let E=v.type;if(E==="registered"){let $=v;if($.ok){if(r.info(`[ws] registered for project ${$.projectId}`),n({kind:"registered",projectId:$.projectId??t.projectId}),y.start(),A?.start(),R(),Ki(t,o,r),o?.contextDir)try{let T=Zn(o.contextDir,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(T)),T.outdated&&(r.warn(`[ctx] context format outdated: v${T.templateVersion} \u2192 v${T.currentVersion}`+(T.missingPaths.length>0?` (missing: ${T.missingPaths.join(", ")})`:"")),l||(l=!0,g().catch(()=>{})))}catch(T){r.warn(`[ctx] context-format detect failed (non-fatal): ${T instanceof Error?T.message:String(T)}`)}}else r.warn(`[ws] register rejected: ${$.reason??"unknown"}`),n({kind:"register_rejected",reason:$.reason??"unknown"}),c=!0,d.close();return}if(E==="hello"){let $=v;h=jn($.protocolVersion);let T=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${T}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Se}, protocol ${Fe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Hi}`),n({kind:"incompatible",hubVersion:typeof $.platformVersion=="string"?$.platformVersion:null,hubProtocol:typeof $.protocolVersion=="number"?$.protocolVersion:null,updateCommand:Hi}));return}if(E==="tracking_targets"){y.setTargets(v.targets);return}if(E==="youtrack_sync_request"){b.setRequest(v);return}if(E==="youtrack_force_sync"){b.forceSync();return}if(E==="sync_local"){await iy(v,o,d,r);return}if(E==="provision_repo"){let $=v;r.info(`[repo] provision_repo: ${$.repo.name} (${$.repo.host}:${$.repo.owner}/${$.repo.repoName})`),await ny(t,o,$.repo,r),await Ki(t,o,r);return}if(E==="remove_repo"){let $=v;r.info(`[repo] remove_repo: ${$.repoName}${$.purge?" (purge)":""}`),await Ki(t,o,r),$.purge&&oy(t,o,$.repoName,r);return}if(E==="context_write"){await sy(v,o,d,r);return}if(E==="adr_promote"){await ay(v,o,d,r);return}if(E==="cred_update"){let $=v,T=B(t.projectId),H=T?.sealKey?await El(t.projectId,$.kind,$.sealed,T.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},Y={type:"cred_update_result",updateId:$.updateId,projectId:t.projectId,ok:H.ok,...H.detail?{detail:H.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(Y)),H.ok?(r.info(`[cred] ${$.kind} replaced${H.detail?` \u2014 ${H.detail}`:""}`),k()):r.warn(`[cred] ${$.kind} replacement rejected: ${H.detail??"unknown"}`);return}if(E==="move_to_farm"){let $=v;r.info(`[farm-move] request to move ${t.projectId} onto farm ${$.farmName} (${$.farmId})`);let T=await fu(t,$,o?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(T)),T.ok?r.info(`[farm-move] done \u2014 farm daemon ${T.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${T.error??"unknown error"}`);return}if(E==="gh_runner_setup"){let $=v;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${$.runnerName} (${$.runnerId})`);let T=await ku(t,$,r);d.readyState===d.OPEN&&d.send(JSON.stringify(T)),T.ok?r.info(`[ghr] runners connected on ${$.runnerName}`):r.warn(`[ghr] setup failed: ${T.error??"see per-repo statuses"}`);return}if(E==="gh_runner_teardown"){let $=v;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${$.runnerName} (${$.runnerId})`);let T=await $u(t,$,r);d.readyState===d.OPEN&&d.send(JSON.stringify(T)),T.ok?r.info(`[ghr] runners disconnected from ${$.runnerName}`):r.warn(`[ghr] teardown failed: ${T.error??"unknown error"}`);return}if(E==="tracker_fields_request"){let $=v,T={type:"tracker_fields_result",requestId:$.requestId,projectId:t.projectId,ok:!1},H=Je({contextDir:o?.contextDir??null});if(!H.ok)T.error=H.error;else try{T.fields=await H.provider.fetchStateFields($.projectKey),T.ok=!0}catch(Y){T.error=Y instanceof Error?Y.message:String(Y)}d.readyState===d.OPEN&&d.send(JSON.stringify(T)),T.ok||r.warn(`[yt-fields] listing failed: ${T.error??"unknown"}`);return}if(E==="project_secret_update"||E==="project_secret_delete"){let $=v,T;if($.type==="project_secret_update"){let Y=B(t.projectId);T=Y?.sealKey?xu(t.projectId,$.name,$.sealed,Y.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else T=Su(t.projectId,$.name);let H={type:"project_secret_update_result",updateId:$.updateId,projectId:t.projectId,ok:T.ok,...T.detail?{detail:T.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(H)),T.ok?(r.info(`[secret] ${$.name} ${$.type==="project_secret_update"?"saved":"deleted"}`+(T.detail?` \u2014 ${T.detail}`:"")),k()):r.warn(`[secret] ${$.name} rejected: ${T.detail??"unknown"}`);return}if(E==="sandbox_keys"){let $=B(t.projectId);if(!$){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let T=Qt(t.projectId),H=Vc(v,$,T,r);for(let Y of H)d.readyState===d.OPEN&&d.send(JSON.stringify(Y));return}if(E!=="dispatch_action")return;let _=v;if(h===!1){let $=`refused: HUB protocol incompatible with CLI v${Se} (protocol ${Fe})`;d.send(JSON.stringify({type:"action_result",actionId:_.actionId,status:"failed",error:$})),r.warn(`[exec] ${_.actionId} (${_.action.type}) \u2192 REFUSED: ${$}`),r.warn(`[exec] update the CLI to clear this: ${Hi}`),n({kind:"action",actionId:_.actionId,actionType:_.action.type,ok:!1,error:$});return}p.add(_.actionId);try{let $=await Yl({action:_.action,repo:_.repo,trackerIssueId:_.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:A?()=>A.reportNow():void 0,refreshContextStatus:o?.contextDir?g:void 0,onRunActivity:de}).catch(Y=>({status:"failed",error:Y instanceof Error?Y.message:String(Y)}));_.action.type==="tracker_comment"&&$.status==="done"&&"result"in $&&typeof $.result?.commentId=="string"&&f.add($.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:_.actionId,...$}));let T=$.status!=="failed",H=!T&&"error"in $?$.error:void 0;T?r.info(`[exec] ${_.actionId} (${_.action.type}) \u2192 done`):r.warn(`[exec] ${_.actionId} (${_.action.type}) \u2192 FAILED: ${H??"?"}`),n({kind:"action",actionId:_.actionId,actionType:_.action.type,ok:T,...H?{error:H}:{}})}finally{p.delete(_.actionId)}}),d.on("close",(S,x)=>{let v=x?.toString("utf-8")??"";if(r.info(`[ws] closed code=${S}${v?` reason=${v}`:""}`),y.stop(),b.stop(),A?.stop(),M(),v==="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:S}),!c&&setTimeout(()=>{u=m()},2e3)}),d.on("error",S=>r.warn(`[ws] error: ${S.message}`)),d}return{stop(){c=!0,u.close()}}}async function Ki(t,e,r){try{let n=await J(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=zr(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 ny(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?un(e.root,o):$e(t.projectId,r.name);if(Cu(un(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await ry().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 oy(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?un(e.root,o):$e(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Cu(un(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{ty(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 iy(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=un(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await ec(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 sy(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 it(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 ay(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 mc(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 Iu(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}fe();re();ot();qi();rt();so();async function Mu(t={profile:void 0}){let{cfg:e,profile:r}=Fn(t.profile),n=B(e.projectId);n&&Kr(n),tn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),rn(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),nn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=pn(Yi(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Wn("CLI_LOG",i,o);if(s.enabled){let u=new er(s);qn(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=Mn(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=pn(Yi(),".codepipe",r?pn("profiles",r,"context"):"context");if(await Mi(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Lu(()=>vo({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 Mi(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=pn(Yi(),".codepipe",r?pn("profiles",r,"context-config"):"context-config");Jn(a.contextDir,m,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=ko(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(()=>{})}vr();ke();fe();async function Yp(t={profile:void 0}){let e=Ce(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=go(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`)")}bn();import{readFileSync as Wb}from"node:fs";q();ke();ot();Eo();Bt();wt();Mt();fe();re();function ue(t){throw new Error(t)}function pe(t,e){return(typeof t!="string"||t.trim().length===0)&&ue(`config: '${e}' must be a non-empty string`),t.trim()}function $n(t,e){if(t==null)return;typeof t!="string"&&ue(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function qb(t){(!t||typeof t!="object")&&ue("config: expected a JSON object");let e=t,r=pe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ue("config: 'hubUrl' must start with http(s)://");let n=pe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ue("config: 'project' is required");let i=o,s=pe(i.id,"project.id");Nt.test(s)||ue("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=pe(i.name,"project.name"),c=pe(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ue("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ue("config: 'project.repos' must be an array");let p=l.map((w,k)=>{(!w||typeof w!="object")&&ue(`config: project.repos[${k}] must be an object`);let R=w,M=pe(R.host,`project.repos[${k}].host`);M!=="github"&&M!=="bitbucket"&&M!=="gitlab"&&ue(`config: project.repos[${k}].host must be 'github', 'bitbucket' or 'gitlab'`);let P={name:pe(R.name,`project.repos[${k}].name`),host:M,owner:pe(R.owner,`project.repos[${k}].owner`),repoName:pe(R.repoName,`project.repos[${k}].repoName`)},j=$n(R.defaultBranch,`project.repos[${k}].defaultBranch`);j&&(P.defaultBranch=j);let G=$n(R.mountAs,`project.repos[${k}].mountAs`);return G&&(P.mountAs=G),P}),f=i.contextRepo;(!f||typeof f!="object")&&ue("config: 'project.contextRepo' is required");let u=f,m=$n(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&ue("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:m,owner:pe(u.owner,"project.contextRepo.owner"),name:$n(u.name,"project.contextRepo.name")??tt(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:d}},y=$n(i.youtrackProjectKey,"project.youtrackProjectKey");y&&(h.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&ue("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ue("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)&&ue("config: 'secrets' must be an object");let w=b,k={};if(w.github){let R=w.github;k.github={token:pe(R.token,"secrets.github.token")}}if(w.bitbucket){let R=w.bitbucket;k.bitbucket={email:pe(R.email,"secrets.bitbucket.email"),apiToken:pe(R.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let R=w.gitlab;k.gitlab={token:pe(R.token,"secrets.gitlab.token")}}if(w.youtrack){let R=w.youtrack;k.youtrack={url:pe(R.url,"secrets.youtrack.url").replace(/\/$/,""),token:pe(R.token,"secrets.youtrack.token")}}if(w.contextWrite){let R=w.contextWrite;k.contextWrite={token:pe(R.token,"secrets.contextWrite.token")}}h.secrets=k}return h}async function Yb(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Vb(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 to(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 Dd(t){let e=!t.configPath||t.configPath==="-"?await Yb():Wb(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){ue(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=qb(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 Vb(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 Sr(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Zt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){ue(`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)ue(`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(Q(f),nt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${qe(s.id)}`),Ut(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 ln(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 Ud,intro as Ld,isCancel as Bd,log as ms,outro as Jb,password as Md}from"@clack/prompts";async function zb(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Gd(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await zb(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Ld("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),ms.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Md({message:"Claude OAuth token"});Bd(i)&&(Ud("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Ya({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Kn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ce(t.profile);if(!e){Ld(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),ms.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Md({message:"Claude OAuth token"});Bd(i)&&(Ud("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=B(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},Q(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(ms.success("Claude OAuth token saved."),Jb("It will be sealed into job bundles when a SANDBOX (re)connects."))}q();ke();ot();Eo();Bt();jo();fe();re();import{cancel as Xb,confirm as Qb,intro as Zb,isCancel as Fd,log as he,outro as ek,select as Hd,text as Pt}from"@clack/prompts";function Kd(t){Xb(t),process.exit(1)}function jr(t){return Fd(t)&&Kd("aborted"),t}function vn(t){return Fd(t)&&Kd("aborted"),typeof t=="string"?t:""}async function tk(t,e){let r=jr(await Hd({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=vn(await Pt({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=vn(await Pt({message:"Context Repo name",placeholder:tt(t),initialValue:tt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Wd(t={profile:void 0}){let e=Ce(t.profile);Zb(`codepipe project add \u2192 ${e.hubUrl}`);let r=jr(await Pt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>Nt.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=jr(await Pt({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=jr(await Hd({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=jr(await Pt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=jr(await Qb({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=vn(await Pt({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()||je(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=je(u);he.message(`${m.host}: ${m.owner}/${m.repoName}`);let d=vn(await Pt({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=vn(await Pt({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 tk(r,a),p=B(e.projectId);he.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Sr(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??Zt(),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}`),Ut(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}`),ek("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)}}vr();ke();fe();re();rt();bn();import{existsSync as rk,rmSync as nk}from"node:fs";import{confirm as ok,intro as ik,isCancel as sk,log as Et,outro as ak,spinner as ck}from"@clack/prompts";function Xe(t){Et.error(t),process.exit(1)}var qd=t=>t.trim().replace(/\/+$/,"");async function Yd(t){ik("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Ie()?.spec.projectId??void 0;e||Xe("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Oe(e);r||Xe(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=qd(r.hubUrl),o=r.projectId,i=qd(t.hub);i.startsWith("http")||Xe("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Xe(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let b=ck();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&&Xe(`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||Xe(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let p=B(o),f=(t.account??r.accountEmail??await Pr()).trim().toLowerCase();if(Et.message(`move project '${o}'
|
|
747
|
+
`;return await at(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 Pc(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:ni.statusColumns}]}async mutateRecord(e,r,n){let o=zr(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Xr(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Kr(e),content:Ti(i)},...uo(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await at(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Dn,status:r.targetStatus,links:[],created:n,updated:n},i=Xr(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Kr(e),content:Ti(o)},...uo(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function Wl(t,e){let r=ae(t,`tasks/${e}/comments.jsonl`);if(!Eh(r))return[];let n=[];for(let o of Ph(r,"utf-8").split(`
|
|
748
|
+
`)){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}no();function Li(t){if(!t)return"youtrack";try{let e=Vl(t,"project.yaml");return ql(e)&&Jl(Yl(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Je(t){let e=Li(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=Ic(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Ah(n);return i?{ok:!0,kind:e,provider:new cn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=ul();return r?{ok:!0,kind:e,provider:new an(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Ah(t){try{let e=Vl(t,"project.yaml");if(!ql(e))return null;let r=Jl(Yl(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var fo=new Map;async function ln(t,e){let n=(fo.get(t)??Promise.resolve()).catch(()=>{}).then(e);fo.set(t,n);try{return await n}finally{fo.get(t)===n&&fo.delete(t)}}async function zl(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;Zr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return G("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{commit:c,pushed:l}=await Gc(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,push:e.push});return ee({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return G("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir);return await Fc(s,a,{branchName:e.branchName,force:e.force}),ee({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return G("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{commit:c,pushed:l}=await Hc(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ee({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return G("no repo spec");let i=Ue(r),s=await i.createPullRequest(r,e);return ee({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return G("no repo spec");let i=Ue(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ee({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return G("no repo spec");let i=Ue(r);return await i.closePR(r,e.prNumber,e.comment),ee({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return G("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{mergedSha:c}=await Kc(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ee({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return G("no repo spec");let i=t.cloneUrlOverride??tn(r),a=(await Wc(i)).filter(p=>qc(p,e.issueKey)),c=Ue(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 ee({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return G("no repo spec");let i=Ue(r);return await i.addPRComment(r,e.prNumber,e.body),ee({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),ee({issueId:t.trackerIssueId,newStatus:e.newStatus})):G("no tracker_issue_id provided"):G(i.error)}case"tracker_comment":{let i=Je({contextDir:t.contextDir});if(!i.ok)return G(i.error);if(!t.trackerIssueId)return G("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ee({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Je({contextDir:t.contextDir});if(!i.ok)return G(i.error);if(!e.projectKey)return G("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 ee({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Je({contextDir:t.contextDir});if(!i.ok)return G(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 G(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ee({applied:s})}case"set_project_setting":{if(!t.contextDir)return G("no context repo clone on this CLI");let i=await Ml(t.contextDir,e.edits);return ee({files:i.files})}case"tracker_edit":{let i=Je({contextDir:t.contextDir});if(!i.ok)return G(i.error);if(!t.contextDir)return G("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 po(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ee({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return G("no context repo clone on this CLI");let i=await Hl(t.contextDir,e);return ee({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return G("no context repo clone on this CLI");let i=await Fl(t.contextDir,e);return ee({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ee({reported:!0})):G("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return G("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ee({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return G("no project workspace on this CLI");if(!r)return G("no repo spec");if(!t.onRunActivity)return G("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Vn(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(d=>d.file===`actions/${e.actionId}.yml`);return G(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Zs(c,e.input);if(!l.ok)return G(l.error);let p=ac(t.contextDir),f=U(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),ln(`${e.projectId}/${r.name}`,async()=>{await cr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=xe(e.projectId,r.name,t.baseDir),d=await Dl({cwd:m,def:c,input:l.values,variables:p,secrets:f?.secrets??{},credEnv:u,onEvent:h=>i(e.runId,h)});return ee({runId:e.runId,status:d.status,exitCode:d.exitCode,...d.failedStep?{failedStep:d.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return G("no context repo clone on this CLI");let i=Bl(t.contextDir,e.path);return ee({path:e.path,...i})}default:return G(`unsupported action type: ${e.type}`)}}catch(i){return G(i instanceof Error?i.message:String(i))}}function ee(t){return{status:"done",result:t}}function G(t){return{status:"failed",error:t}}je();Mi();fe();te();import{existsSync as fu,readFileSync as mu}from"node:fs";import{join as gu}from"node:path";async function hu(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=we(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");go(e.farmId,e.farmPublicKey);let s=U(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await V(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=gu(r,"project.yaml"),m=gu(r,"regimen.yaml");fu(u)&&fu(m)?c={projectYaml:mu(u,"utf-8"),regimenYaml:mu(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=ct(e.farmPublicKey,JSON.stringify(l));mo(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await yo(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))}}je();Ce();je();import{homedir as Kh}from"node:os";import{existsSync as Wh,mkdirSync as qh,readFileSync as Yh,writeFileSync as Vh}from"node:fs";import{dirname as Jh,join as zh}from"node:path";function Hi(){return M("RUNNER_PINS")??zh(Kh(),".codepipe","runner-pins.json")}function yu(){let t=Hi();if(!Wh(t))return{};try{return JSON.parse(Yh(t,"utf-8"))}catch{return{}}}function Xh(t){let e=Hi();qh(Jh(e),{recursive:!0}),Vh(e,JSON.stringify(t,null,2)+`
|
|
749
|
+
`,{mode:384})}function Qh(t){return yu()[t]}function Ki(t,e){let r=yu();r[t]=e,Xh(r)}function wu(t,e){let r=we(e),n=Qh(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 ${Hi()}.`);return r}fe();te();var ku=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function bu(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:ku(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 Zh={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:ku(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)=>bu(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>bu(t,e,r,"remove-token")},$u={api:Zh,fetchProject:V,provisionOnRunner:Zl,teardownOnRunner:eu};async function vu(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(we(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");wu(e.runnerId,e.runnerPublicKey);let i=U(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).filter(c=>c.host==="github");if(a.length===0)throw new Error("the project has no GitHub repositories \u2014 nothing to connect a runner to");return{githubToken:i,repos:a}}async function xu(t,e,r,n=$u){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 vu(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=ct(e.runnerPublicKey,JSON.stringify(l));Ki(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 Su(t,e,r,n=$u){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 vu(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=ct(e.runnerPublicKey,JSON.stringify(c));Ki(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();F();je();te();var Ru=16*1024;function ey(t){return Ie.test(t)?ft(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ie}`}function Tu(t,e,r,n){let o=ey(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(lr(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>Ru)return{ok:!1,detail:`secret value too large (max ${Ru} chars)`};try{return qa(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Iu(t,e){try{return Ya(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)}}}te();kt();var bo=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=Ue(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 Mt){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let 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=Ue(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=ty(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function ty(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}F();var ko=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 v=e.stageField?{stageField:e.stageField}:{},x=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},E=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(E){let j=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[B,pe]=await Promise.all([j.length>0?r.listIssues({projectKey:e.projectKey,columns:j,...v,...x}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...v})]),ye=new Map;for(let A of[...B,...pe])ye.set(A.id,A);o=[...ye.values()]}else{let j=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:j,...v,...x})}}catch(v){this.log.warn(`[yt-sync] listIssues failed: ${v instanceof Error?v.message:String(v)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let v of o){if(s.add(v.id),a.has(v.status))continue;let x=await Eu(r,v.id,e.sinceMs,this.log);x&&i.set(v.id,x)}let c=[];for(let v of e.offBoardIssueIds){if(s.has(v))continue;let x=await Eu(r,v,e.sinceMs,this.log);if(x&&x.length>0&&i.set(v,x),e.requireAssignee||x&&x.length>0){let L=await oy(r,v,e.stageField,this.log);if(L)c.push(L);else if(x&&x.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(v=>!a.has(v.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(v=>({issue:v,comments:i.get(v.id)??[],attachments:p.get(v.id)??[]}));try{await po(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let v of f)this.shippedAttachments.add(v)}catch(v){let x=v instanceof Error?v.message:String(v);this.abandonTick(`context task sync failed: ${x}`);return}let m=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[v,x]of i){let L=x.filter(j=>!m(j.id));if(L.length===0)continue;d.push({issueId:v,comments:L.map(ry)});let E=L.flatMap(j=>{let B=zt(j.body);return B?[{commentId:j.id,author:j.author,name:B.name,args:B.args,createdAt:j.createdAt}]:[]});E.length>0&&h.push({issueId:v,commands:E})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Cu),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Cu)}:{},observedAtMs:n};this.send(y);let $=d.reduce((v,x)=>v+x.comments.length,0),w=h.reduce((v,x)=>v+x.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${$} 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=ny(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 Cu(t){let{description:e,...r}=t;return r}function ry(t){let{body:e,...r}=t;return r}function ny(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 oy(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 Eu(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 Wi="npm i -g @code-partner/codepipe@latest";function $o(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${Te} (protocol ${Fe})`);let n=d=>e.onEvent?.(d),o=e.workspace;o?.contextDir&&uc(o.contextDir,r);let i=Pu("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Pu("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=ho(t.hubUrl,t.cliToken),h=null,y=new bo(i,g=>{d.readyState===d.OPEN&&d.send(JSON.stringify(g))},r),$=new ko(s,g=>{d.readyState===d.OPEN&&d.send(JSON.stringify(g))},r,{contextDir:o?.contextDir??null,isSelfComment:g=>f.has(g)}),w=null,v=async()=>{try{let g={trackerProvider:Li(o?.contextDir??null)};try{let T=await V(t.hubUrl,t.cliToken,t.projectId);g={...g,repos:T.repos,contextRepo:T.contextRepo}}catch(T){r.warn(`[readiness] could not fetch project summary for push checks: ${T instanceof Error?T.message:String(T)}`)}let I=await Cl(t.projectId,g);if(d.readyState!==d.OPEN)return;let k={type:"cli_readiness",projectId:t.projectId,ready:I.ready,checks:I.checks,creds:I.creds,secretNames:Va(t.projectId),checkedAt:I.checkedAt};if(d.send(JSON.stringify(k)),I.ready)r.info("[readiness] ready");else{let T=I.checks.filter(P=>!P.ok).map(P=>`${P.name}(${P.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${T.join(", ")}`)}}catch(g){r.warn(`[readiness] check failed: ${g instanceof Error?g.message:String(g)}`)}},x=()=>{v(),w=setInterval(()=>void v(),a),typeof w.unref=="function"&&w.unref()},L=()=>{w&&(clearInterval(w),w=null)},E=150,j=new Map,B=g=>{let I=j.get(g);if(!I||(I.timer&&clearTimeout(I.timer),j.delete(g),I.events.length===0||d.readyState!==d.OPEN))return;let k={type:"run_activity",projectId:t.projectId,runId:g,events:I.events};d.send(JSON.stringify(k))},pe=(g,I)=>{let k=j.get(g);if(k||(k={events:[],timer:null},j.set(g,k)),k.events.push(I),I.kind==="result"){B(g);return}k.timer||(k.timer=setTimeout(()=>B(g),E),k.timer.unref?.())},ye=o?.contextDir?new Jn(o.contextDir,t.projectId,g=>{d.readyState===d.OPEN&&d.send(JSON.stringify(g))},r):null,A=async()=>{let g=o?.contextDir;if(!g)throw new Error("no context repo clone on this CLI");let I;try{I=(await V(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let k=await Oc(g,t.projectId,I,r);return d.readyState===d.OPEN&&d.send(JSON.stringify(k)),k};return d.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let g=rc(t.projectId),I=M("ORIGIN")==="farm"?"farm":"local",k=M("FARM_ID"),T=t.accountEmail??g.email,P;try{let S=Al(t.projectId);S&&(P=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 b={type:"register",projectId:t.projectId,platformVersion:Te,protocolVersion:Fe,accountId:g.accountId,accountLabel:g.label,origin:I,inFlightActionIds:[...p],...T?{accountEmail:T}:{},...I==="farm"&&k?{farmId:k}:{},...P?{sealPublicKey:P}:{}};d.send(JSON.stringify(b))}),d.on("message",async g=>{let I=g.toString("utf-8");if(I==="pong"||I==="ping")return;let k;try{k=JSON.parse(I)}catch{return}if(!k||typeof k!="object")return;let T=k.type;if(T==="registered"){let b=k;if(b.ok){if(r.info(`[ws] registered for project ${b.projectId}`),n({kind:"registered",projectId:b.projectId??t.projectId}),y.start(),ye?.start(),x(),qi(t,o,r),o?.contextDir)try{let S=eo(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,A().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: ${b.reason??"unknown"}`),n({kind:"register_rejected",reason:b.reason??"unknown"}),c=!0,d.close();return}if(T==="hello"){let b=k;h=An(b.protocolVersion);let S=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${S}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Te}, protocol ${Fe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Wi}`),n({kind:"incompatible",hubVersion:typeof b.platformVersion=="string"?b.platformVersion:null,hubProtocol:typeof b.protocolVersion=="number"?b.protocolVersion:null,updateCommand:Wi}));return}if(T==="tracking_targets"){y.setTargets(k.targets);return}if(T==="youtrack_sync_request"){$.setRequest(k);return}if(T==="youtrack_force_sync"){$.forceSync();return}if(T==="sync_local"){await ly(k,o,d,r);return}if(T==="provision_repo"){let b=k;r.info(`[repo] provision_repo: ${b.repo.name} (${b.repo.host}:${b.repo.owner}/${b.repo.repoName})`),await ay(t,o,b.repo,r),await qi(t,o,r);return}if(T==="remove_repo"){let b=k;r.info(`[repo] remove_repo: ${b.repoName}${b.purge?" (purge)":""}`),await qi(t,o,r),b.purge&&cy(t,o,b.repoName,r);return}if(T==="context_write"){await uy(k,o,d,r);return}if(T==="adr_promote"){await py(k,o,d,r);return}if(T==="cred_update"){let b=k,S=U(t.projectId),W=S?.sealKey?await _l(t.projectId,b.kind,b.sealed,S.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},H={type:"cred_update_result",updateId:b.updateId,projectId:t.projectId,ok:W.ok,...W.detail?{detail:W.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(H)),W.ok?(r.info(`[cred] ${b.kind} replaced${W.detail?` \u2014 ${W.detail}`:""}`),v()):r.warn(`[cred] ${b.kind} replacement rejected: ${W.detail??"unknown"}`);return}if(T==="move_to_farm"){let b=k;r.info(`[farm-move] request to move ${t.projectId} onto farm ${b.farmName} (${b.farmId})`);let S=await hu(t,b,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(T==="gh_runner_setup"){let b=k;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let S=await xu(t,b,r);d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners connected on ${b.runnerName}`):r.warn(`[ghr] setup failed: ${S.error??"see per-repo statuses"}`);return}if(T==="gh_runner_teardown"){let b=k;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let S=await Su(t,b,r);d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners disconnected from ${b.runnerName}`):r.warn(`[ghr] teardown failed: ${S.error??"unknown error"}`);return}if(T==="tracker_fields_request"){let b=k,S={type:"tracker_fields_result",requestId:b.requestId,projectId:t.projectId,ok:!1},W=Je({contextDir:o?.contextDir??null});if(!W.ok)S.error=W.error;else try{S.fields=await W.provider.fetchStateFields(b.projectKey),S.ok=!0}catch(H){S.error=H instanceof Error?H.message:String(H)}d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.ok||r.warn(`[yt-fields] listing failed: ${S.error??"unknown"}`);return}if(T==="project_secret_update"||T==="project_secret_delete"){let b=k,S;if(b.type==="project_secret_update"){let H=U(t.projectId);S=H?.sealKey?Tu(t.projectId,b.name,b.sealed,H.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else S=Iu(t.projectId,b.name);let W={type:"project_secret_update_result",updateId:b.updateId,projectId:t.projectId,ok:S.ok,...S.detail?{detail:S.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(W)),S.ok?(r.info(`[secret] ${b.name} ${b.type==="project_secret_update"?"saved":"deleted"}`+(S.detail?` \u2014 ${S.detail}`:"")),v()):r.warn(`[secret] ${b.name} rejected: ${S.detail??"unknown"}`);return}if(T==="sandbox_keys"){let b=U(t.projectId);if(!b){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let S=er(t.projectId),W=Xc(k,b,S,r);for(let H of W)d.readyState===d.OPEN&&d.send(JSON.stringify(H));return}if(T!=="dispatch_action")return;let P=k;if(h===!1){let b=`refused: HUB protocol incompatible with CLI v${Te} (protocol ${Fe})`;d.send(JSON.stringify({type:"action_result",actionId:P.actionId,status:"failed",error:b})),r.warn(`[exec] ${P.actionId} (${P.action.type}) \u2192 REFUSED: ${b}`),r.warn(`[exec] update the CLI to clear this: ${Wi}`),n({kind:"action",actionId:P.actionId,actionType:P.action.type,ok:!1,error:b});return}p.add(P.actionId);try{let b=await zl({action:P.action,repo:P.repo,trackerIssueId:P.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:ye?()=>ye.reportNow():void 0,refreshContextStatus:o?.contextDir?A:void 0,onRunActivity:pe}).catch(H=>({status:"failed",error:H instanceof Error?H.message:String(H)}));P.action.type==="tracker_comment"&&b.status==="done"&&"result"in b&&typeof b.result?.commentId=="string"&&f.add(b.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:P.actionId,...b}));let S=b.status!=="failed",W=!S&&"error"in b?b.error:void 0;S?r.info(`[exec] ${P.actionId} (${P.action.type}) \u2192 done`):r.warn(`[exec] ${P.actionId} (${P.action.type}) \u2192 FAILED: ${W??"?"}`),n({kind:"action",actionId:P.actionId,actionType:P.action.type,ok:S,...W?{error:W}:{}})}finally{p.delete(P.actionId)}}),d.on("close",(g,I)=>{let k=I?.toString("utf-8")??"";if(r.info(`[ws] closed code=${g}${k?` reason=${k}`:""}`),y.stop(),$.stop(),ye?.stop(),L(),k==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:g}),!c&&setTimeout(()=>{u=m()},2e3)}),d.on("error",g=>r.warn(`[ws] error: ${g.message}`)),d}return{stop(){c=!0,u.close()}}}async function qi(t,e,r){try{let n=await V(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Qr(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 ay(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?dn(e.root,o):xe(t.projectId,r.name);if(ju(dn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await sy().clone(tn(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 cy(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?dn(e.root,o):xe(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!ju(dn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{iy(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 ly(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=dn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await nc(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 uy(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 at(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 py(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 yc(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 Pu(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}fe();te();st();Vi();ot();ao();async function Hu(t={profile:void 0}){let{cfg:e,profile:r}=Hn(t.profile),n=U(e.projectId);n&&qr(n),nn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),on(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),sn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=fn(Ji(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=qn("CLI_LOG",i,o);if(s.enabled){let u=new rr(s);Yn(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=Gn(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=fn(Ji(),".codepipe",r?fn("profiles",r,"context"):"context");if(await Fi(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Gu(()=>xo({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 Fi(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=fn(Ji(),".codepipe",r?fn("profiles",r,"context-config"):"context-config");zn(a.contextDir,m,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=$o(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(`
|
|
750
|
+
[${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}Sr();ve();fe();async function Xp(t={profile:void 0}){let e=Pe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=ho(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 V(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`)")}$n();import{readFileSync as Jb}from"node:fs";F();ve();st();jo();Gt();kt();Ft();fe();te();function ce(t){throw new Error(t)}function ue(t,e){return(typeof t!="string"||t.trim().length===0)&&ce(`config: '${e}' must be a non-empty string`),t.trim()}function xn(t,e){if(t==null)return;typeof t!="string"&&ce(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function zb(t){(!t||typeof t!="object")&&ce("config: expected a JSON object");let e=t,r=ue(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ce("config: 'hubUrl' must start with http(s)://");let n=ue(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ce("config: 'project' is required");let i=o,s=ue(i.id,"project.id");Dt.test(s)||ce("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=ue(i.name,"project.name"),c=ue(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ce("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ce("config: 'project.repos' must be an array");let p=l.map((w,v)=>{(!w||typeof w!="object")&&ce(`config: project.repos[${v}] must be an object`);let x=w,L=ue(x.host,`project.repos[${v}].host`);L!=="github"&&L!=="bitbucket"&&L!=="gitlab"&&ce(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:ue(x.name,`project.repos[${v}].name`),host:L,owner:ue(x.owner,`project.repos[${v}].owner`),repoName:ue(x.repoName,`project.repos[${v}].repoName`)},j=xn(x.defaultBranch,`project.repos[${v}].defaultBranch`);j&&(E.defaultBranch=j);let B=xn(x.mountAs,`project.repos[${v}].mountAs`);return B&&(E.mountAs=B),E}),f=i.contextRepo;(!f||typeof f!="object")&&ce("config: 'project.contextRepo' is required");let u=f,m=xn(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&ce("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:m,owner:ue(u.owner,"project.contextRepo.owner"),name:xn(u.name,"project.contextRepo.name")??nt(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:d}},y=xn(i.youtrackProjectKey,"project.youtrackProjectKey");y&&(h.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&ce("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ce("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites);let $=e.secrets;if($!==void 0){(typeof $!="object"||$===null)&&ce("config: 'secrets' must be an object");let w=$,v={};if(w.github){let x=w.github;v.github={token:ue(x.token,"secrets.github.token")}}if(w.bitbucket){let x=w.bitbucket;v.bitbucket={email:ue(x.email,"secrets.bitbucket.email"),apiToken:ue(x.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let x=w.gitlab;v.gitlab={token:ue(x.token,"secrets.gitlab.token")}}if(w.youtrack){let x=w.youtrack;v.youtrack={url:ue(x.url,"secrets.youtrack.url").replace(/\/$/,""),token:ue(x.token,"secrets.youtrack.token")}}if(w.contextWrite){let x=w.contextWrite;v.contextWrite={token:ue(x.token,"secrets.contextWrite.token")}}h.secrets=v}return h}async function Xb(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Qb(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await yt(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 wt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await ro(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 bt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await xt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Md(t){let e=!t.configPath||t.configPath==="-"?await Xb():Jb(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){ce(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=zb(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 Qb(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 Tr(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??tr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){ce(`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 St(o,i,a)}catch(u){if(u instanceof N&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await V(o,i,s.id);else if(u instanceof N)ce(`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),it({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${qe(s.id)}`),Bt(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 pn(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`)}ve();te();import{cancel as Gd,intro as Fd,isCancel as Hd,log as hs,outro as Zb,password as Kd}from"@clack/prompts";async function ek(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Wd(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await ek(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Fd("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),hs.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Kd({message:"Claude OAuth token"});Hd(i)&&(Gd("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),za({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Wn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Pe(t.profile);if(!e){Fd(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),hs.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Kd({message:"Claude OAuth token"});Hd(i)&&(Gd("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=U(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},X(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(hs.success("Claude OAuth token saved."),Zb("It will be sealed into job bundles when a SANDBOX (re)connects."))}F();ve();st();jo();Gt();Ao();fe();te();import{cancel as tk,confirm as rk,intro as nk,isCancel as qd,log as he,outro as ok,select as Yd,text as jt}from"@clack/prompts";function Vd(t){tk(t),process.exit(1)}function _r(t){return qd(t)&&Vd("aborted"),t}function Sn(t){return qd(t)&&Vd("aborted"),typeof t=="string"?t:""}async function ik(t,e){let r=_r(await Yd({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=Sn(await jt({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=Sn(await jt({message:"Context Repo name",placeholder:nt(t),initialValue:nt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Jd(t={profile:void 0}){let e=Pe(t.profile);nk(`codepipe project add \u2192 ${e.hubUrl}`);let r=_r(await jt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>Dt.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=_r(await jt({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=_r(await Yd({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=_r(await jt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=_r(await rk({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=Sn(await jt({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()||_e($)?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=_e(u);he.message(`${m.host}: ${m.owner}/${m.repoName}`);let d=Sn(await jt({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:$=>$.trim().length>0?void 0:"required"})).trim(),h=Sn(await jt({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 ik(r,a),p=U(e.projectId);he.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Tr(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??tr(),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 St(e.hubUrl,e.cliToken,c);he.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Bt(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}`),ok("done")}catch(u){u instanceof N?(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)}}Sr();ve();fe();te();ot();$n();import{existsSync as sk,rmSync as ak}from"node:fs";import{confirm as ck,intro as lk,isCancel as uk,log as At,outro as pk,spinner as dk}from"@clack/prompts";function Xe(t){At.error(t),process.exit(1)}var zd=t=>t.trim().replace(/\/+$/,"");async function Xd(t){lk("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Ee()?.spec.projectId??void 0;e||Xe("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=De(e);r||Xe(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=zd(r.hubUrl),o=r.projectId,i=zd(t.hub);i.startsWith("http")||Xe("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Xe(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let $=dk();$.start(`reading project ${o} from ${n}\u2026`);try{l=await V(n,r.cliToken,o),$.stop(`read project ${o} (${l.name})`)}catch(w){throw $.stop("could not read the source project",1),w instanceof N&&Xe(`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||Xe(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let p=U(o),f=(t.account??r.accountEmail??await jr()).trim().toLowerCase();if(At.message(`move project '${o}'
|
|
747
751
|
from : ${n} (profile ${e})
|
|
748
752
|
to : ${i} (profile ${s}, project ${a}, account ${f})
|
|
749
753
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
750
754
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
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
|
|
752
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await
|
|
753
|
-
`)}async function
|
|
755
|
+
`+(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 $=await ck({message:"Continue?",initialValue:!0});(uk($)||!$)&&Xe("aborted")}!c&&a===o&&At.warn(`source and destination share the same project id, so they share one secrets file (${qe(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 Ar(i,f),d={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};At.step(`registering project on ${i}\u2026`);let h;try{h=await St(i,u,d)}catch($){if($ instanceof N&&$.status===409){At.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await V(i,u,a)}catch(w){throw w instanceof N&&Xe(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if($ instanceof N&&$.status===403)Xe(`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($ instanceof N)Xe(`target HUB \u2192 ${$.status} ${$.message}`);else throw $}At.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),it({hubUrl:i,cliToken:u,projectId:a,accountEmail:m},s);let y={...p??{},hubUrl:i,cliToken:u,projectId:a};if(delete y.sandboxPins,X(y),At.success(`profile '${s}' \u2192 ${qe(a)}`),c){let $=Me(s);sk($)&&(ak($),At.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}pk(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}ve();import{existsSync as ys,rmSync as fk,statSync as mk}from"node:fs";import{join as Bo,relative as gk,resolve as hk}from"node:path";import{cancel as yk,intro as Zd,isCancel as wk,log as ne,outro as ef,text as qt}from"@clack/prompts";import{simpleGit as tf}from"simple-git";Ao();fe();te();ot();function Se(t){yk(t),process.exit(1)}function Yt(t){return wk(t)&&Se("aborted"),typeof t=="string"?t:""}async function Qd(t){try{let e=await tf(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function bk(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function kk(t,e){let r=U(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(bk(r,e)){ne.message(`reusing existing ${e} credentials`);return}if(ne.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Yt(await qt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Yt(await qt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Yt(await qt({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),ne.success(`saved ${e} credentials`)}async function rf(t){let e=Pe(t.profile);Zd(`codepipe repo add \u2192 project ${e.projectId}`);let r=Ee()??void 0,n;try{n=(await V(e.hubUrl,e.cliToken,e.projectId)).repos}catch(w){Se(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await Qd(process.cwd());w?(o=process.cwd(),ne.message(`using the current directory (${w})`)):o=Yt(await qt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:v=>v.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(ys(o)&&mk(o).isDirectory()){i=hk(o);let w=await Qd(i);w||Se(`${i} is not a git repository (no origin remote)`);let v=_e(w);v||Se(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=v,s=w,ne.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let w=_e(o);w||Se(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,s=o,ne.message(`${a}: ${c}/${l}`)}let p=Yt(await qt({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)&&Se(`a repo named "${p}" is already registered`);let f=Yt(await qt({message:"default branch (optional)",placeholder:"main"})).trim(),u=p;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let w=gk(r.root,i);u=w===""?".":w}let m=Yt(await qt({message:"mount_as (directory relative to the workspace root)",placeholder:u,initialValue:u})).trim()||u;n.some(w=>(w.mountAs??w.name)===m)&&Se(`mount_as "${m}" is already used by another repo`),await kk(e,a);let d={name:p,host:a,owner:c,repoName:l,mountAs:m,...f?{defaultBranch:f}:{}};if(!i){let w=r?Bo(r.root,m):xe(e.projectId,p);if(ys(Bo(w,".git")))ne.message(`already cloned at ${w}`);else{ne.info(`cloning ${s} \u2192 ${w} \u2026`);try{await tf().clone(s,w),ne.success(`cloned into ${w}`)}catch(v){Se(`clone failed: ${v instanceof Error?v.message.trim():String(v)}
|
|
756
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await pu(e.hubUrl,e.cliToken,e.projectId,d)}catch(w){w instanceof N&&Se(`HUB \u2192 ${w.status} ${w.message}`),Se(w instanceof Error?w.message:String(w))}let{updated:y,errors:$}=Qr(e.projectId,h.repos,r?.contextDir);for(let w of y)ne.message(`updated ${w}`);for(let w of $)ne.warn(`could not update ${w.path}: ${w.error}`);ne.success(`added "${p}" \u2014 project now has ${h.repos.length} repo(s)`),ef("done")}async function nf(t){let e=Pe(t.profile);Zd(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Ee()??void 0,n;try{let c=(await V(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 du(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof N&&(a.status===404&&Se(`no repo named "${t.name}" in this project`),Se(`HUB \u2192 ${a.status} ${a.message}`)),Se(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Qr(e.projectId,o.repos,r?.contextDir);for(let a of i)ne.message(`updated ${a}`);for(let a of s)ne.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ne.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Bo(r.root,n):xe(e.projectId,t.name);if(ys(Bo(a,".git")))try{fk(a,{recursive:!0,force:!0}),ne.message(`deleted local clone ${a}`)}catch(c){ne.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ne.message(`no local clone found to purge (${a})`)}ne.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),ef("done")}async function of(t){let e=Pe(t.profile),r;try{r=(await V(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}`)}}No();us();import{existsSync as yf,mkdirSync as Rk,readFileSync as Tk,writeFileSync as Ik}from"node:fs";import{homedir as Ck}from"node:os";import{dirname as Ek,join as wf}from"node:path";import*as Or from"node:readline";fe();te();ot();No();fe();import{existsSync as ks,readFileSync as $k,writeFileSync as vk}from"node:fs";import{join as Tn}from"node:path";import{simpleGit as bs}from"simple-git";var sf=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],xk="apply-queue.json";function af(t){return Tn(t,xk)}function Nr(t){let e=af(t);if(!ks(e))return{};try{return JSON.parse($k(e,"utf-8"))}catch{return{}}}function cf(t,e){vk(af(t),JSON.stringify(e,null,2)+`
|
|
757
|
+
`)}async function lf(t,e,r,n,o){let i;try{i=await au(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($=>$.name===u.repoName);if(!m)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let d=Tn(t.root,m.mountAs);if(!ks(Tn(d,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await bs(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=bs(u.dir),d=await Sk(m),h=u.claimRepo;try{await m.fetch()}catch(w){return await ws(a,o),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${Rn(w)}`}}let y=`origin/${h.baseRef}`,$;try{$=await io(m,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(w){return await ws(a,o),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${Rn(w)}`}}a.push({git:m,dir:u.dir,mountAs:u.spec.mountAs,originalRef:d,branch:h.branchName,baseSha:y,deliveryCommit:$,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([...sf,"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([...sf,"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 ws(a,o),{ok:!1,message:`apply failed in ${u.mountAs}: ${Rn(m)} (rolled back all repos)`}}let l=Nr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},cf(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
758
|
${f}
|
|
755
|
-
or: /abort ${r} --reason "..."`}}function
|
|
759
|
+
or: /abort ${r} --reason "..."`}}function $s(t,e){let r=Nr(t);r[e]&&(delete r[e],cf(t,r))}async function ws(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}: ${Rn(n)} \u2014 check manually`)}}async function uf(t,e,r){let o=Nr(t.contextDir)[e];if(o){for(let i of o.repos){let s=Tn(t.root,i.mountAs);if(!ks(Tn(s,".git")))continue;let a=bs(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}: ${Rn(p)} \u2014 check manually`)}}$s(t.contextDir,e)}}async function Sk(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Rn(t){return t instanceof Error?t.message.trim():String(t)}var Mo=wf(Ck(),".codepipe","history"),pf=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],bf=500,df=40;async function kf(){let t=Ee();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=U(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),qr(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=Nr(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
|
|
756
760
|
\u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
|
|
757
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=
|
|
758
|
-
`))}async function
|
|
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}
|
|
760
|
-
`),t.unread+=1
|
|
761
|
-
bye.`),setTimeout(()=>process.exit(0),150))}function
|
|
761
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=Or.createInterface({input:process.stdin,output:process.stdout,completer:Pk,history:zk(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};Lc(s=>Vt(i,s)),i.daemon=$o({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>Vt(i,s),warn:s=>Vt(i,s)},onEvent:s=>Kk(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),xs(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await jk(i,a)){hf(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,xs(i),o.prompt()}),o.on("close",()=>{hf(i)})}function Pk(t){let e=pf.filter(r=>r.startsWith(t));return[e.length?e:pf,t]}async function jk(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return Ak(),!1;case"/status":return await _k(t),!1;case"/tasks":return await Nk(t,n),!1;case"/task":return await Ok(t,n),!1;case"/sync":return await Dk(t),!1;case"/logs":return Wk(t,n),!1;case"/monitor":return qk(t),!1;case"/apply":return await ff(t,n,"apply"),!1;case"/unstash":return await ff(t,n,"unstash"),!1;case"/applied":return await Uk(t,n),!1;case"/abort":return await Lk(t,n),!1;case"/approve":return await mf(t,n,"approve"),!1;case"/merge":return await mf(t,n,"merge"),!1;case"/login":return Mk(t,n),!1;case"/secret":return Gk(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Ak(){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(`
|
|
762
|
+
`))}async function _k(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=yf(wf(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function Nk(t,e){let r=Yk(e,"--phase");try{let n=await iu(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){Cn(n)}}async function Ok(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await su(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){Cn(n)}}async function Dk(t){let e=await kn(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 ff(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await lf(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function Uk(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=Nr(t.ws.contextDir)[r],i=Vk(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?Bk(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 cu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);$s(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Cn(c)}}async function mf(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await uu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Cn(o)}}async function Lk(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=Jk(e,"--reason")||"local apply aborted";await uf(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await lu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Cn(o)}}function Bk(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Mk(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 Gk(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(`
|
|
763
|
+
`)}`:" (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}Fk(t.secrets,n,i),X(t.secrets),qr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}Hk(t.secrets,n),X(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function Fk(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 Hk(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 Kk(t,e){switch(e.kind){case"connected":t.connection="connecting",Vt(t,"[hub] connected");break;case"registered":t.connection="registered",Vt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",In(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Vt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",In(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":In(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?Vt(t,`[hub] action ${e.actionType} done`):In(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Vt(t,e){t.logBuffer.push(e),t.logBuffer.length>bf&&t.logBuffer.shift(),t.follow&&In(t,e)}function Wk(t,e){let r=e[0];if(r==="follow"||r==="on"){vs(t,!0);return}if(r==="off"){vs(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(bf,Number(r)||df)):df,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 qk(t){vs(t,!t.follow)}function vs(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function In(t,e){Or.cursorTo(process.stdout,0),Or.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
764
|
+
`),t.unread+=1,xs(t),t.rl.prompt(!0)}function xs(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var gf=!1;function hf(t){gf||(gf=!0,Xk(t.rl),t.daemon.stop(),console.log(`
|
|
765
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function Yk(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Vk(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 Jk(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Cn(t){t instanceof N?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function zk(){if(!yf(Mo))return[];try{return Tk(Mo,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Xk(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{Rk(Ek(Mo),{recursive:!0}),Ik(Mo,r.slice().reverse().join(`
|
|
762
766
|
`)+`
|
|
763
|
-
`)}catch{}}vr();q();Te();vr();ke();fe();bn();import{hostname as Vk}from"node:os";import{cancel as Jk,confirm as yf,intro as zk,isCancel as kf,log as Nr,multiselect as Xk,outro as wf,password as Qk,select as vs,text as xs}from"@clack/prompts";function In(t){Jk(t),process.exit(1)}function Or(t){return kf(t)&&In("aborted"),t}function Mo(t){return kf(t)&&In("aborted"),typeof t=="string"?t:""}function Ss(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function bf(t,e){try{let{secret:r}=await yo(t,e);return r}catch(r){throw r instanceof O&&r.status===404&&In("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 Zk(t,e){if(Or(await vs({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 Bi(t,e);if(o.length>0)return Or(await Xk({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));Nr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Nr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Mo(await xs({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 Rs(t){zk("codepipe worker \u2014 set up this machine as a runner");let e=ge(t.profile);e&&(Nr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Or(await yf({message:"re-register this worker?",initialValue:!1}))||In("keeping the existing registration"));let r=Oe(t.profile)??Oe(),n=Mo(await xs({message:"HUB URL",placeholder:Ge,initialValue:F("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=Or(await vs({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 bf(n,a),Nr.success("account-issued registration token minted");else if(i==="login"){let u=await Pr();a=(await Er(n,u)).cliToken,s=await bf(n,a),Nr.success("account-issued registration token minted")}else s=Mo(await Qk({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||In("a registration token is required");let c=await Zk(n,a),l=Mo(await xs({message:"worker name",initialValue:Vk(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=Or(await vs({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await Gt({hub:n,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Nr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Or(await yf({message:"start the claim-loop now?",initialValue:!0}))){wf("registered. start later with `codepipe worker`.");return}wf("starting the claim-loop\u2026"),await hn(t.profile?{profile:t.profile}:{})}function t$(){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 F("PROFILE")}var ie=t$();Aa(ie);Oa();var xe=new e$;xe.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Se).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 hf()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});xe.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 Dd({configPath:t.config,skipVerify:t.skipVerify===!0}):await Rd({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});xe.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 Va({...t,profile:ie})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});xe.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 Td({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});xe.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Mu({profile:ie})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});xe.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 hd({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});xe.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 Gd({profile:ie,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});xe.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Yp({profile:ie})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});xe.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 as({profile:ie,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var $f=xe.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");$f.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??F("HUB_URL")??Oe(ie)?.hubUrl??Ge,r=t.token??F("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ss()){await Rs({profile:ie});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=F("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??F("WORKER_NAME"),i=t.llm??F("WORKER_LLM");await Gt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ie?{profile:ie}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});$f.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ge(ie)&&Ss()){await Rs({profile:ie});return}await hn(ie?{profile:ie}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var vf=xe.command("project").description("Manage CodePipe projects");vf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Wd({profile:ie})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});vf.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 Yd({...t,cliProfile:ie})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Ts=xe.command("repo").description("Manage the project's git repositories");Ts.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 Qd({profile:ie,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ts.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 Zd({profile:ie,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ts.command("list").description("List the project's repos").action(async()=>{try{await ef({profile:ie})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});xe.parseAsync();
|
|
767
|
+
`)}catch{}}Sr();F();Ce();Sr();ve();fe();$n();import{hostname as Qk}from"node:os";import{cancel as Zk,confirm as $f,intro as e$,isCancel as Sf,log as Dr,multiselect as t$,outro as vf,password as r$,select as Ss,text as Rs}from"@clack/prompts";function En(t){Zk(t),process.exit(1)}function Ur(t){return Sf(t)&&En("aborted"),t}function Go(t){return Sf(t)&&En("aborted"),typeof t=="string"?t:""}function Ts(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function xf(t,e){try{let{secret:r}=await wo(t,e);return r}catch(r){throw r instanceof N&&r.status===404&&En("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 n$(t,e){if(Ur(await Ss({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 Gi(t,e);if(o.length>0)return Ur(await t$({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}));Dr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Dr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Go(await Rs({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 Is(t){e$("codepipe worker \u2014 set up this machine as a runner");let e=ge(t.profile);e&&(Dr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Ur(await $f({message:"re-register this worker?",initialValue:!1}))||En("keeping the existing registration"));let r=De(t.profile)??De(),n=Go(await Rs({message:"HUB URL",placeholder:Ge,initialValue:M("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=Ur(await Ss({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 xf(n,a),Dr.success("account-issued registration token minted");else if(i==="login"){let u=await jr();a=(await Ar(n,u)).cliToken,s=await xf(n,a),Dr.success("account-issued registration token minted")}else s=Go(await r$({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||En("a registration token is required");let c=await n$(n,a),l=Go(await Rs({message:"worker name",initialValue:Qk(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=Ur(await Ss({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 Ht({hub:n,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Dr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Ur(await $f({message:"start the claim-loop now?",initialValue:!0}))){vf("registered. start later with `codepipe worker`.");return}vf("starting the claim-loop\u2026"),await wn(t.profile?{profile:t.profile}:{})}function i$(){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 M("PROFILE")}var oe=i$();Oa(oe);La();var Re=new o$;Re.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Te).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 kf()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Re.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 Md({configPath:t.config,skipVerify:t.skipVerify===!0}):await Ed({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.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 Xa({...t,profile:oe})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.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 Pd({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Re.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Hu({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Re.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 kd({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.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 Wd({profile:oe,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Xp({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Re.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 ls({profile:oe,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Rf=Re.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Rf.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??M("HUB_URL")??De(oe)?.hubUrl??Ge,r=t.token??M("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ts()){await Is({profile:oe});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=M("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??M("WORKER_NAME"),i=t.llm??M("WORKER_LLM");await Ht({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...oe?{profile:oe}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Rf.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ge(oe)&&Ts()){await Is({profile:oe});return}await wn(oe?{profile:oe}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Tf=Re.command("project").description("Manage CodePipe projects");Tf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Jd({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Tf.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 Xd({...t,cliProfile:oe})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Cs=Re.command("repo").description("Manage the project's git repositories");Cs.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 rf({profile:oe,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Cs.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 nf({profile:oe,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Cs.command("list").description("List the project's repos").action(async()=>{try{await of({profile:oe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Re.parseAsync();
|