@code-partner/codepipe 0.5.3 → 0.5.4-dev.140.g8dc77f6
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 +282 -141
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,28 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Xf=Object.defineProperty;var I=(t,e)=>()=>(t&&(e=t(t=0)),e);var Qf=(t,e)=>{for(var r in e)Xf(t,r,{get:e[r],enumerable:!0})};var Re,He,ts=I(()=>{"use strict";Re="0.5.4-dev.140.g8dc77f6",He="https://hub.dev.codepipe.dev"});function Nn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Zf&&t<=Ke}var Ke,Zf,Vi=I(()=>{"use strict";ts();Ke=4,Zf=4});var Ji=I(()=>{"use strict";ts()});function On(t=4){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 Ds(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 Us(t,e=Os){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 Ls(t,e=Os){return e.filter(r=>r.version>t)}var He,Lr,Os,Bs=R(()=>{"use strict";He=".codepipe-context.yaml",Lr=".devpipe-context.yaml",Os=[{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 Ms=R(()=>{"use strict"});var If,a$,Gs=R(()=>{"use strict";If=[{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"]}],a$=If.flatMap(t=>t.phases)});function Pt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Fs,Vo=R(()=>{"use strict";Fs=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});var Ke,jn,Cf,Jo,Hs,zo=R(()=>{"use strict";Ke="opus",jn="sonnet",Cf="haiku",Jo=[Ke,jn,Cf],Hs={analyze:Ke,implement:Ke,"resolve-conflict":Ke,rework:Ke,estimate:jn,build:jn,"code-review":Ke,draft:jn,index:Ke,backfill:Ke,analysis:Ke,chat:Ke}});function pt(t){return Ef.has(t)?!0:Pf.some(e=>t.startsWith(e))}function An(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function jt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Xo(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Vs(t,e){let r=An(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=jt(r.id,"id")??n;if(!Ks.test(o))throw new Error(`id must match ${Ks} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=jt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let f=An(r.env,"env");s={};for(let[u,m]of Object.entries(f)){if(!Se.test(u))throw new Error(`env name "${u}" must match ${Se}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${u} must be a scalar`);s[u]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Ws)throw new Error(`too many params (max ${Ws})`);let f=new Set;a=c.map((u,m)=>jf(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>qs)throw new Error(`too many steps (max ${qs})`);let p=l.map((f,u)=>{let m=An(f,`steps[${u}]`),d=jt(m.run,`steps[${u}].run`);if(!d||d.trim().length===0)throw new Error(`steps[${u}].run is required`);let h=jt(m.name,`steps[${u}].name`),y=Xo(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 jf(t,e,r){let n=An(t,`params[${e}]`),o=jt(n.name,`params[${e}].name`);if(!o||!Se.test(o))throw new Error(`params[${e}].name must match ${Se}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(d=>typeof d=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=jt(n.label,`params[${e}].label`),c=jt(n.help,`params[${e}].help`),l=n.required===!0,p=Xo(n.min,`params[${e}].min`),f=Xo(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 Js(t,e){let r=t.params??[],n=new Map(r.map(i=>[i.name,i]));for(let i of Object.keys(e))if(!n.has(i))return{ok:!1,error:`unknown param: ${i}`};let o={};for(let i of r){let s=e[i.name];if(s==null||typeof s=="string"&&s.trim()==="")if(i.default!==void 0)s=i.default;else{if(i.required)return{ok:!1,error:`${i.name} is required`};continue}switch(i.type){case"string":{if(typeof s!="string")return{ok:!1,error:`${i.name} must be a string`};o[i.name]=s;break}case"enum":{if(typeof s!="string"||!(i.enum??[]).includes(s))return{ok:!1,error:`${i.name} must be one of: ${(i.enum??[]).join(", ")}`};o[i.name]=s;break}case"number":{let a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${i.name} must be a number`};if(i.min!==void 0&&a<i.min)return{ok:!1,error:`${i.name} must be \u2265 ${i.min}`};if(i.max!==void 0&&a>i.max)return{ok:!1,error:`${i.name} must be \u2264 ${i.max}`};o[i.name]=a;break}case"boolean":{let a=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:null;if(a===null)return{ok:!1,error:`${i.name} must be a boolean`};o[i.name]=a;break}}}return{ok:!0,values:o}}var Se,Ef,Pf,Ys,Ks,Ws,qs,Qo=R(()=>{"use strict";Se=/^[A-Z][A-Z0-9_]*$/,Ef=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Pf=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ys=600,Ks=/^[a-z0-9-]+$/,Ws=32,qs=64});function Zs(t=Af){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Zs(r.groups));return e}function _f(t,e){let r=JSON.stringify(e);return Zs().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function ea(t){let e=_f(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>zs)return{ok:!1,error:`${e.id} must have \u2264 ${zs} entries`};let s={};for(let[a,c]of i){if(!Se.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Se}`};if(pt(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>Xs)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Xs} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var zs,Xs,Qs,Af,ta=R(()=>{"use strict";Qo();Vo();zo();zs=64,Xs=2e3,Qs=2e3,Af=[{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:[...Jo],help:"Overrides the recommended defaults for every role not listed below."},...Fs.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Jo],help:`recommended: ${Hs[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:Qs,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:Qs,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 ra=R(()=>{"use strict"});var na=R(()=>{"use strict"});var oa=R(()=>{"use strict"});var ia=R(()=>{"use strict"});function sa(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}function et(t){return`${t}${Nf}`}var At,Nf,aa=R(()=>{"use strict";At=/^[a-z][a-z0-9-]{1,30}$/,Nf="-codepipe-ctx"});var ca=R(()=>{"use strict"});var la=R(()=>{"use strict"});function Yt(t){for(let e of Of){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Of,ua=R(()=>{"use strict";Of=[{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 pa=R(()=>{"use strict"});var da=R(()=>{"use strict"});var fa=R(()=>{"use strict"});function ma(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function ha(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=ma(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Vt.test(r))return r;let n=ma(t);return Vt.test(n)?n:Zo}function ya(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 Mr(t){return`tasks/${t}/issue.yaml`}var ga,_n,Zo,Vt,ei,$$,Nn,Br,wa=R(()=>{"use strict";ga=["bug","feature","epic"],_n="feature",Zo="TASK",Vt=/^[A-Z][A-Z0-9]{1,9}$/;ei={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},$$=ei.backlog,Nn="tracker/config.yaml",Br="tracker/counter"});var ka=R(()=>{"use strict"});function Jt(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function On(t){switch(t){case Gr.gitlab:return"oauth2";case Gr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Gr,_t,ba=R(()=>{"use strict";Gr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};_t="x-bitbucket-api-token-auth"});var $a=R(()=>{"use strict"});var va=R(()=>{"use strict";ka();ba();$a()});var xa,Y=R(()=>{"use strict";_s();Ns();Bs();Ms();Gs();Vo();zo();ta();Qo();ra();na();oa();ia();aa();ca();la();ua();pa();da();fa();wa();va();xa=20});function K(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ne=R(()=>{"use strict"});import{existsSync as Sa,renameSync as Df}from"node:fs";function Nt(t,e,r=n=>console.error(n)){if(Sa(e)||!Sa(t))return!1;try{return Df(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 Dn=R(()=>{"use strict"});import{existsSync as Un,readFileSync as Ra,readdirSync as Uf,writeFileSync as Lf}from"node:fs";import{dirname as Bf,join as dt}from"node:path";import{parse as Mf}from"yaml";function Gf(t=process.cwd()){let e=t;for(;;){if(Un(dt(e,We,"project.yaml")))return e;if(Un(dt(e,ti,"project.yaml")))return Nt(dt(e,ti),dt(e,We))&&Hf(e),e;let r=Bf(e);if(r===e)return null;e=r}}function Ff(t){let e=dt(t,We);return Un(e)?e:dt(t,ti)}function Hf(t){let e=dt(t,".gitignore");if(!Un(e))return;let r=Ra(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&&Lf(e,n)}function Re(t=process.cwd()){let e=Gf(t);if(!e)return null;let r=Ff(e),n=Kf(Ra(dt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Ta(t,e,r){return Uf(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 Ln(t,e=process.cwd()){try{let r=Re(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Kf(t){let e=Mf(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 Ia(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,ti,tt=R(()=>{"use strict";Dn();We=".codepipe",ti=".devpipe"});import{homedir as Ca}from"node:os";import{mkdirSync as Wf,readFileSync as qf,writeFileSync as Yf,existsSync as ri}from"node:fs";import{dirname as Pa,join as Bn,resolve as Vf}from"node:path";import{fileURLToPath as Jf}from"node:url";function ja(t){let e=Bn(Ea,".env");if(ri(e)&&process.loadEnvFile(e),t){let r=Bn(Ea,"profiles",t,".env");ri(r)&&process.loadEnvFile(r)}}function zt(t){let e=K("CONFIG");return e||(t?Bn(Ca(),".codepipe","profiles",t,"config.json"):Bn(Ca(),".codepipe","config.json"))}function Oe(t){let e=zt(t);if(!ri(e))return null;let r=qf(e,"utf-8");return JSON.parse(r)}function rt(t,e){let r=zt(e);Wf(Pa(r),{recursive:!0}),Yf(r,JSON.stringify(t,null,2)+`
|
|
7
|
-
|
|
8
|
-
`,{mode:384})}function
|
|
9
|
-
`,{mode:384})}function
|
|
5
|
+
`}function Xi(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 Qi(t,e=zi){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 Zi(t,e=zi){return e.filter(r=>r.version>t)}var We,Kr,zi,ea=I(()=>{"use strict";We=".codepipe-context.yaml",Kr=".devpipe-context.yaml",zi=[{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",We]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[We]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project model (the map / VIEW): model/ scaffold with the format README",addedPaths:["model/README.md"]}]});function jt(t,e){return typeof t=="string"&&e.includes(t)}function re(t){return typeof t=="string"&&t.length>0}function em(t){return typeof t=="string"&&/^(system|container|component|code):.+/.test(t)}function tm(t,e){if(!t||typeof t!="object"||Array.isArray(t))return[`${e}: must be an object`];let r=t,n=[];re(r.id)||n.push(`${e}: id must be a non-empty string`),re(r.label)||n.push(`${e}: label must be a non-empty string`),jt(r.level,At)||n.push(`${e}: level must be one of ${At.join("|")}`),r.repo!==null&&!re(r.repo)&&n.push(`${e}: repo must be a non-empty string or null`),jt(r.freshness,ra)||n.push(`${e}: freshness must be one of ${ra.join("|")}`),r.lod!==void 0&&(jt(r.lod,ta)?r.level!=="code"&&n.push(`${e}: lod is only allowed on code-level nodes`):n.push(`${e}: lod must be one of ${ta.join("|")}`));for(let o of["parent","summary","contentHash"])r[o]!==void 0&&!re(r[o])&&n.push(`${e}: ${o} must be a non-empty string`);if(r.links!==void 0&&(Array.isArray(r.links)?r.links.forEach((o,s)=>{let i=o;(!i||typeof i!="object"||!jt(i.kind,na)||!re(i.ref))&&n.push(`${e}: links[${s}] must be { kind: ${na.join("|")}, ref }`)}):n.push(`${e}: links must be a list`)),r.source!==void 0){let o=r.source;(!o||typeof o!="object"||Array.isArray(o)||!re(o.repo))&&n.push(`${e}: source must be an object with a non-empty repo`)}if(r.layout!==void 0){let o=r.layout;(o&&typeof o=="object"&&!Array.isArray(o)?["x","y","width","height"].every(i=>typeof o[i]=="number"):!1)||n.push(`${e}: layout must carry numeric x/y/width/height`)}return n}function rm(t,e){if(!t||typeof t!="object"||Array.isArray(t))return[`${e}: must be an object`];let r=t,n=[];return re(r.id)||n.push(`${e}: id must be a non-empty string`),jt(r.kind,oa)||n.push(`${e}: kind must be one of ${oa.join("|")}`),re(r.from)||n.push(`${e}: from must be a non-empty string`),re(r.to)||n.push(`${e}: to must be a non-empty string`),r.repo!==null&&!re(r.repo)&&n.push(`${e}: repo must be a non-empty string or null`),n}function ns(t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,errors:["shard must be an object"]};let e=t,r=[];(typeof e.modelFormatVersion!="number"||!Number.isFinite(e.modelFormatVersion))&&r.push("modelFormatVersion must be a number"),jt(e.level,At)||r.push(`level must be one of ${At.join("|")}`);let n=e.repo;n!==null&&!re(n)&&r.push("repo must be a non-empty string or null"),e.container!==void 0&&!re(e.container)&&r.push("container must be a non-empty string"),e.builtFromCommit!==null&&!re(e.builtFromCommit)&&r.push("builtFromCommit must be a non-empty string or null");let o=new Set;return Array.isArray(e.nodes)?e.nodes.forEach((s,i)=>{let a=s??{},c=re(a.id)?`node ${a.id}`:`nodes[${i}]`;r.push(...tm(s,c)),re(a.id)&&(o.has(a.id)&&r.push(`${c}: duplicate id`),o.add(a.id)),re(n)&&(a.repo!==n&&r.push(`${c}: repo-mix \u2014 node repo must be "${n}"`),re(a.id)&&jt(a.level,At)&&a.level!=="system"&&!a.id.startsWith(`${a.level}:${n}:`)&&r.push(`${c}: id must start with "${a.level}:${n}:"`))}):r.push("nodes must be a list"),Array.isArray(e.edges)?e.edges.forEach((s,i)=>{let a=s??{},c=re(a.id)?`edge ${a.id}`:`edges[${i}]`;r.push(...rm(s,c)),re(a.from)&&!o.has(a.from)&&r.push(`${c}: dangling from \u2014 must be a node of this shard`),re(a.to)&&!o.has(a.to)&&!em(a.to)&&r.push(`${c}: to must be a shard node or a valid node id`)}):r.push("edges must be a list"),{ok:r.length===0,errors:r}}function sa(t,e){return t.id<e.id?-1:t.id>e.id?1:0}function rs(t){if(Array.isArray(t))return t.map(rs);if(t&&typeof t=="object"){let e=t,r={};for(let n of Object.keys(e).sort())e[n]!==void 0&&(r[n]=rs(e[n]));return r}return t}function aa(t){let e={...t,nodes:[...t.nodes].sort(sa),edges:[...t.edges].sort(sa)};return`${JSON.stringify(rs(e),null,2)}
|
|
6
|
+
`}var Dn,ia,At,ta,ra,na,oa,ca=I(()=>{"use strict";Dn="model",ia="model/README.md",At=["system","container","component","code"],ta=["file","class","function"],ra=["fresh","stale","orphaned","superseded"],na=["adr","task"],oa=["contains","depends_on","references"]});var la=I(()=>{"use strict"});var nm,J$,ua=I(()=>{"use strict";nm=[{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"]}],J$=nm.flatMap(t=>t.phases)});function _t(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var da,os=I(()=>{"use strict";da=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});var qe,Ln,om,ss,pa,is=I(()=>{"use strict";qe="opus",Ln="sonnet",om="haiku",ss=[qe,Ln,om],pa={analyze:qe,implement:qe,"resolve-conflict":qe,rework:qe,estimate:Ln,build:Ln,"code-review":qe,draft:Ln,index:qe,backfill:qe,analysis:qe,chat:qe}});function ft(t){return sm.has(t)?!0:im.some(e=>t.startsWith(e))}function Un(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Nt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function as(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function ya(t,e){let r=Un(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Nt(r.id,"id")??n;if(!fa.test(o))throw new Error(`id must match ${fa} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let s=Nt(r.title,"title")?.trim()||o,i;if(r.env!==void 0&&r.env!==null){let f=Un(r.env,"env");i={};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`);i[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>ma)throw new Error(`too many params (max ${ma})`);let f=new Set;a=c.map((u,m)=>am(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>ga)throw new Error(`too many steps (max ${ga})`);let d=l.map((f,u)=>{let m=Un(f,`steps[${u}]`),p=Nt(m.run,`steps[${u}].run`);if(!p||p.trim().length===0)throw new Error(`steps[${u}].run is required`);let h=Nt(m.name,`steps[${u}].name`),y=as(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:p,...h?{name:h}:{},...y!==void 0?{timeout_sec:y}:{}}});return{id:o,title:s,...i?{env:i}:{},...a?{params:a}:{},steps:d}}function am(t,e,r){let n=Un(t,`params[${e}]`),o=Nt(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 s=n.type;if(s!=="string"&&s!=="enum"&&s!=="number"&&s!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let i;if(s==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(p=>typeof p=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);i=m}let a=Nt(n.label,`params[${e}].label`),c=Nt(n.help,`params[${e}].help`),l=n.required===!0,d=as(n.min,`params[${e}].min`),f=as(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:s,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...i?{enum:i}:{},...d!==void 0?{min:d}:{},...f!==void 0?{max:f}:{},...u!=null?{default:u}:{}}}function wa(t,e){let r=t.params??[],n=new Map(r.map(s=>[s.name,s]));for(let s of Object.keys(e))if(!n.has(s))return{ok:!1,error:`unknown param: ${s}`};let o={};for(let s of r){let i=e[s.name];if(i==null||typeof i=="string"&&i.trim()==="")if(s.default!==void 0)i=s.default;else{if(s.required)return{ok:!1,error:`${s.name} is required`};continue}switch(s.type){case"string":{if(typeof i!="string")return{ok:!1,error:`${s.name} must be a string`};o[s.name]=i;break}case"enum":{if(typeof i!="string"||!(s.enum??[]).includes(i))return{ok:!1,error:`${s.name} must be one of: ${(s.enum??[]).join(", ")}`};o[s.name]=i;break}case"number":{let a=typeof i=="number"?i:typeof i=="string"?Number(i):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${s.name} must be a number`};if(s.min!==void 0&&a<s.min)return{ok:!1,error:`${s.name} must be \u2265 ${s.min}`};if(s.max!==void 0&&a>s.max)return{ok:!1,error:`${s.name} must be \u2264 ${s.max}`};o[s.name]=a;break}case"boolean":{let a=typeof i=="boolean"?i:i==="true"?!0:i==="false"?!1:null;if(a===null)return{ok:!1,error:`${s.name} must be a boolean`};o[s.name]=a;break}}}return{ok:!0,values:o}}var Ie,sm,im,ha,fa,ma,ga,cs=I(()=>{"use strict";Ie=/^[A-Z][A-Z0-9_]*$/,sm=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),im=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];ha=600,fa=/^[a-z0-9-]+$/,ma=32,ga=64});function va(t=cm){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...va(r.groups));return e}function lm(t,e){let r=JSON.stringify(e);return va().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function xa(t){let e=lm(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 s=r.trim();return e.type==="string"&&e.mustContain&&!s.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&s.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:s}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let s=r.trim();return e.suggestions?.includes(s)?{ok:!0,field:e,value:s}:{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 s=r.map(i=>typeof i=="string"?i.trim():"").filter(i=>i.length>0);return s.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:s}}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 s=Object.entries(r);if(s.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(s.length>ba)return{ok:!1,error:`${e.id} must have \u2264 ${ba} entries`};let i={};for(let[a,c]of s){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>ka)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${ka} chars`};i[a]=c}return{ok:!0,field:e,value:i}}}}var ba,ka,$a,cm,Sa=I(()=>{"use strict";cs();os();is();ba=64,ka=2e3,$a=2e3,cm=[{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:[...ss],help:"Overrides the recommended defaults for every role not listed below."},...da.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...ss],help:`recommended: ${pa[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:$a,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:$a,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 Ra=I(()=>{"use strict"});var Ia=I(()=>{"use strict"});var Ta=I(()=>{"use strict"});var Ca=I(()=>{"use strict"});function Ea(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}${um}`}var Ot,um,Pa=I(()=>{"use strict";Ot=/^[a-z][a-z0-9-]{1,30}$/,um="-codepipe-ctx"});var ja=I(()=>{"use strict"});var Aa=I(()=>{"use strict"});function Xt(t){for(let e of dm){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var dm,_a=I(()=>{"use strict";dm=[{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 Na=I(()=>{"use strict"});var Oa=I(()=>{"use strict"});var Da=I(()=>{"use strict"});function La(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Ba(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=La(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Qt.test(r))return r;let n=La(t);return Qt.test(n)?n:ls}function Ma(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),s=t.slice(0,10-o.length)+o;if(!r.has(s.toUpperCase()))return s}return t}function qr(t){return`tasks/${t}/issue.yaml`}var Ua,Bn,ls,Qt,us,lv,Mn,Wr,Fa=I(()=>{"use strict";Ua=["bug","feature","epic"],Bn="feature",ls="TASK",Qt=/^[A-Z][A-Z0-9]{1,9}$/;us={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},lv=us.backlog,Mn="tracker/config.yaml",Wr="tracker/counter"});var Ga=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 Fn(t){switch(t){case Yr.gitlab:return"oauth2";case Yr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Yr,Dt,Ha=I(()=>{"use strict";Yr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Dt="x-bitbucket-api-token-auth"});var Ka=I(()=>{"use strict"});var Wa=I(()=>{"use strict";Ga();Ha();Ka()});var qa,q=I(()=>{"use strict";Vi();Ji();ea();ca();la();ua();os();is();Sa();cs();Ra();Ia();Ta();Ca();Pa();ja();Aa();_a();Na();Oa();Da();Fa();Wa();qa=20});function K(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Oe=I(()=>{"use strict"});import{existsSync as Ya,renameSync as pm}from"node:fs";function Lt(t,e,r=n=>console.error(n)){if(Ya(e)||!Ya(t))return!1;try{return pm(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 Gn=I(()=>{"use strict"});import{existsSync as Hn,readFileSync as Va,readdirSync as fm,writeFileSync as mm}from"node:fs";import{dirname as gm,join as mt}from"node:path";import{parse as hm}from"yaml";function ym(t=process.cwd()){let e=t;for(;;){if(Hn(mt(e,Ye,"project.yaml")))return e;if(Hn(mt(e,ds,"project.yaml")))return Lt(mt(e,ds),mt(e,Ye))&&bm(e),e;let r=gm(e);if(r===e)return null;e=r}}function wm(t){let e=mt(t,Ye);return Hn(e)?e:mt(t,ds)}function bm(t){let e=mt(t,".gitignore");if(!Hn(e))return;let r=Va(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let s=o.trim();return s===".devpipe"||s===".devpipe/"||s==="/.devpipe"||s==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
|
|
7
|
+
`);n!==r&&mm(e,n)}function Te(t=process.cwd()){let e=ym(t);if(!e)return null;let r=wm(e),n=ps(Va(mt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Ja(t,e,r){return fm(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 Kn(t,e=process.cwd()){try{let r=Te(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function ps(t){let e=hm(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:[],s=[];for(let i of o){if(!i||typeof i!="object")continue;let a=i,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let d=a.host,f=d==="bitbucket"?"bitbucket":d==="gitlab"?"gitlab":"github";s.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:s}}function za(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 Ye,ds,Ve=I(()=>{"use strict";Gn();Ye=".codepipe",ds=".devpipe"});import{homedir as Xa}from"node:os";import{mkdirSync as km,readFileSync as $m,writeFileSync as vm,existsSync as fs}from"node:fs";import{dirname as Za,join as Wn,resolve as xm}from"node:path";import{fileURLToPath as Sm}from"node:url";function ec(t){let e=Wn(Qa,".env");if(fs(e)&&process.loadEnvFile(e),t){let r=Wn(Qa,"profiles",t,".env");fs(r)&&process.loadEnvFile(r)}}function er(t){let e=K("CONFIG");return e||(t?Wn(Xa(),".codepipe","profiles",t,"config.json"):Wn(Xa(),".codepipe","config.json"))}function De(t){let e=er(t);if(!fs(e))return null;let r=$m(e,"utf-8");return JSON.parse(r)}function ot(t,e){let r=er(e);km(Za(r),{recursive:!0}),vm(r,JSON.stringify(t,null,2)+`
|
|
8
|
+
`,{mode:384})}function qn(t){if(t)return{cfg:Ce(t),profile:t};let e;try{e=Te()?.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:Ce(void 0),profile:void 0}}function Ce(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 ${er(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Qa,$e=I(()=>{"use strict";Oe();Ve();Qa=xm(Za(Sm(import.meta.url)),"..")});import{homedir as oc}from"node:os";import{existsSync as sc,mkdirSync as ic,readFileSync as ac,writeFileSync as cc}from"node:fs";import{dirname as lc,join as uc}from"node:path";function dc(t,e,r){let n=G(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},Q(n)}function pc(t,e){let r=G(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],Q(r),!0)}function fc(t){return Object.keys(G(t)?.secrets??{}).sort()}function Yn(t,e,r){let n=G(t);if(!n)return"mismatch";let o=n.sandboxPins??{},s=o[e];return s&&s===r?"ok":s&&s!==r?"mismatch":(o[e]=r,n.sandboxPins=o,Q(n),"pinned")}function mc(t,e){let r=G(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],Q(r),!0):!1}function Je(t){return uc(oc(),".codepipe","secrets",`${t}.json`)}function G(t){let e=Je(t);return sc(e)?JSON.parse(ac(e,"utf-8")):null}function Q(t){let e=Je(t.projectId);ic(lc(e),{recursive:!0}),cc(e,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function Vn(){return uc(oc(),".codepipe","shared.json")}function ms(){let t=Vn();return sc(t)?JSON.parse(ac(t,"utf-8")):null}function gc(t){let e=Vn();ic(lc(e),{recursive:!0}),cc(e,JSON.stringify(t,null,2)+`
|
|
10
|
+
`,{mode:384})}function tr(t){let e=G(t)?.claude?.oauthToken;return e||ms()?.claude?.oauthToken}function Vr(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 rr(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var ne=I(()=>{"use strict"});import{appendFileSync as Rm,existsSync as yc,mkdirSync as Im,renameSync as wc,statSync as Tm,unlinkSync as Cm}from"node:fs";import{Writable as Em}from"node:stream";import{join as Pm}from"node:path";function Jn(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,s=jm(process.env[`${t}_MAX_BYTES`]??String(bc.maxBytes)),i=process.env[`${t}_MAX_FILES`],a=i?Math.max(1,Number(i)):bc.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:s,maxFiles:a}}function jm(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 zn(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...s)=>{n(...s);try{t.writeLine(Am(o,s))}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 Am(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:_m(o)).join(" ");return`${r} ${t} ${n}`}function _m(t){try{return JSON.stringify(t)}catch{return String(t)}}var bc,nr,gs=I(()=>{"use strict";bc={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},nr=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Im(e.dir,{recursive:!0}),this.currentPath=Pm(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
|
|
10
11
|
`)?e:e+`
|
|
11
|
-
`;
|
|
12
|
+
`;Rm(this.currentPath,r,"utf-8")}asWritable(){return new Em({write:(e,r,n)=>{try{let o=typeof e=="string"?e:e.toString("utf-8");for(let s of o.split(/\r?\n/))s&&this.writeLine(s);n()}catch(o){n(o)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!yc(this.currentPath)||Tm(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;yc(n)&&(r>=this.cfg.maxFiles?Cm(n):wc(n,`${this.currentPath}.${r+1}`))}wc(this.currentPath,`${this.currentPath}.1`)}}}});import{existsSync as gt,mkdirSync as Cc,readFileSync as bs,writeFileSync as or}from"node:fs";import{homedir as Vm}from"node:os";import{join as ze}from"node:path";import{simpleGit as Jm}from"simple-git";function zr(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,s]of n){let i=ze(t,o);gt(i)||(or(i,s),r.push(o))}return r}function Ut(t,e,r){let n=ze(Vm(),".codepipe","profiles",t,"context-config");return Cc(n,{recursive:!0}),or(ze(n,"project.yaml"),e.projectYaml),or(ze(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 sr){let o=ze(e,n),s=ze(t,n);if(!(!gt(o)||gt(s)))try{or(s,bs(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(i){r.warn(`[config] could not seed ${n}: ${i instanceof Error?i.message:String(i)}`)}}}function ir(t){let e=ze(t,".gitignore"),r=gt(e)?bs(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(i=>i.trim()));if(sr.filter(i=>!n.has(i)&&!n.has(`/${i}`)).length===0)return!1;let s=r.length===0||r.endsWith(`
|
|
12
13
|
`)?"":`
|
|
13
|
-
`;return
|
|
14
|
+
`;return or(e,r+s+zm.join(`
|
|
14
15
|
`)+`
|
|
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
|
|
18
|
-
`)+(
|
|
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 Qn(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 Fm(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 Fm(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Zn(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=yc.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: ${yc.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 wc(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 Hm(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 hi(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 wi(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new yi(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new ki(e)}return new bi}var Dt,yc,yi,wi,ki,bi,wt=R(()=>{"use strict";Dt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};yc=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];yi=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new Dt(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},wi=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new Dt(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let p=await i.json();for(let f of p.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(l=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],p=[];for(let f of l.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${o}/actions/runs/${f.id}/jobs?per_page=50`,{headers:n});if(!u.ok)continue;let m=(await u.json()).jobs??[];for(let d of m.filter(h=>h.conclusion==="failure")){let h=await fetch(`${o}/actions/jobs/${d.id}/logs`,{headers:n});if(!h.ok)continue;let y=await h.text();p.push(`### CI job: ${d.name}
|
|
16
|
+
`),!0}async function Ec(t,e){try{if(!gt(ze(t,".git")))return;let r=Jm(t),n=(await r.raw(["ls-files","--",...sr])).split(`
|
|
17
|
+
`).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 vs(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 ks(t){let e=new Map;for(let r of sr){let n=ze(t,r);gt(n)&&e.set(r,bs(n))}return e}function $s(t,e){Cc(t,{recursive:!0});for(let[r,n]of e){let o=ze(t,r);gt(o)||or(o,n)}}var sr,zm,st=I(()=>{"use strict";it();sr=["project.yaml","regimen.yaml"];zm=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Xm,mkdirSync as Qm,rmSync as Zm,writeFileSync as xs}from"node:fs";import{dirname as eg,isAbsolute as tg,join as Ac,normalize as ro}from"node:path";import{simpleGit as _c}from"simple-git";async function Ss(t,e){let r=ro(t),o=(to.get(r)??Promise.resolve()).catch(()=>{}).then(e);to.set(r,o);try{return await o}finally{to.get(r)===o&&to.delete(r)}}async function Xe(t,e,r){return Ss(t,()=>Rs(t,e,r))}async function Rs(t,e,r){if(!Xm(Ac(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=oe(t,a.path);if(a.deleted){Zm(c,{force:!0});continue}Qm(eg(c),{recursive:!0}),a.encoding==="base64"?xs(c,Buffer.from(a.content,"base64")):xs(c,a.content)}let n=_c(t),o=e.filter(a=>!a.deleted).map(a=>a.path),s=e.filter(a=>a.deleted).map(a=>a.path);for(let a=0;a<o.length;a+=eo)await n.raw(["add","-A","-f","--",...o.slice(a,a+eo)]);for(let a=0;a<s.length;a+=eo)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...s.slice(a,a+eo)]);await n.raw(["reset","-q","--",...sr]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await vs(t))}async function vs(t){let e=_c(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Pc;n++){try{await e.push();return}catch(s){r=s}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let s=await og(e);if(s.length>0&&s.every(a=>rg.has(a)||jc.test(a))){for(let a of s)jc.test(a)?await ng(e,t,a):await e.raw(["checkout","--theirs","--",a]);await e.add(s),await e.raw(["-c","core.editor=true","rebase","--continue"])}else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${s.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 ng(t,e,r){let n=async i=>await t.raw(["show",`:${i}:${r}`]).catch(()=>""),o=new Map;for(let i of[await n(2),await n(3)])for(let a of i.split(`
|
|
18
|
+
`)){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 s=[...o.values()].sort((i,a)=>i.createdAt.localeCompare(a.createdAt)).map(i=>i.raw);xs(oe(e,r),s.join(`
|
|
19
|
+
`)+(s.length>0?`
|
|
20
|
+
`:""))}async function og(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
21
|
+
`).map(r=>r.trim()).filter(Boolean)}function oe(t,e){if(tg(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=ro(Ac(t,e)),n=ro(t+"/");if(r!==ro(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Pc,rg,jc,eo,to,it=I(()=>{"use strict";st();Pc=3,rg=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md","model/INDEX.json"]),jc=/^tasks\/[^/]+\/comments\.jsonl$/,eo=500,to=new Map});function Bc(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
22
|
+
`+t.slice(t.length-e)}async function ht(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 s=(await n.json()).login??"ok",i=n.headers.get("x-oauth-scopes");if(i!==null&&e&&!i.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${i||"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 s}async function oo(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(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 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 yt(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(i){throw new Error(`cannot reach api.bitbucket.org (${i instanceof Error?i.message:String(i)})`)}if(o.ok)return t;if(o.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let s=await yg(o);throw o.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${s})`):o.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${s})`):o.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${s})`):new Error(`Bitbucket \u2192 ${o.status} ${o.statusText}${s}`)}async function yg(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function so(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 s={};try{s=await o.json()}catch{}let i=s.error?.detail?.granted;if(Array.isArray(i)){let c=Mc.filter(l=>!i.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: ${Mc.join(", ")}`}let a=s.error?.message?`: ${s.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function wt(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 Fc(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 wg(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 Ts(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 Le(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Es(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Cs(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Ps(e)}return new js}var Bt,Mc,Cs,Es,Ps,js,bt=I(()=>{"use strict";Bt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};Mc=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Cs=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 i=(await o.json()).values?.[0];return i?{url:i.links?.html?.href??"",number:i.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 Bt(`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 s=await o.json();return s.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:s.state==="DECLINED"||s.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 s=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",i=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:s,close_source_branch:o})});if(!i.ok)throw new Error(`bitbucket merge PR #${r}: ${i.status} ${await i.text()}`);let a=await i.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()}`)}},Es=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 s=(await n.json())[0];return s?{url:s.html_url,number:s.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 Bt(`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 s=await o.json();if(s.state==="closed"&&s.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(s.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let i=s.mergeable===!1||s.mergeable_state==="dirty"?"conflict":s.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:s.head?.sha?await this.fetchCiStatus(e,s.head.sha):"none",mergeable:i}}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[s,i]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(s.ok){let d=await s.json();for(let f of d.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(i.ok){let d=await i.json();(d.total_count??0)>0&&(l=!0,d.state==="pending"?a=!0:(d.state==="failure"||d.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}`,s=["failure","timed_out","cancelled","action_required","startup_failure"];try{let i=await fetch(`${o}/pulls/${r}`,{headers:n});if(!i.ok)return;let a=(await i.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??[],d=[];for(let f of l.filter(u=>u.conclusion&&s.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 p of m.filter(h=>h.conclusion==="failure")){let h=await fetch(`${o}/actions/jobs/${p.id}/logs`,{headers:n});if(!h.ok)continue;let y=await h.text();d.push(`### CI job: ${p.name}
|
|
22
23
|
|
|
23
|
-
${
|
|
24
|
+
${Bc(y,8e3)}`)}}return d.length===0?void 0:Bc(d.join(`
|
|
24
25
|
|
|
25
|
-
`),16e3)}catch{return}}async mergePR(e,r,n,o){let
|
|
26
|
+
`),16e3)}catch{return}}async mergePR(e,r,n,o){let s=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(!s.ok)throw new Error(`github merge PR #${r}: ${s.status} ${await s.text()}`);let i=await s.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 i?.sha?{mergedSha:i.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()}`)}},Ps=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 s=(await n.json())[0];return s?{url:s.web_url??"",number:s.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 Bt(`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 s=await o.json();if(s.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(s.state==="closed"||s.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let i=wg(s.head_pipeline?.status??s.pipeline?.status),a=s.merge_status==="cannot_be_merged"||s.has_conflicts===!0?"conflict":s.merge_status==="can_be_merged"&&s.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:i,mergeable:a}}async mergePR(e,r,n,o){let s=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,i,a=await fetch(s,{headers:this.headers()});if(a.ok){let d=await a.json().catch(()=>null);i=d?.sha??d?.diff_refs?.head_sha}let c=await fetch(`${s}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...i?{sha:i}:{}})});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()}`)}};js=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(Ts(e,r,"merge"))}async closePR(e,r,n){throw new Error(Ts(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Ts(e,r,"comment"))}}});import{existsSync as kt,readFileSync as ar,readdirSync as Hc}from"node:fs";import{join as As}from"node:path";import{simpleGit as Kc}from"simple-git";import{parse as Wc}from"yaml";function qc(t){try{let e=oe(t,Mn);if(!kt(e))return null;let r=Wc(ar(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Qt.test(n)?null:{prefix:n}}catch{return null}}function Yc(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
26
27
|
# The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
|
|
27
28
|
# later would orphan existing tasks/<KEY>/ directories.
|
|
28
29
|
prefix: ${t}
|
|
@@ -30,15 +31,15 @@ prefix: ${t}
|
|
|
30
31
|
# Statuses are the built-in default set for now:
|
|
31
32
|
# Backlog | To Do | In Progress | Review | Done | Rejected
|
|
32
33
|
# A configurable status set / pipeline mapping is a planned extension.
|
|
33
|
-
`}function
|
|
34
|
-
`}function
|
|
34
|
+
`}function _s(t=0){return`${t}
|
|
35
|
+
`}function bg(t){return t==="depends_on"||t==="subtask"}function kg(t){let e;try{e=Wc(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=Ua.includes(r.type)?r.type:Bn,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;bg(l.type)&&typeof l.target=="string"&&l.target&&o.push({type:l.type,targetKey:l.target})}let s=typeof r.created=="string"?r.created:new Date(0).toISOString(),i=typeof r.updated=="string"?r.updated:s,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:s,updated:i}}function Ns(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
36
|
`)+`
|
|
36
|
-
`}function
|
|
37
|
-
`),o=n.indexOf("---");if(o<0)return;let
|
|
38
|
-
`).trim();if(!(!a||a==="_(no description)_"))return a}function
|
|
37
|
+
`}function Qr(t,e){let r=oe(t,qr(e));return kt(r)?kg(ar(r,"utf-8")):null}function Vc(t){let e=As(t,"tasks");if(!kt(e))return[];let r=[];for(let n of Hc(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Qr(t,n.name);o&&r.push(o)}return r}function $g(t,e){let r=oe(t,`tasks/${e}/task.md`);if(!kt(r))return;let n=ar(r,"utf-8").split(`
|
|
38
|
+
`),o=n.indexOf("---");if(o<0)return;let s=n.slice(o+1),i=s.lastIndexOf("## Attachments");i>=0&&s.slice(i+1).every(d=>d.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(d.trim()))&&(s=s.slice(0,i));let a=s.join(`
|
|
39
|
+
`).trim();if(!(!a||a==="_(no description)_"))return a}function Zr(t,e,r={}){let n=r.withDescription?$g(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:vg(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function vg(t){return t.charAt(0).toUpperCase()+t.slice(1)}function xg(t){let e=oe(t,Wr);if(!kt(e))return 0;let r=Number.parseInt(ar(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function Sg(t,e){let r=As(t,"tasks");if(!kt(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let s of Hc(r,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=n.exec(s.name);if(!i)continue;let a=Number.parseInt(i[1],10);Number.isFinite(a)&&a>o&&(o=a)}return o}function Rg(t,e){return Math.max(xg(t),Sg(t,e))+1}async function Jc(t,e,r,n){return Ss(t,()=>Ig(t,e,r,n))}async function Ig(t,e,r,n){if(!kt(As(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Xr(t);let o=null;for(let s=0;s<Gc;s++){let i=Rg(t,e),a=`${e}-${i}`,c=[...r(a),{path:Wr,content:_s(i)}];try{return await Rs(t,c,n(a)),a}catch(l){if(o=l,await Cg(t,n(a)),await Xr(t),Tg(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Gc} attempts: ${o instanceof Error?o.message:String(o)}`)}function Tg(t,e){for(let r of e){let n=oe(t,r.path);if(!kt(n)||(r.encoding==="base64"?ar(n).toString("base64"):ar(n,"utf-8"))!==r.content)return!1}return!0}async function Xr(t){let e=Kc(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 Cg(t,e){let r=Kc(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
|
|
39
40
|
`)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
|
|
40
|
-
`).some(
|
|
41
|
-
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var
|
|
41
|
+
`).some(s=>s.trim()===e.split(`
|
|
42
|
+
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Gc,io=I(()=>{"use strict";q();it();Gc=5});function cr(t,e,r,n){return[{path:"README.md",content:Mg(t,e)},{path:".gitignore",content:_g()},{path:"CLAUDE.md",content:Og(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Ng()},{path:"knowledge/README.md",content:Dg()},{path:"knowledge/build.yaml",content:Bg()},{path:"actions/README.md",content:Lg()},{path:ia,content:Ug()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Ag()},{path:"adr/README.md",content:Eg()},{path:"adr/0000-template.md",content:Pg()},{path:"adr/INDEX.md",content:jg()},{path:We,content:On()},...t.trackerProvider==="internal"?[{path:Mn,content:Yc(t.youtrackProjectKey??ls)},{path:Wr,content:_s()}]:[]]}function Eg(){return`# ADR \u2014 architecture decision records
|
|
42
43
|
|
|
43
44
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
44
45
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -66,7 +67,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
66
67
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
67
68
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
68
69
|
open a PR to this repository.
|
|
69
|
-
`}function
|
|
70
|
+
`}function Pg(){return`# ADR-NNNN: <title>
|
|
70
71
|
|
|
71
72
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
72
73
|
- **Date:** YYYY-MM-DD
|
|
@@ -88,12 +89,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
88
89
|
## Alternatives considered
|
|
89
90
|
|
|
90
91
|
- **<alternative>** \u2014 why it was rejected.
|
|
91
|
-
`}function
|
|
92
|
+
`}function jg(){return`# ADR index
|
|
92
93
|
|
|
93
94
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
94
95
|
|
|
95
96
|
(no accepted ADRs yet)
|
|
96
|
-
`}function
|
|
97
|
+
`}function Ag(){return`# Audit
|
|
97
98
|
|
|
98
99
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
99
100
|
project appends only to its own file \u2014
|
|
@@ -102,14 +103,14 @@ project appends only to its own file \u2014
|
|
|
102
103
|
|
|
103
104
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
104
105
|
shared aggregate here.
|
|
105
|
-
`}function
|
|
106
|
+
`}function Qe(t,e,r,n){let o=t.trackerProvider==="internal";return{projectYaml:o?Fg(t):Gg(t,r,n),regimenYaml:Hg(t.automationLevel,o?!0:e,o)}}function _g(){return`# codepipe project config is local to each member's workspace
|
|
106
107
|
project.yaml
|
|
107
108
|
regimen.yaml
|
|
108
109
|
|
|
109
110
|
# codepipe runtime
|
|
110
111
|
session.log
|
|
111
112
|
apply-queue.json
|
|
112
|
-
`}function
|
|
113
|
+
`}function Ng(){return`# Index prompt
|
|
113
114
|
|
|
114
115
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
115
116
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -166,7 +167,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
166
167
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
167
168
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
168
169
|
empty or unavailable, say so briefly rather than inventing content.
|
|
169
|
-
`}function
|
|
170
|
+
`}function Og(t){return`# Project context for the CodePipe agent
|
|
170
171
|
|
|
171
172
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
172
173
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -194,7 +195,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
194
195
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
195
196
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
196
197
|
only after the analysis is approved.
|
|
197
|
-
`}function
|
|
198
|
+
`}function Dg(){return`# Knowledge
|
|
198
199
|
|
|
199
200
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
200
201
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -211,7 +212,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
211
212
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
212
213
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
213
214
|
any merge conflict in it as noise (either side converges on the next run).
|
|
214
|
-
`}function
|
|
215
|
+
`}function Lg(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
|
|
215
216
|
|
|
216
217
|
One \`<id>.yml\` per action. Every file here appears as a button on the
|
|
217
218
|
project's **RUN** tab; an action with \`params\` opens a small wizard first.
|
|
@@ -250,7 +251,140 @@ steps:
|
|
|
250
251
|
Parameter values are passed to the commands **only as env vars** \u2014 reference
|
|
251
252
|
them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
|
|
252
253
|
command text itself.
|
|
253
|
-
`}function
|
|
254
|
+
`}function Ug(){return`# model/ \u2014 the project map (C4 model)
|
|
255
|
+
|
|
256
|
+
Machine-extracted **C4 model** of the project: one graph of nodes
|
|
257
|
+
(System/Context \u2192 Container \u2192 Component \u2192 Code) and edges, with code\u2194ADR\u2194task
|
|
258
|
+
links and freshness statuses. It powers the map view in the dashboard and
|
|
259
|
+
targeted context for agent prompts. Files here are written by the pipeline
|
|
260
|
+
(extraction runs, committed by the CLI) \u2014 treat them as generated; this README
|
|
261
|
+
is the format reference.
|
|
262
|
+
|
|
263
|
+
**Structure and links only.** Model files never copy code bodies or task
|
|
264
|
+
texts \u2014 they carry ids, paths, labels, short summaries and references; heavy
|
|
265
|
+
data is read from the sources on demand.
|
|
266
|
+
|
|
267
|
+
## Layout \u2014 sharded by (repo, container, level)
|
|
268
|
+
|
|
269
|
+
model/
|
|
270
|
+
README.md # this file
|
|
271
|
+
project.json # project root, external systems, cross-repo edges
|
|
272
|
+
<repo>/ # one directory per logical repo
|
|
273
|
+
containers.json # Container nodes of the repo + their edges
|
|
274
|
+
components/<container-slug>.json # Component nodes of one container + their edges
|
|
275
|
+
code/<container-slug>.json # Code nodes (files) of one container + their edges
|
|
276
|
+
INDEX.json # DERIVED aggregate \u2014 regenerated, do not edit
|
|
277
|
+
|
|
278
|
+
- \`<repo>\` is the repo's **logical name** from the project config. Repos never
|
|
279
|
+
mix: every node of \`model/<repo>/**\` belongs to that repo, and its id carries
|
|
280
|
+
the repo as a segment. A shared Context Repo therefore keeps each project
|
|
281
|
+
repo's model apart.
|
|
282
|
+
- \`<container-slug>\` is the container's workspace path with every \`/\` turned
|
|
283
|
+
into \`-\` (e.g. \`packages/shared\` \u2192 \`packages-shared\`).
|
|
284
|
+
- Each shard carries the edges **outgoing from its own nodes**, so an
|
|
285
|
+
incremental re-extraction of one container rewrites one file. Cross-repo
|
|
286
|
+
edges live in \`project.json\` (\`"repo": null\`).
|
|
287
|
+
- \`INDEX.json\` is regenerated deterministically from the shards (like
|
|
288
|
+
\`adr/INDEX.md\`) \u2014 never hand-edited.
|
|
289
|
+
|
|
290
|
+
## Shard envelope
|
|
291
|
+
|
|
292
|
+
Every \`*.json\` file except \`INDEX.json\` is one shard:
|
|
293
|
+
|
|
294
|
+
- \`modelFormatVersion\` \u2014 version of the model **content** schema (currently
|
|
295
|
+
${1}). Its own axis, separate from the Context
|
|
296
|
+
Repo scaffold version: a reader that meets another value treats the model as
|
|
297
|
+
"needs a rebuild" \u2014 it does not fail.
|
|
298
|
+
- \`level\` \u2014 \`system\` | \`container\` | \`component\` | \`code\`.
|
|
299
|
+
- \`repo\` \u2014 the shard's logical repo; \`null\` only in \`project.json\`.
|
|
300
|
+
- \`container\` \u2014 the shard's workspace path (component/code shards).
|
|
301
|
+
- \`builtFromCommit\` \u2014 the repo commit the shard was extracted from (per repo:
|
|
302
|
+
a shared Context Repo may hold repos rebuilt at different times).
|
|
303
|
+
- \`nodes\` / \`edges\` \u2014 see below.
|
|
304
|
+
|
|
305
|
+
## Nodes and edges
|
|
306
|
+
|
|
307
|
+
A node: \`id\`, \`level\`, \`repo\` (\`null\` only on the project root and external
|
|
308
|
+
systems), \`label\`, optional \`lod\` (\`file\` | \`class\` | \`function\`, code level
|
|
309
|
+
only \u2014 \`class\`/\`function\` are extracted on demand), optional \`parent\`,
|
|
310
|
+
\`source\` (repo/path/symbol pointers), \`summary\`, \`links\`
|
|
311
|
+
(\`{ kind: adr | task, ref }\`), \`freshness\`
|
|
312
|
+
(\`fresh\` | \`stale\` | \`orphaned\` | \`superseded\`), \`layout\` (baked offline)
|
|
313
|
+
and \`contentHash\` (hash of structural inputs).
|
|
314
|
+
|
|
315
|
+
An edge: \`id\` (canonically \`<kind>|<from>|<to>\`), \`kind\`
|
|
316
|
+
(\`contains\` | \`depends_on\` | \`references\`), \`from\` (a node of the shard),
|
|
317
|
+
\`to\` (may point outside the shard) and \`repo\` (\`null\` = cross-repo).
|
|
318
|
+
|
|
319
|
+
Node ids are stable keys, built to survive refactoring where possible:
|
|
320
|
+
|
|
321
|
+
- \`system:project\` \u2014 the single project root; \`system:ext:<slug>\` \u2014 an
|
|
322
|
+
external system;
|
|
323
|
+
- \`container:<repo>:<workspace-path>\`;
|
|
324
|
+
- \`component:<repo>:<slug>\` \u2014 the slug is AI-assigned once and re-fed on later
|
|
325
|
+
runs, so it is stable and independent of file paths;
|
|
326
|
+
- \`code:<repo>:<repo-relative-path>\`, plus \`#<symbol>\` for class/function
|
|
327
|
+
detail.
|
|
328
|
+
|
|
329
|
+
## Canonical serialization
|
|
330
|
+
|
|
331
|
+
Files are canonical JSON \u2014 object keys sorted, \`nodes\`/\`edges\` sorted by
|
|
332
|
+
\`id\`, 2-space indent, trailing newline \u2014 so the same input always produces a
|
|
333
|
+
byte-identical file and every incremental change is a minimal, reviewable
|
|
334
|
+
diff.
|
|
335
|
+
|
|
336
|
+
## Example \u2014 a real slice
|
|
337
|
+
|
|
338
|
+
\`model/cp-codepipe/components/packages-shared.json\` (one component of the
|
|
339
|
+
\`packages/shared\` container, linked to its ADR):
|
|
340
|
+
|
|
341
|
+
\`\`\`json
|
|
342
|
+
{
|
|
343
|
+
"builtFromCommit": "0d1e2f3",
|
|
344
|
+
"container": "packages/shared",
|
|
345
|
+
"edges": [
|
|
346
|
+
{
|
|
347
|
+
"from": "component:cp-codepipe:shared-context-contracts",
|
|
348
|
+
"id": "contains|component:cp-codepipe:shared-context-contracts|code:cp-codepipe:packages/shared/src/context-template.ts",
|
|
349
|
+
"kind": "contains",
|
|
350
|
+
"repo": "cp-codepipe",
|
|
351
|
+
"to": "code:cp-codepipe:packages/shared/src/context-template.ts"
|
|
352
|
+
},
|
|
353
|
+
{
|
|
354
|
+
"from": "component:cp-codepipe:shared-context-contracts",
|
|
355
|
+
"id": "contains|component:cp-codepipe:shared-context-contracts|code:cp-codepipe:packages/shared/src/project-map.ts",
|
|
356
|
+
"kind": "contains",
|
|
357
|
+
"repo": "cp-codepipe",
|
|
358
|
+
"to": "code:cp-codepipe:packages/shared/src/project-map.ts"
|
|
359
|
+
}
|
|
360
|
+
],
|
|
361
|
+
"level": "component",
|
|
362
|
+
"modelFormatVersion": ${1},
|
|
363
|
+
"nodes": [
|
|
364
|
+
{
|
|
365
|
+
"freshness": "fresh",
|
|
366
|
+
"id": "component:cp-codepipe:shared-context-contracts",
|
|
367
|
+
"label": "Context Repo contracts",
|
|
368
|
+
"level": "component",
|
|
369
|
+
"links": [
|
|
370
|
+
{ "kind": "adr", "ref": "ADR-0020" },
|
|
371
|
+
{ "kind": "task", "ref": "DEV-481" }
|
|
372
|
+
],
|
|
373
|
+
"parent": "container:cp-codepipe:packages/shared",
|
|
374
|
+
"repo": "cp-codepipe",
|
|
375
|
+
"summary": "Format contracts of the Context Repo: scaffold versioning and the project-map schema."
|
|
376
|
+
}
|
|
377
|
+
],
|
|
378
|
+
"repo": "cp-codepipe"
|
|
379
|
+
}
|
|
380
|
+
\`\`\`
|
|
381
|
+
|
|
382
|
+
The sibling shards of the same slice: \`model/cp-codepipe/containers.json\`
|
|
383
|
+
holds \`container:cp-codepipe:packages/shared\` (with its \`contains\` edges down
|
|
384
|
+
to the components), and \`model/cp-codepipe/code/packages-shared.json\` holds
|
|
385
|
+
the two \`code:cp-codepipe:packages/shared/src/*.ts\` file nodes with their
|
|
386
|
+
\`depends_on\` edges.
|
|
387
|
+
`}function Bg(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
254
388
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
255
389
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
256
390
|
#
|
|
@@ -266,7 +400,7 @@ command text itself.
|
|
|
266
400
|
# - name: test
|
|
267
401
|
# run: npm test
|
|
268
402
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
269
|
-
`}function
|
|
403
|
+
`}function Mg(t,e){return`# ${e.name}
|
|
270
404
|
|
|
271
405
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
272
406
|
|
|
@@ -292,7 +426,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
292
426
|
pipeline \u2014 don't edit them by hand.
|
|
293
427
|
|
|
294
428
|
Automation level: **${t.automationLevel}**.
|
|
295
|
-
`}function
|
|
429
|
+
`}function Fg(t){return`# Project description for CodePipe.
|
|
296
430
|
id: ${t.projectId}
|
|
297
431
|
name: ${t.name}
|
|
298
432
|
|
|
@@ -315,19 +449,19 @@ branch:
|
|
|
315
449
|
pattern: codepipe/<TASK_ID>
|
|
316
450
|
|
|
317
451
|
repos:
|
|
318
|
-
${
|
|
319
|
-
`}function
|
|
452
|
+
${zc(t)}
|
|
453
|
+
`}function zc(t){return t.repos.length===0?` [] # add repos here
|
|
320
454
|
`:t.repos.map(e=>` - name: ${e.name}
|
|
321
455
|
host: ${e.host}
|
|
322
456
|
owner: ${e.owner}
|
|
323
457
|
repo: ${e.repoName}
|
|
324
458
|
mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
|
|
325
459
|
default_branch: ${e.defaultBranch}`:"")).join(`
|
|
326
|
-
`)}function
|
|
460
|
+
`)}function Gg(t,e,r){let n=e?`
|
|
327
461
|
tracker_url: ${e}`:`
|
|
328
462
|
# tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
|
|
329
463
|
assignee: ${r}`:`require_assignee: false
|
|
330
|
-
# assignee: your.youtrack.login`,
|
|
464
|
+
# assignee: your.youtrack.login`,s=t.youtrackProjectKey?` project_key: ${t.youtrackProjectKey}${n}
|
|
331
465
|
poll_interval_sec: 60
|
|
332
466
|
# Name of the YT workflow field the board is driven by. Default: Stage
|
|
333
467
|
# (custom field); YouTrack's standard configuration uses State.
|
|
@@ -371,12 +505,12 @@ ${Ic(t)}
|
|
|
371
505
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
372
506
|
${o}`:` # project_key: \u2026
|
|
373
507
|
# tracker_url: https://your.youtrack.cloud
|
|
374
|
-
poll_interval_sec: 60`,
|
|
508
|
+
poll_interval_sec: 60`,i=zc(t);return`# Project description for CodePipe.
|
|
375
509
|
id: ${t.projectId}
|
|
376
510
|
name: ${t.name}
|
|
377
511
|
|
|
378
512
|
youtrack:
|
|
379
|
-
${
|
|
513
|
+
${s}
|
|
380
514
|
|
|
381
515
|
adapters:
|
|
382
516
|
tracker: youtrack
|
|
@@ -401,8 +535,8 @@ branch:
|
|
|
401
535
|
pattern: codepipe/<TASK_ID>
|
|
402
536
|
|
|
403
537
|
repos:
|
|
404
|
-
${
|
|
405
|
-
`}function
|
|
538
|
+
${i}
|
|
539
|
+
`}function Hg(t,e,r=!1){let n=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
|
|
406
540
|
automation:
|
|
407
541
|
level: ${t}
|
|
408
542
|
|
|
@@ -537,19 +671,19 @@ llm:
|
|
|
537
671
|
# # the previous task's branch (auto-merge without reworking the
|
|
538
672
|
# # tail of the chain).
|
|
539
673
|
# 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 Gg(t,e,r){return new Promise((n,o)=>{let i=bt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new Jc(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Ci(t,e,r){return new Promise(n=>{let o=bt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function Fg(t){try{let e=await fetch(t);return e.ok?new Jc(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function el(t,e=443,r=Xc){let n=`${t}:${e}`,o=Vc.get(n);if(o)return o;let i=Hg(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Vc.set(n,i),i}async function Hg(t,e,r){if(!zc)return!1;let n=8e3;if(await Ci(t,e,n))return!0;let o=await Gg(t,e,n),i=bt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Mg(o);if(!c)break;let l=await Fg(c);if(!l)break;if(s.push(l.toString()),bt.setDefaultCACertificates([...i,...s]),await Ci(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 Ci(t,e,n)}var zc,Yc,Vc,Xc,tl=R(()=>{"use strict";Ne();zc=typeof bt.getCACertificates=="function"&&typeof bt.setDefaultCACertificates=="function",Yc=!1,Vc=new Map,Xc=t=>console.warn(t)});function il(){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){Qc();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(Zc(s)&&await el(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Kg(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Wg(){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}=Wg(),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&&Kg(l.status,p)){await rl(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<o){await rl(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 sl(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 qg(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=nl.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 nl.set(o,l.id),l.id}async function al(t,e,r,n=Zr){let o=await qg(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 cl(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 ll(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 ul(t,e){let r=ol.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 ol.set(e,i.id),i.id}async function pl(t,e,r,n,o,i=Zr){let s=await ul(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 dl(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 gl(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 hl(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 yl(t,e){let r=e.stageField??Zr,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=${ml}&$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=>bl(c,r))}async function wl(t,e,r=Zr){let n=`/api/issues/${encodeURIComponent(e)}?fields=${ml}`,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 bl(await o.json(),r)}async function kl(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Vg}&$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=gl(s.attachments);return c&&(a.attachments=c),a})}function Jg(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 bl(t,e=Zr){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=gl(t.attachments);a&&(s.attachments=a);let c=Jg(t.links);return c&&(s.links=c),s}async function $l(t,e){let r=await zg(t,e);return r.length>0?r:Xg(t,e)}async function zg(t,e){let r=await ul(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:vl(s.bundle)});return i}async function Xg(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:vl(s.projectCustomField?.bundle)});return i}function vl(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var rl,Zr,nl,ol,fl,Yg,ml,Vg,Lt=R(()=>{"use strict";tl();rl=t=>new Promise(e=>setTimeout(e,t));Zr="Stage",nl=new Map;ol=new Map;fl="attachments(id,name,url,size,mimeType)",Yg="links(direction,linkType(name),issues(idReadable))",ml=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${fl},${Yg}`,Vg=`id,text,created,author(login),${fl}`});function en(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 tn(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 rn(t,e=process.env){if(!t)return!1;let r=`https://${_t}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function ji(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 Sl(t,e=process.env){return ji(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>en(t,e),e)}function Rl(t,e=process.env){return ji(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>tn(t,e),e)}function Tl(t,e=process.env){return ji(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${_t}:${encodeURIComponent(t)}@bitbucket.org/`,()=>rn(t,e),e)}var oo=R(()=>{"use strict";Y()});import{homedir as Th}from"node:os";import{existsSync as Ih,mkdirSync as Ch,readFileSync as Eh,writeFileSync as Ph}from"node:fs";import{dirname as jh,join as Ah}from"node:path";function Di(){return K("FARM_PINS")??Ah(Th(),".codepipe","farm-pins.json")}function ql(){let t=Di();if(!Ih(t))return{};try{return JSON.parse(Eh(t,"utf-8"))}catch{return{}}}function _h(t){let e=Di();Ch(jh(e),{recursive:!0}),Ph(e,JSON.stringify(t,null,2)+`
|
|
542
|
-
`,{mode:384})}function
|
|
674
|
+
`}var Mt=I(()=>{"use strict";q();io()});import{createCipheriv as kh,createDecipheriv as $h,createHash as vh,createPrivateKey as xh,createPublicKey as Gs,diffieHellman as wl,generateKeyPairSync as bl,hkdfSync as kl,randomBytes as Sh}from"node:crypto";function po(){let{publicKey:t,privateKey:e}=bl("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function be(t){let e=Buffer.from(t,"base64");return(vh("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function at(t,e){let r=Gs({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=bl("x25519"),s=n.export({type:"spki",format:"der"}),i=r.export({type:"spki",format:"der"}),a=wl({privateKey:o,publicKey:r}),c=Buffer.from(kl("sha256",a,Buffer.concat([s,i]),$l,32)),l=Sh(12),d=kh("aes-256-gcm",c,l),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,u=Buffer.concat([d.update(f),d.final()]),m=d.getAuthTag(),p={v:1,epk:s.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:u.toString("base64")};return Buffer.from(JSON.stringify(p),"utf-8").toString("base64")}function ur(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let n=xh({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Gs({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),s=o.export({type:"spki",format:"der"}),i=Gs(n).export({type:"spki",format:"der"}),a=wl({privateKey:n,publicKey:o}),c=Buffer.from(kl("sha256",a,Buffer.concat([s,i]),$l,32)),l=$h("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 $l,Ee=I(()=>{"use strict";$l=Buffer.from("devpipe-sealedbox-v1","utf-8")});import{X509Certificate as Rl}from"node:crypto";import{readFileSync as Ih}from"node:fs";import $t from"node:tls";function Th(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Cl(t=Tl){if(xl)return;xl=!0;let e=K("EXTRA_CA_FILE");if(!(!e||!Il))try{let r=Th(Ih(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}$t.setDefaultCACertificates([...$t.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 El(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 Ch(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
675
|
+
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Eh(t,e,r){return new Promise((n,o)=>{let s=$t.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let i=s.getPeerCertificate(!0),a=new Set;for(;i?.issuerCertificate&&i.issuerCertificate!==i&&i.fingerprint256&&!a.has(i.fingerprint256);)a.add(i.fingerprint256),i=i.issuerCertificate;let c=i?.raw?new Rl(i.raw):null;s.end(),n(c)});s.on("error",o),s.setTimeout(r,()=>{s.destroy(),o(new Error("tls connect timeout"))})})}function Hs(t,e,r){return new Promise(n=>{let o=$t.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 Ph(t){try{let e=await fetch(t);return e.ok?new Rl(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Pl(t,e=443,r=Tl){let n=`${t}:${e}`,o=Sl.get(n);if(o)return o;let s=jh(t,e,r).catch(i=>(r(`[tls] chain repair for ${t} failed: ${i instanceof Error?i.message:String(i)}`),!1));return Sl.set(n,s),s}async function jh(t,e,r){if(!Il)return!1;let n=8e3;if(await Hs(t,e,n))return!0;let o=await Eh(t,e,n),s=$t.getCACertificates(),i=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Ch(o);if(!c)break;let l=await Ph(c);if(!l)break;if(i.push(l.toString()),$t.setDefaultCACertificates([...s,...i]),await Hs(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${i.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return Hs(t,e,n)}var Il,xl,Sl,Tl,jl=I(()=>{"use strict";Oe();Il=typeof $t.getCACertificates=="function"&&typeof $t.setDefaultCACertificates=="function",xl=!1,Sl=new Map,Tl=t=>console.warn(t)});function Ol(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Pe(t,e,r){Cl();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,s={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,s)}catch(i){if(El(i)&&await Pl(new URL(t.baseUrl).host))return await fetch(o,s);throw i}}function Ah(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function _h(){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 Ks(t,e,r,n){let{attempts:o,baseMs:s,capMs:i}=_h(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Pe(t,r,n)}catch(d){a=new Error(`${e}: ${d instanceof Error?d.message:String(d)}`)}if(l){if(l.ok)return l;let d=await l.text();if(c<o&&Ah(l.status,d)){await Al(Math.min(i,s*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${d}`)}if(c<o){await Al(Math.min(i,s*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function vt(t){let e;try{e=await Pe(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Dl(t){try{let e=await Pe(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Nh(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,s=_l.get(o);if(s)return s;let i=await Pe(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let c=(await i.json()).customFields.find(d=>d.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(d=>d.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return _l.set(o,l.id),l.id}async function Ll(t,e,r,n=sn){let o=await Nh(t,e,r,n);await Ks(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 Ks(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Bl(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Ks(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Ml(t,e){let r=Nl.get(e);if(r)return r;let n=await Pe(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let s=(await n.json()).find(i=>i.shortName===e);if(!s)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Nl.set(e,s.id),s.id}async function Fl(t,e,r,n,o,s=sn){let i=await Ml(t,e),a=await Pe(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:n,customFields:[{name:s,$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 Gl(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,s=await Pe(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!s.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${s.status} ${await s.text()}`)}function Wl(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 ql(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 Yl(t,e){let r=e.stageField??sn,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(" "),s=`/api/issues?query=${encodeURIComponent(o)}&fields=${Kl}&$top=200`,i=await Pe(t,s);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(c=>zl(c,r))}async function Vl(t,e,r=sn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Kl}`,o=await Pe(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return zl(await o.json(),r)}async function Jl(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Dh}&$top=500`,o=await Pe(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(i=>i.created>r).map(i=>{let a={id:i.id,issueId:e,author:i.author?.login??"unknown",body:i.text??"",createdAt:new Date(i.created).toISOString()},c=Wl(i.attachments);return c&&(a.attachments=c),a})}function Lh(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 zl(t,e=sn){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),s=r.find(l=>l.name==="Type"),i={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&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),s?.value?.name&&(i.issueType=s.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(l=>l.name));let a=Wl(t.attachments);a&&(i.attachments=a);let c=Lh(t.links);return c&&(i.links=c),i}async function Xl(t,e){let r=await Uh(t,e);return r.length>0?r:Bh(t,e)}async function Uh(t,e){let r=await Ml(t,e),n=await Pe(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),s=[];for(let i of o)i.$type==="StateProjectCustomField"&&i.field?.name&&s.push({name:i.field.name,values:Ql(i.bundle)});return s}async function Bh(t,e){let r=`project: ${e}`,n=await Pe(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),s=[];for(let i of o[0]?.customFields??[])i.$type==="StateIssueCustomField"&&i.name&&s.push({name:i.name,values:Ql(i.projectCustomField?.bundle)});return s}function Ql(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Al,sn,_l,Nl,Hl,Oh,Kl,Dh,Gt=I(()=>{"use strict";jl();Al=t=>new Promise(e=>setTimeout(e,t));sn="Stage",_l=new Map;Nl=new Map;Hl="attachments(id,name,url,size,mimeType)",Oh="links(direction,linkType(name),issues(idReadable))",Kl=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Hl},${Oh}`,Dh=`id,text,created,author(login),${Hl}`});function an(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=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function cn(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=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function ln(t,e=process.env){if(!t)return!1;let r=`https://${Dt}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(s,i)=>{e[`GIT_CONFIG_KEY_${n+s}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+s}`]=i};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function qs(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,s=!1;for(let i=0;i<o;i++){let a=n[`GIT_CONFIG_KEY_${i}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${i}`]=`url.${e}.insteadOf`,s=!0)}return s||r()}function eu(t,e=process.env){return qs(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>an(t,e),e)}function tu(t,e=process.env){return qs(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>cn(t,e),e)}function ru(t,e=process.env){return qs(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Dt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>ln(t,e),e)}var fo=I(()=>{"use strict";q()});import{homedir as dy}from"node:os";import{existsSync as py,mkdirSync as fy,readFileSync as my,writeFileSync as gy}from"node:fs";import{dirname as hy,join as yy}from"node:path";function Xs(){return K("FARM_PINS")??yy(dy(),".codepipe","farm-pins.json")}function bu(){let t=Xs();if(!py(t))return{};try{return JSON.parse(my(t,"utf-8"))}catch{return{}}}function wy(t){let e=Xs();fy(hy(e),{recursive:!0}),gy(e,JSON.stringify(t,null,2)+`
|
|
676
|
+
`,{mode:384})}function by(t){return bu()[t]}function ko(t,e){let r=bu();r[t]=e,wy(r)}function $o(t,e){let r=be(e),n=by(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 ${Xs()}.`);return r}var Qs=I(()=>{"use strict";Oe();Ee()});import{setTimeout as ky}from"node:timers/promises";import $y from"ws";function vo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new $y(r)}async function xt(t,e,r){return Me(t,e,"/projects",r)}async function ku(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new D(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function xo(t,e,r,n){return Me(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function $u(t,e,r,n){return Me(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function vu(t,e,r,n){return Me(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function xu(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 D(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function So(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new D(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Zs(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new D(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Su(t,e,r={}){let n=r.attempts??3,o;for(let s=0;s<n;s++)try{let i=await Zs(t,e),a=new Set;for(let c of i)c.id!==r.excludeProjectId&&c.trackerProvider==="internal"&&c.youtrackProjectKey&&a.add(c.youtrackProjectKey.toUpperCase());return a}catch(i){o=i,s<n-1&&await ky(r.delayMs??1500)}throw o}async function Ru(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 pn(e)}if(!r.ok)throw new D(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Iu(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new D(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Tu(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new D(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Cu(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 D(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Eu(t,e,r,n){return Me(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Pu(t,e,r,n,o){return Me(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function ju(t,e,r,n,o){return Me(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function Au(t,e,r,n,o){return Me(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function fn(t,e,r,n){return Me(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function ei(t,e,r,n){await Me(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function _u(t,e,r,n){return Me(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Nu(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),s=await o.text(),i=s?JSON.parse(s):null;if(!o.ok){let a=i&&typeof i=="object"&&"error"in i?String(i.error):`HTTP ${o.status}`;throw new D(o.status,i,a)}return i}async function J(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new D(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function Me(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),s=await o.text(),i=s?JSON.parse(s):null;if(!o.ok){let a=i&&typeof i=="object"&&"error"in i?String(i.error):`HTTP ${o.status}`;throw new D(o.status,i,a)}return i}var D,pn,me=I(()=>{"use strict";D=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};pn=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{execFileSync as qy}from"node:child_process";import{mkdtempSync as Yy,mkdirSync as Vy,readFileSync as ed,rmSync as Jy,writeFileSync as zy}from"node:fs";import{tmpdir as Xy}from"node:os";import{dirname as Qy,join as td}from"node:path";function rd(t="codepipe-context"){let e=Yy(td(Xy(),"codepipe-ssh-")),r=td(e,"id_ed25519");try{return qy("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:ed(r,"utf-8"),publicKey:ed(`${r}.pub`,"utf-8").trim()}}finally{Jy(e,{recursive:!0,force:!0})}}async function nd(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 s=await o.text();if(!(o.status===422&&/already in use/i.test(s)))throw new Error(`add deploy key failed: ${o.status} ${s}`)}function od(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 sd(t,e){Vy(Qy(t),{recursive:!0});let r=e.endsWith(`
|
|
543
677
|
`)?e:e+`
|
|
544
|
-
`;return
|
|
545
|
-
`,{mode:384})}var
|
|
546
|
-
`}async function
|
|
547
|
-
`))!==-1;){let
|
|
548
|
-
`)){let
|
|
678
|
+
`;return zy(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var si=I(()=>{"use strict"});import{existsSync as id,mkdirSync as ad}from"node:fs";import{dirname as cd}from"node:path";import{simpleGit as fr}from"simple-git";function Zy(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 s=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(s)return`https://${n}@${s[1]}/${s[2]}`;let i=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return i?`https://${n}@${i[1]}`:t}function ew(t,e){return e?.contextWrite?.token?{user:Fn(t),secret:e.contextWrite.token}:t===Yr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Yr.bitbucket?e?.bitbucket?.apiToken?{user:Dt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function ld(t,e){let r=e.sleep??(s=>new Promise(i=>setTimeout(i,s))),n=e.initialDelayMs??5e3,o=e.maxDelayMs??6e4;for(;;)try{return await t()}catch(s){if(!(s instanceof Co))throw s;e.log.warn(`[ctx] ${s.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 Eo(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,s;try{s=await J(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new Co(c)}let i=s.contextRepo;if(!i)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=ew(Zt(i.cloneUrl),r);if(a){let c=await tw({ctx:i,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await rw({ctx:i,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 tw(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,s=Zy(e.cloneUrl,n.secret,n.user),i=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(id(`${r}/.git`)){let l=fr(r);await l.remote(["set-url","origin",s]),await l.fetch("origin",i),await l.checkout(i);let d=ks(r);await l.reset(["--hard",`origin/${i}`]),$s(r,d),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${i}`)}else ad(cd(r),{recursive:!0}),await fr().clone(s,r,["--branch",i]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${i} \u2192 ${r}`);await ud(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 rw(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,s=`${r}.deploy-key`,i=sd(s,n),a=od(e.cloneUrl),c=e.branch;try{if(id(`${r}/.git`)){let l=fr(r);await l.addConfig("core.sshCommand",i,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let d=ks(r);await l.reset(["--hard",`origin/${c}`]),$s(r,d),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ad(cd(r),{recursive:!0}),await fr().env({...process.env,GIT_SSH_COMMAND:i}).clone(a,r,["--branch",c]),await fr(r).addConfig("core.sshCommand",i,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await ud(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 ud(t){let e=fr(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 Co,ii=I(()=>{"use strict";q();me();st();si();Co=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as nw}from"node:child_process";function ow(){try{return nw("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function pd(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:ow(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var fd=I(()=>{"use strict"});import{homedir as mr}from"node:os";import{mkdirSync as sw,readFileSync as md,writeFileSync as iw,existsSync as ci}from"node:fs";import{dirname as aw,join as St}from"node:path";function cw(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Fe(t){let e=K("SANDBOX_CONFIG");if(e)return e;let r=St(mr(),".codepipe","worker");return t?St(r,"profiles",t,"config.json"):St(r,"config.json")}function gd(){return St(mr(),".devpipe-sandbox","config.json")}function Po(){Lt(St(mr(),".devpipe"),St(mr(),".codepipe")),K("SANDBOX_CONFIG")||Lt(St(mr(),".devpipe-sandbox"),St(mr(),".codepipe-sandbox"))}function he(t){let e=Fe(t),r=null;return ci(e)?r=JSON.parse(md(e,"utf-8")):!t&&!K("SANDBOX_CONFIG")&&ci(gd())&&(r=JSON.parse(md(gd(),"utf-8"))),r?(r.planningLane=cw(),r):null}function hd(t,e){let r=Fe(e);sw(aw(r),{recursive:!0}),iw(r,JSON.stringify(t,null,2)+`
|
|
679
|
+
`,{mode:384})}var jo=I(()=>{"use strict";Oe();Gn();ci(".env")&&process.loadEnvFile(".env")});import lw from"ws";var gr,li=I(()=>{"use strict";gr=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 s=await fetch(`${this.hubUrl}/jobs/release`,o);if(!s.ok&&s.status!==409&&s.status!==404)throw new Error(`release failed: ${s.status} ${await s.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 lw(e)}}});import{hostname as uw}from"node:os";async function Ht(t){Po();let e=he(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Fe(t.profile)}.`),process.exit(1));let r=t.name??uw(),n=pd({projects:t.projects??[],llm:t.llm??null}),o=new gr(t.hub.replace(/\/$/,"")),s=po(),i=be(s.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:s.publicKey});hd({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:s.publicKey,sealPrivateKey:s.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Fe(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${i}`),console.log("")}var yd=I(()=>{"use strict";Ee();fd();jo();li()});import{spawn as dw}from"node:child_process";function ui(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function fw(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 mw(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 di(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
|
|
680
|
+
`}async function $d(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new ct;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{}},s=[],i=null,a=c=>{let l=Date.now(),d=c.type;if(d==="assistant"){let f=c.message;for(let u of f?.content??[]){let m=u.type;if(m==="text"){let p=String(u.text??"").trim();p&&o({ts:l,kind:"text",author:"agent",text:ui(p,wd)})}else if(m==="tool_use"){let p=String(u.name??""),h=u.input?.file_path??u.input?.path,y=fw(h,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:p,...y?{file:y}:{}})}}return}if(d==="user"){let f=c.message;for(let u of f?.content??[])if(u.type==="tool_result"){let m=u.is_error===!0,p=m?ui(mw(u.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:m,...p?{text:p}:{}})}return}if(d==="result"){i=c;let f=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...f?{text:f}:{}});return}if(d==="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 d=dw(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});d.stdout.setEncoding("utf-8"),d.stderr.setEncoding("utf-8");let f=!1,u=!1,m=null,p=()=>{f=!0,d.kill("SIGTERM"),m=setTimeout(()=>d.kill("SIGKILL"),bd)};e.signal?.addEventListener("abort",p,{once:!0});let h=null,y=()=>{h&&clearTimeout(h),h=setTimeout(()=>{u=!0,console.warn(`[claude:chat] idle for ${kd}ms \u2014 ending session`),d.kill("SIGTERM"),m=setTimeout(()=>d.kill("SIGKILL"),bd)},kd)},k=()=>{m&&clearTimeout(m),h&&clearTimeout(h),e.signal?.removeEventListener("abort",p)},w=!0,b=x=>{if(!(!w||d.stdin.destroyed))try{d.stdin.write(x)}catch{}};b(di(e.prompt)),y(),(async()=>{try{for await(let x of e.interactive.inbox){if(f||!w)break;if(y(),x.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:ui(x.text,wd)}),b(di(x.text));else{b(di(pw)),w=!1;try{d.stdin.end()}catch{}break}}}catch{}})();let T="",L=x=>{let A;try{A=JSON.parse(x)}catch{return}a(A)};d.stdout.on("data",x=>{s.push(x),y(),T+=x;let A;for(;(A=T.indexOf(`
|
|
681
|
+
`))!==-1;){let O=T.slice(0,A).trim();T=T.slice(A+1),O&&L(O)}}),d.stderr.on("data",x=>{s.push(x);for(let A of x.split(`
|
|
682
|
+
`)){let O=A.trim();O&&console.warn(`[claude:chat:stderr] ${O}`)}}),d.on("error",x=>{k(),l(x)}),d.on("close",x=>{if(k(),f){l(new ct);return}if(u){l(new Error("chat session ended: idle for too long without a reply"));return}T.trim()&&L(T.trim()),console.log(`[claude:chat] exit code=${x}`),c({artifactPaths:[],log:s.join(""),usage:gw(i)})})})}function gw(t){let e=_t();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 wd,bd,kd,pw,vd=I(()=>{"use strict";q();hr();wd=16e3,bd=5e3,kd=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),pw="\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 hw}from"node:child_process";import{existsSync as yw}from"node:fs";function bw(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function xd(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 s=o.type;if(s==="text"){let i=String(o.text??"").trim();i&&console.log(`[claude] text: ${Rt(i,200)}`)}else if(s==="tool_use"){let i=String(o.name??""),a=o.input,c=vw(i,a);console.log(`[claude] tool_use ${i}${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 s=Rd(o.content);console.log(`[claude] tool_result (error)${s?`: ${Rt(s,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,s=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${s}`),e}return console.log(`[claude] ${String(r)} ${Rt(JSON.stringify(e),200)}`),e}function kw(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():"",s=e.api_error_status,i=e.subtype;o?n.push(Rt(o,500)):typeof i=="string"&&i!=="success"&&n.push(i),typeof s=="number"&&n.push(`(api_status=${s})`)}return n.length===1&&r.trim()&&n.push(Rt(r.trim().split(`
|
|
549
683
|
`).slice(-5).join(`
|
|
550
|
-
`),500)),n.join(" \u2014 ")}function
|
|
551
|
-
`))!==-1;){let
|
|
552
|
-
`)){let
|
|
684
|
+
`),500)),n.join(" \u2014 ")}function $w(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 Rd(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function vw(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=${Rt(r,80)}`}return""}function Rt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function ke(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function xw(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=ke(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:ke(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 Sw(t,e,r,n){let o=_t(),s=t&&typeof t.usage=="object"?t.usage:null;s?(o.inputTokens=ke(s.input_tokens),o.outputTokens=ke(s.output_tokens),o.cacheReadInputTokens=ke(s.cache_read_input_tokens),o.cacheCreationInputTokens=ke(s.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=ke(t?.total_cost_usd),o.numTurns=t&&ke(t.num_turns)>0?ke(t.num_turns):r,o.durationMs=ke(t?.duration_ms);let i=typeof t?.model=="string"?t.model:"";return o.model=i||n,o}function Rw(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,s=[];for(let i of o?.content??[]){let a=i.type;if(a==="text"){let c=String(i.text??"").trim();c&&s.push({ts:r,kind:"text",text:Rt(c,Sd)})}else if(a==="tool_use"){let c=String(i.name??""),l=i.input,d=l?.file_path??l?.path??l?.notebook_path,f=Iw(d,e);s.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return s}if(n==="user"){let o=t.message,s=[];for(let i of o?.content??[])if(i.type==="tool_result"){let a=i.is_error===!0,c=a?Rt(Rd(i.content),Sd):"";s.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return s}if(n==="result"){let o=String(t.subtype??"").trim(),s=typeof t.num_turns=="number"?t.num_turns:void 0,i=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...o?{text:o}:{},...s!==void 0?{turns:s}:{},...i!==void 0?{costUsd:i}:{}}]}return[]}function Iw(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 yr,ct,ww,gn,Sd,hr=I(()=>{"use strict";q();vd();yr=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},ct=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},ww=5e3;gn=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return $d(this.binary,e);if(e.signal?.aborted)throw new ct;let r=["-p",bw(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 p of e.addDirs??[])r.push("--add-dir",p);let n=[],o=[],s=null,i={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,d=p=>{if(p){if(p.type==="result"){s=p;return}if(p.type==="rate_limit_event"){let h=xw(p.rate_limit_info);h&&(!l||h.utilization>l.utilization)&&(l=h);return}if(p.type==="assistant"){let h=p.message;typeof h?.model=="string"&&(c=h.model);let y=h?.usage;y&&(a+=1,i.input+=ke(y.input_tokens),i.output+=ke(y.output_tokens),i.cacheRead+=ke(y.cache_read_input_tokens),i.cacheCreate+=ke(y.cache_creation_input_tokens))}}},f=e.role,u=e.onActivity,m=p=>{if(u)for(let h of Rw(p,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((p,h)=>{let y=hw(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 k=!1,w=null,b=()=>{k=!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")},ww)};e.signal?.addEventListener("abort",b,{once:!0});let T=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",b)},L="";y.stdout.on("data",x=>{n.push(x),L+=x;let A;for(;(A=L.indexOf(`
|
|
685
|
+
`))!==-1;){let O=L.slice(0,A).trim();if(L=L.slice(A+1),O){let P=xd(O);d(P),P&&m(P)}}}),y.stderr.on("data",x=>{n.push(x),o.push(x);for(let A of x.split(`
|
|
686
|
+
`)){let O=A.trim();O&&console.warn(`[claude:stderr] ${O}`)}}),y.on("error",x=>{T(),h(x)}),y.on("close",x=>{if(T(),k){h(new ct);return}if(L.trim()){let O=xd(L.trim());d(O),O&&m(O)}let A=s?.is_error===!0;if(x!==0||A){let O=typeof s?.api_error_status=="number"?s.api_error_status:void 0,P=typeof s?.subtype=="string"?s.subtype:void 0,g=typeof s?.result=="string"?s.result:void 0;h(new yr(kw(x,s,o.join("")),{code:x,apiErrorStatus:O,subtype:P,resultText:g,retryAfterMs:$w(s)}));return}console.log("[claude] exit code=0"),p({artifactPaths:[],log:n.join(""),usage:Sw(s,i,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&yw(n))}};Sd=200});import{mkdirSync as Tw,writeFileSync as wr}from"node:fs";import{dirname as Cw,join as br}from"node:path";function Id(t,e,r){let n=br(t,e);Tw(Cw(n),{recursive:!0}),wr(n,r)}function Ew(t,e,r){return`# ${t} \u2014 Estimate
|
|
553
687
|
|
|
554
688
|
**Title:** ${e}
|
|
555
689
|
|
|
@@ -570,7 +704,7 @@ production-grade estimates.)
|
|
|
570
704
|
${r.split(`
|
|
571
705
|
`).slice(0,8).join(`
|
|
572
706
|
`).trim()||"(empty)"}
|
|
573
|
-
`}function
|
|
707
|
+
`}function Pw(t,e,r,n){let o=n?`
|
|
574
708
|
## Reviewer rework instruction
|
|
575
709
|
|
|
576
710
|
> ${n.split(`
|
|
@@ -599,10 +733,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
599
733
|
${r.split(`
|
|
600
734
|
`).slice(0,8).join(`
|
|
601
735
|
`).trim()||"(empty)"}
|
|
602
|
-
`}function
|
|
736
|
+
`}function jw(t){return`# ${t} \u2014 Open questions
|
|
603
737
|
|
|
604
738
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
605
|
-
`}function
|
|
739
|
+
`}function Aw(t,e,r){let n=r?` (rework: ${r.split(`
|
|
606
740
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
607
741
|
index 0000000..1111111 100644
|
|
608
742
|
--- a/CHANGELOG.md
|
|
@@ -613,7 +747,7 @@ index 0000000..1111111 100644
|
|
|
613
747
|
+- mock-runner placeholder change for slice 5 testing.
|
|
614
748
|
+
|
|
615
749
|
# Changelog
|
|
616
|
-
`}function
|
|
750
|
+
`}function _w(t,e,r){return`# ${t} \u2014 Diff summary
|
|
617
751
|
|
|
618
752
|
**Title:** ${e}
|
|
619
753
|
${r?`
|
|
@@ -624,140 +758,147 @@ ${r?`
|
|
|
624
758
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
625
759
|
|
|
626
760
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
627
|
-
`}var
|
|
628
|
-
`),
|
|
761
|
+
`}var hn,pi=I(()=>{"use strict";q();hr();hn=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)",s=r.taskDescription??"",i=[];if(e.role==="estimate"){let a=Ew(n,o,s);wr(br(e.workspaceDir,"ESTIMATE.md"),a),i.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;wr(br(e.workspaceDir,"SOLUTION.md"),Pw(n,o,s,a)),i.push("SOLUTION.md"),wr(br(e.workspaceDir,"QUESTIONS.md"),jw(n)),i.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Id(e.workspaceDir,"changes/sample.patch",Aw(n,o,a)),i.push("changes/sample.patch"),Id(e.workspaceDir,"diff-summary.md",_w(n,o,a)),i.push("diff-summary.md")}else e.role==="rework"&&(wr(br(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
762
|
+
`),i.push("NOTE.md"));return{artifactPaths:i,log:`mock runner produced ${i.length} artifact(s) for role=${e.role}`,usage:_t()}}async runInteractive(e){let r=e.onActivity,n=s=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:s}),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 s of e.interactive.inbox){if(e.signal?.aborted)throw new ct;if(s.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:s.text}),s.text.trim()&&(o=s.text.trim().slice(0,80)),n(`\u041F\u043E\u043D\u044F\u043B: **${s.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 wr(br(e.workspaceDir,"DRAFT.md"),`${o}
|
|
629
763
|
|
|
630
764
|
\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:
|
|
765
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:_t()}}}});function Td(t){switch(t){case"mock":return new hn;case"claude-headless":return new gn;default:return null}}var Cd=I(()=>{"use strict";hr();pi();hr();pi()});function jd(t=process.env){return{maxAttempts:Ao(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Ao(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Ao(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Ao(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function Lw(t){if(t instanceof yr){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:s}=t.details,i=o??"";return Ow.test(i)?{retryable:!1,reason:"out_of_credits"}:n&&Dw.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:s}:Nw.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Ed.test(i)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:n??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return Ed.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Ad(t){if(t instanceof yr){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Pd.test(n)}let e=t instanceof Error?t.message:String(t);return Pd.test(e)}function Uw(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 _d(t,e,r){let n=r.sleep??(i=>new Promise(a=>setTimeout(a,i))),o=Date.now()+r.policy.totalBudgetMs,s="";for(let i=1;;i++)try{return await t.run(e)}catch(a){s=a instanceof Error?a.message:String(a);let c=Lw(a),l=i>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw i>1?new Error(`agent failed after ${i} attempts: ${s}`):a;let d=Uw(i,r.policy,c.retryAfterMs);if(Date.now()+d>o)throw new Error(`agent failed after ${i} attempts (retry budget exhausted): ${s}`);console.warn(`[job] ${r.jobId} agent attempt ${i}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${d}ms`),await r.onBeforeRetry(),await n(d)}}function Ao(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var Nw,Ed,Ow,Dw,Pd,Nd=I(()=>{"use strict";hr();Nw=new Set([429,500,502,503,529]),Ed=/(\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,Ow=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,Dw=new Set(["error_max_turns"]);Pd=/(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 Bw,rmSync as Mw,writeFileSync as Od}from"node:fs";import{tmpdir as Fw}from"node:os";import{join as fi}from"node:path";function _o(t){return`[url "https://${t}/"]
|
|
632
766
|
insteadOf = git@${t}:
|
|
633
767
|
insteadOf = ssh://git@${t}/
|
|
634
|
-
`}function
|
|
768
|
+
`}function Dd(t,e){if(t.length===0)return null;let r=Bw(fi(Fw(),"devpipe-gitcreds-")),n=fi(r,"credentials"),o=fi(r,"gitconfig");return Od(n,t.join(`
|
|
635
769
|
`)+`
|
|
636
|
-
`,{mode:384}),
|
|
770
|
+
`,{mode:384}),Od(o,`[credential]
|
|
637
771
|
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(
|
|
640
|
-
`).map(l=>l.trim()).filter(l=>l.length>0),c=await
|
|
641
|
-
${
|
|
642
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
643
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),
|
|
644
|
-
`+e.subarray(e.length-
|
|
645
|
-
\u2026 [${r.length-e} bytes elided]`}var
|
|
772
|
+
`+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{Mw(r,{recursive:!0,force:!0})}catch{}}}}function mi(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Gw)),t.bitbucket?.apiToken&&(e.push(`https://${Dt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Hw)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Kw)),Dd(e,r)}function Ld(t,e){if(t.contextWrite?.token){let r=Zt(e)??"github.com",n=Fn(r);return Dd([`https://${n}:${t.contextWrite.token}@${r}`],[_o(r)])}return mi(t)}var Gw,Hw,Kw,Ud=I(()=>{"use strict";q();Gw=_o("github.com"),Hw=_o("bitbucket.org"),Kw=_o("gitlab.com")});import{spawn as Md}from"node:child_process";import{existsSync as No,mkdirSync as yn,readFileSync as Ww,rmSync as gi,symlinkSync as qw}from"node:fs";import{homedir as Yw}from"node:os";import{dirname as $r,join as Wt}from"node:path";function Fd(){return Wt(Yw(),".codepipe-sandbox","repos")}function Gd(t,e){let n=(kr.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{kr.get(t)===o&&kr.delete(t)},()=>{kr.get(t)===o&&kr.delete(t)});return kr.set(t,o),n}function Bd(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 Vw(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 Hd(t,e,r,n,o){let s=async c=>{await z(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await z(t,["reset","--hard",`origin/${c}`],o),await z(t,["clean","-fdx"],o)},i=async()=>{try{return await s(r),r}catch(c){if(!n||n===r||!Bd(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await s(n),n}},a=async()=>{No(t)&&gi(t,{recursive:!0,force:!0}),yn($r(t),{recursive:!0});try{return await z(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Bd(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),No(t)&&gi(t,{recursive:!0,force:!0}),yn($r(t),{recursive:!0}),await z(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(No(Wt(t,".git")))try{return await i()}catch(c){if(!Vw(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 Kd(t){await z(t.workspacePath,["reset","--hard",t.baseSha]),await z(t.workspacePath,["clean","-fdx"])}async function Wd(t,e){let r=t.workspacePath;await z(r,["add","-A"]);let n=(await ge(r,["write-tree"])).trim(),o=(await ge(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let s={...process.env,GIT_AUTHOR_NAME:vr,GIT_AUTHOR_EMAIL:xr,GIT_COMMITTER_NAME:vr,GIT_COMMITTER_EMAIL:xr};return(await ge(r,["commit-tree",n,"-m",e],s)).trim()}async function qd(t,e,r,n,o){try{await z(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(s){let i=s instanceof Error?s.message:String(s);throw Zt(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(i)?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"+i):s}}async function Yd(t,e){return ge(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Vd(t,e,r,n,o){await z(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await z(t.workspacePath,["checkout","--force",r])}async function Jd(t,e,r,n,o,s){let i=t.workspacePath;await z(i,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],s);let a=(await ge(i,["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=p=>ge(i,["rev-parse","-q","--verify",`${p}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await ge(i,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await z(i,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],s).catch(h=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(h)}`)}),await c(n)||await z(i,["fetch","origin",n],s).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={...s??process.env,GIT_AUTHOR_NAME:vr,GIT_AUTHOR_EMAIL:xr,GIT_COMMITTER_NAME:vr,GIT_COMMITTER_EMAIL:xr},d=(await ge(i,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),f=(await ge(i,["commit-tree",d,"-p",n,"-m","delivery"],l)).trim();await z(i,["cherry-pick","--quit"],l).catch(()=>{});let u=null;try{await z(i,["cherry-pick","--no-commit",f],l)}catch(p){u=p instanceof Error?p.message:String(p)}let m=(await ge(i,["diff","--name-only","--diff-filter=U"])).split(`
|
|
773
|
+
`).map(p=>p.trim()).filter(p=>p.length>0);if(u&&m.length===0)throw await z(i,["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 hi(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:vr,GIT_AUTHOR_EMAIL:xr,GIT_COMMITTER_NAME:vr,GIT_COMMITTER_EMAIL:xr};(await ge(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await z(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await z(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let i=null;try{await z(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){i=l instanceof Error?l.message:String(l)}let a=(await ge(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
774
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await ge(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(i&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${i}`);return a}function z(t,e,r){return new Promise((n,o)=>{let s=Md("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),i=[];s.stderr.setEncoding("utf-8"),s.stderr.on("data",a=>i.push(a)),s.on("error",o),s.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
|
|
775
|
+
${i.join("").trim()||"(no stderr)"}`))})})}function ge(t,e,r){return new Promise((n,o)=>{let s=Md("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),i=[],a=[];s.stdout.setEncoding("utf-8"),s.stderr.setEncoding("utf-8"),s.stdout.on("data",c=>i.push(c)),s.stderr.on("data",c=>a.push(c)),s.on("error",o),s.on("close",c=>{if(c===0)return n(i.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
|
|
776
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function zd(t,e){No(t)&&gi(t,{recursive:!0,force:!0}),yn($r(t),{recursive:!0}),qw(e,t,"dir")}async function Xd(t,e,r){await z(t,["worktree","prune"]).catch(()=>{}),yn($r(r),{recursive:!0}),await z(t,["worktree","add","--detach",r,`origin/${e}`])}async function Jw(t,e,r){yn($r(r),{recursive:!0}),await z($r(r),["clone","--quiet","--no-checkout",t,r]),await z(r,["checkout","--force","--detach",e])}async function Qd(t,e,r,n="worktree",o){return r.length===0?[]:Gd(e,async()=>{let s=[];for(let i of r){let a=Wt(Fd(),e,i.name);console.log(`[git] code: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${a}`);let c;try{c=await Hd(a,i.cloneUrl,i.ref,i.defaultBranch,o)}catch(f){throw new Error(`failed to materialize project repo "${i.name}" (${i.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await ge(a,["rev-parse","HEAD"])).trim(),d=Wt(t,"code",i.name);n==="direct"?(zd(d,a),console.log(`[git] code: linked ${d} \u2192 ${a} @ ${l.slice(0,10)}`)):n==="clone"?(await Jw(a,l,d),console.log(`[git] code: clone ${d} \u2190 ${a} @ ${l.slice(0,10)}`)):(await Xd(a,c,d),console.log(`[git] code: worktree ${d} \u2190 ${a} @ ${l.slice(0,10)}`)),s.push({name:i.name,workspacePath:d,cachePath:a,ref:c,baseSha:l})}return s})}async function Zd(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let s=r;return Gd(e,async()=>{let i=Wt(Fd(),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${i}`);try{await Hd(i,s.cloneUrl,s.ref,void 0,o)}catch(l){throw new Error(`failed to materialize context repo (${s.cloneUrl}): `+(l instanceof Error?l.message:String(l)))}let a=Wt(t,"context");n==="direct"?(zd(a,i),console.log(`[git] context: linked ${a} \u2192 ${i}`)):(await Xd(i,s.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${i}`));let c=(await ge(i,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:i,baseSha:c}})}async function ep(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await z(r,["add","-A",...n]).catch(()=>{});let o;try{o=await ge(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let s=o.split(`
|
|
777
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),i=[];for(let a of s)try{let c=Ww(Wt(r,a)).toString("base64");i.push({path:a,contentBase64:c})}catch{}return i}var kr,vr,xr,tp=I(()=>{"use strict";q();kr=new Map;vr="CodePipe Agent",xr="codepipe@codepartner.ee"});import{readFileSync as zw}from"node:fs";import{join as Xw}from"node:path";function rp(t){let e=Xw(t,wn),r;try{r=zw(e,"utf-8")}catch{throw new It(`BUILD produced no ${wn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(d){throw new It(`${wn} is not valid JSON: ${d instanceof Error?d.message:String(d)}`)}if(!n||typeof n!="object")throw new It(`${wn} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new It(`${wn}: "ok" must be a boolean`);let s=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(d=>{if(!d||typeof d!="object")return[];let f=d,u=typeof f.name=="string"?f.name:null,m=typeof f.exitCode=="number"?f.exitCode:null;if(u===null||m===null)return[];let p={name:u,exitCode:m};return typeof f.durationMs=="number"&&(p.durationMs=f.durationMs),[p]}),c=typeof o.logTail=="string"?Qw(o.logTail):"",l={ok:s,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!s){let d=a.find(f=>f.exitCode!==0);d&&(l.failedStep=d.name)}return l}function Qw(t){let e=Buffer.from(t,"utf-8");return e.length<=yi?t:`\u2026 [${e.length-yi} bytes elided] \u2026
|
|
778
|
+
`+e.subarray(e.length-yi).toString("utf-8")}var yi,It,wn,np=I(()=>{"use strict";yi=8*1024,It=class extends Error{},wn="meta/build-result.json"});import{readFileSync as Zw}from"node:fs";import{join as eb}from"node:path";function sp(t){let e=eb(t,Sr),r;try{r=Zw(e,"utf-8")}catch{throw new lt(`code review produced no ${Sr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new lt(`${Sr} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new lt(`${Sr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new lt(`${Sr}: "approved" must be a boolean`);let s=o.approved,i=typeof o.remarks=="string"?op(o.remarks,tb):"";if(!s&&i.trim().length===0)throw new lt(`${Sr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?op(o.summary,rb):"";return{approved:s,remarks:i,summary:a}}function op(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
|
|
779
|
+
\u2026 [${r.length-e} bytes elided]`}var tb,rb,lt,Sr,ip=I(()=>{"use strict";tb=16*1024,rb=4*1024,lt=class extends Error{},Sr="meta/review-result.json"});import{readFileSync as nb,statSync as ob}from"node:fs";import{join as ap}from"node:path";function db(t){return t.startsWith("meta/")||ub.has(t)}function pb(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 fb(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function cp(t,e,r){let n=r?.maxBytes??sb,o=r?.totalBytes??ib,s=r?.maxCount??ab,i=e.map((p,h)=>{let y=null;try{y=ob(ap(t,p)).size}catch{}return{path:p,index:h,size:y}}),a=[...i].sort((p,h)=>{let y=k=>db(k.path)?0:1;return y(p)!==y(h)?y(p)-y(h):(p.size??0)-(h.size??0)}),c=a.slice(0,s),l=a.slice(s).sort((p,h)=>p.index-h.index).map(p=>p.path),d=new Array(i.length),f=[],u=0;for(let p of c){let h=null;if(p.size!==null&&p.size<=n&&u+p.size<=o)try{h=nb(ap(t,p.path))}catch{}if(h!==null){u+=h.length,d[p.index]={path:p.path,contentBase64:h.toString("base64")};continue}let y=p.size===null?fb(p.path):pb(p.path,p.size,n,o),k=Buffer.from(y,"utf-8");u+=k.length,d[p.index]={path:p.path,contentBase64:k.toString("base64")},f.push({path:p.path,bytes:p.size??0})}let m=d.filter(p=>p!==void 0);if(l.length>0){let p=l.slice(0,lb),h=`# Artifacts omitted from upload
|
|
646
780
|
|
|
647
|
-
${l.length} file(s) exceeded the SANDBOX artifact count budget (${
|
|
781
|
+
${l.length} file(s) exceeded the SANDBOX artifact count budget (${s}) 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
782
|
|
|
649
|
-
`+
|
|
650
|
-
`).join("")+(l.length>
|
|
651
|
-
\u2026and ${l.length-
|
|
652
|
-
`:"");m.push({path
|
|
783
|
+
`+p.map(y=>`- ${y}
|
|
784
|
+
`).join("")+(l.length>p.length?`
|
|
785
|
+
\u2026and ${l.length-p.length} more.
|
|
786
|
+
`:"");m.push({path:cb,contentBase64:Buffer.from(h,"utf-8").toString("base64")})}return{artifacts:m,omitted:f,dropped:l}}var sb,ib,ab,cb,lb,ub,lp=I(()=>{"use strict";sb=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),ib=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),ab=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),cb="artifacts-omitted.md",lb=500,ub=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 mb,mkdtempSync as gb,readFileSync as hb,readdirSync as dp,rmSync as up}from"node:fs";import{tmpdir as yb}from"node:os";import{join as Oo,relative as wb}from"node:path";function pp(t){let e=gb(Oo(yb(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>up(e,{recursive:!0,force:!0}),listFiles:()=>fp(e,e),readFile:r=>hb(Oo(e,r),"utf-8"),clean:()=>{for(let r of dp(e))kb.has(r)||up(Oo(e,r),{recursive:!0,force:!0})}}}function fp(t,e){let r=[];for(let n of dp(e)){let o=Oo(e,n),s=mb(o);if(!s.isSymbolicLink())if(s.isDirectory()){if(e===t&&bb.has(n))continue;r.push(...fp(t,o))}else r.push(wb(t,o))}return r}var bb,kb,mp=I(()=>{"use strict";bb=new Set(["code","context","scratch"]),kb=new Set(["code","context"])});import{mkdirSync as $b,readFileSync as gp,readdirSync as vb,writeFileSync as xb}from"node:fs";import{homedir as Sb}from"node:os";import{dirname as Rb,join as Rr}from"node:path";function Tb(t){let e=Buffer.from(t,"utf-8");if(e.length<=Do)return t;let r=Math.floor(Do/4),n=Do-r,o=e.subarray(0,r).toString("utf-8"),s=e.subarray(e.length-n).toString("utf-8"),i=e.length-r-n;return`${o}
|
|
653
787
|
|
|
654
|
-
\u2026 [${
|
|
788
|
+
\u2026 [${i} bytes elided \u2014 log capped at ${Do} bytes for upload] \u2026
|
|
655
789
|
|
|
656
|
-
${
|
|
790
|
+
${s}`}function Cb(){let t=[],e=!1,r=null,n=s=>{if(r){let i=r;r=null,i({value:s,done:!1})}else t.push(s)},o=()=>{if(r){let s=r;r=null,s({value:void 0,done:!0})}};return{push(s){e||n(s)},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(s=>{r=s})}}}}}}async function bn(t={}){Po();let e=he(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=t.profile?`sandbox-${t.profile}`:"sandbox",o=Rr(Sb(),".codepipe","logs"),s=Jn("SANDBOX_LOG",n,o);if(s.enabled){let P=new nr(s);zn(P),console.log(`[log] file logging \u2192 ${P.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe-sandbox v${Re} (protocol ${Ke})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let i=Td(e.llm);console.log(`llm backend: ${i?i.name():"(none \u2014 will not claim agent jobs)"}`);let a=jd();console.log(`llm retry: maxAttempts=${a.maxAttempts} backoff=${a.baseDelayMs}\u2013${a.maxDelayMs}ms budget=${a.totalBudgetMs}ms`);let c=new gr(e.hubUrl,e.token),l=!1,d=new AbortController,f=new Map,u=null,m=null,p=!1,h=()=>{let P=c.openControlSocket();return u=P,P.on("open",()=>{console.log("[ws] connected");let g={type:"sandbox_hello",platformVersion:Re,protocolVersion:Ke};P.send(JSON.stringify(g))}),P.on("message",g=>{let N=g.toString("utf-8"),$=null;try{let E=JSON.parse(N);E&&typeof E=="object"&&($=E)}catch{}if($&&$.type==="hello"){let E=$;m=Nn(E.protocolVersion);let S=m?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${E.platformVersion} (protocol ${E.protocolVersion}) \u2014 ${S}`),m&&(p=!1);return}if($&&$.type==="pause_job"){let E=typeof $.jobId=="string"?$.jobId:"",S=E?f.get(E):void 0;S?(console.warn(`[ws] pause_job ${E} \u2014 aborting agent`),S.paused=!0,S.abort.abort()):console.log(`[ws] pause_job ${E} \u2014 not a running job, ignoring`),E&&P.send(JSON.stringify({type:"job_paused",jobId:E}));return}if($&&($.type==="chat_user_message"||$.type==="chat_finalize")){let E=typeof $.jobId=="string"?$.jobId:"",S=E?f.get(E):void 0;if(S?.chatInbox)if($.type==="chat_user_message"){let j=typeof $.text=="string"?$.text:"";j.trim()&&S.chatInbox.push({kind:"user",text:j})}else S.chatInbox.finalize();else console.log(`[ws] ${String($.type)} ${E} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${N}`)}),P.on("close",(g,N)=>{console.log(`[ws] closed code=${g} reason=${N?.toString()||""}`),u===P&&(u=null),!l&&setTimeout(h,2e3)}),P.on("error",g=>console.warn(`[ws] error: ${g.message}`)),P},y=h(),k=async P=>{for(;!l;){if(m===!1){p||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Re}, protocol ${Ke}) \u2014 not claiming jobs until versions align.`),p=!0),await new Promise(g=>setTimeout(g,5e3));continue}try{let g=await c.claim(d.signal,P);if(g.status===204)continue;if(g.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,l=!0;break}if(!g.ok){console.warn(`[claim:${P}] ${g.status} \u2014 backoff 5s`),await new Promise($=>setTimeout($,5e3));continue}let N=await g.json();await w(c,N)}catch(g){if(d.signal.aborted)break;let N=g instanceof Error?g.message:String(g);console.warn(`[claim:${P}] error: ${N} \u2014 backoff 5s`),await new Promise($=>setTimeout($,5e3))}}};async function w(P,g){let N={abort:new AbortController,paused:!1};g.role==="chat"&&(N.chatInbox=Cb()),f.set(g.jobId,N);let $=!1,E=null,S=null,j=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),F=async()=>{try{await P.heartbeat(g.jobId)==="claim_lost"&&($=!0,console.warn(`[job] ${g.jobId} claim lost \u2014 HUB sweeper took it`))}catch(B){let _e=B instanceof Error?B.message:String(B);console.warn(`[job] ${g.jobId} heartbeat error: ${_e}`)}};F();let v=setInterval(()=>{F()},j),R=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(T(g.prompt," \u2502 "));let H=[],te=null,jn=400,Vo=25,_=500,le=()=>{if(te&&(clearTimeout(te),te=null),H.length===0)return;let B=H.splice(0,H.length),_e=u;if(!_e||_e.readyState!==_e.OPEN)return;let et={type:"agent_activity",jobId:g.jobId,taskId:g.taskId,projectId:g.projectId,role:g.role,phase:g.phase,events:B};try{_e.send(JSON.stringify(et))}catch{}},Ae=B=>{H.push(B),H.length>_&&H.shift(),H.length>=Vo?le():te||(te=setTimeout(le,jn))},Ge=g.role==="analysis"&&g.taskId.startsWith("draft::")?g.taskId.slice(7):null,dt=new Set,pt=null;try{if(!i){$||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:R,finishedAt:new Date().toISOString()});return}let B=pp(g.jobId);console.log(`[job] ${g.jobId} workspace=${B.dir}`);let _e=b(g,r);E=_e.gitCreds,S=_e.contextGitCreds;let et=E?.env,Fi=_e.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:_e.claudeOauthToken}:void 0,tt=[],Mr=null,Jo=null;try{let U=g.role==="build"?"clone":"worktree";tt=await Qd(B.dir,g.projectId,g.projectRepos,U,et);let M=await Zd(B.dir,g.projectId,g.contextRepo,"worktree",et);Jo=M,Mr=M?.workspacePath??null}catch(U){let M=U instanceof Error?U.message:String(U);console.warn(`[job] ${g.jobId} materialize failed: ${M}`),$||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${M}`},startedAt:R,finishedAt:new Date().toISOString()}),B.dispose();return}let Gi=async()=>{if(!g.deliveries||g.deliveries.length===0)return[];let U=g.contextRepo?.cloneUrl;if(!U||!et)throw new Error(U?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let M=[];for(let V of g.deliveries){let Y=tt.find(ue=>ue.name===V.name);if(Y){if(g.role==="implement"&&V.baseSha&&V.baseSha!==Y.baseSha){let ue=await Jd(Y,V.deliveryRef,V.deliverySha,V.baseSha,U,et);console.log(`[job] ${g.jobId} ${Y.name}: base moved ${V.baseSha.slice(0,10)} \u2192 ${Y.baseSha.slice(0,10)} \u2014 re-applied delivery ${V.deliverySha.slice(0,10)} (${ue.length} conflicted file(s))`),ue.length>0&&M.push(`- **${Y.name}**:`,...ue.map(Fr=>` - \`${Fr}\``));continue}await Vd(Y,V.deliveryRef,V.deliverySha,U,et),console.log(`[job] ${g.jobId} ${Y.name}: checked out delivery ${V.deliverySha.slice(0,10)} for ${g.role}`)}}return M},zo=[];if(g.role==="build"||g.role==="implement"||g.role==="code-review")try{zo=await Gi()}catch(U){let M=U instanceof Error?U.message:String(U);console.warn(`[job] ${g.jobId} delivery checkout failed: ${M}`),$||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${M}`},startedAt:R,finishedAt:new Date().toISOString()}),B.dispose();return}let Xo=g.role==="resolve-conflict"?g.metadata?.taskBranchByRepo??{}:{},Hi="";if(g.role==="resolve-conflict"){if(!tt.some(U=>Xo[U.name])){let U="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} ${U}`),$||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:U},startedAt:R,finishedAt:new Date().toISOString()}),B.dispose();return}try{let U=[];for(let M of tt){let V=Xo[M.name];if(!V)continue;let Y=await hi(M,V,et);console.log(`[job] ${g.jobId} ${M.name}: merged ${V} into ${M.ref} \u2014 ${Y.length} conflicted file(s)`),Y.length>0?U.push(`- **${M.name}**:`,...Y.map(ue=>` - \`${ue}\``)):U.push(`- **${M.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Hi=`
|
|
657
791
|
|
|
658
792
|
## Conflicts to resolve
|
|
659
793
|
|
|
660
|
-
`+(
|
|
794
|
+
`+(U.length>0?U.join(`
|
|
661
795
|
`):"(no task branches to merge)")+`
|
|
662
|
-
`}catch(
|
|
796
|
+
`}catch(U){let M=U instanceof Error?U.message:String(U);console.warn(`[job] ${g.jobId} conflict merge failed: ${M}`),$||await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${M}`},startedAt:R,finishedAt:new Date().toISOString()}),B.dispose();return}}let Yf=zo.length>0?`
|
|
663
797
|
|
|
664
798
|
## Base branch moved \u2014 conflicts to resolve
|
|
665
799
|
|
|
666
800
|
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
801
|
|
|
668
|
-
`+
|
|
802
|
+
`+zo.join(`
|
|
669
803
|
`)+`
|
|
670
|
-
`:""
|
|
804
|
+
`:"",Vf=x(L(g.prompt,tt,Mr),Mr,g.taskId)+Hi+Yf,Qo=[...tt.map(U=>U.workspacePath),...Mr?[Mr]:[]];Qo.length>0&&console.log(`[job] ${g.jobId} --add-dir: ${Qo.join(", ")}`),Ge&&(pt=setInterval(()=>{let M=u;if(!M||M.readyState!==M.OPEN)return;let V;try{V=vb(Rr(B.dir,"drafts")).filter(Y=>Y.endsWith(".json")).sort()}catch{return}for(let Y of V){if(dt.has(Y))continue;if(dt.size>=qa)break;let ue;try{let Ne=JSON.parse(gp(Rr(B.dir,"drafts",Y),"utf-8")),zt=typeof Ne.localRef=="string"?Ne.localRef:"",An=typeof Ne.title=="string"?Ne.title:"",Zo=typeof Ne.body=="string"?Ne.body:"";if(!zt||!An)continue;ue={localRef:zt,title:An,body:Zo,...Ne.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Ne.links)?{links:Ne.links}:{}}}catch{continue}dt.add(Y);let Fr={type:"child_draft",jobId:g.jobId,projectId:g.projectId,draftId:Ge,child:ue};try{M.send(JSON.stringify(Fr))}catch{}}},1500));try{let U={workspaceDir:B.dir,role:g.role,prompt:Vf,addDirs:Qo,metadata:g.metadata??{},...g.model?{model:g.model}:{},...Fi?{env:Fi}:{},signal:N.abort.signal,onActivity:Ae},M=N.chatInbox?await i.run({...U,interactive:{inbox:N.chatInbox.iterable}}):await _d(i,U,{jobId:g.jobId,policy:a,onBeforeRetry:async()=>{B.clean();for(let Z of tt)try{await Kd(Z);let de=Xo[Z.name];g.role==="resolve-conflict"&&de&&await hi(Z,de,et)}catch(de){let Gr=de instanceof Error?de.message:String(de);console.warn(`[job] ${g.jobId} worktree reset failed (${Z.name}): ${Gr}`)}try{await Gi()}catch(Z){let de=Z instanceof Error?Z.message:String(Z);console.warn(`[job] ${g.jobId} delivery re-checkout failed: ${de}`)}},aborted:()=>$||N.paused}),V=[];if(Ib.has(g.role)&&tt.length>0){let Z=g.metadata??{},de=typeof Z.commitMessage=="string"?Z.commitMessage:`${g.taskId}: changes`,Gr=g.contextRepo?.cloneUrl,Wi=S?.env;if(!Gr||!Wi)throw new Error("delivery requested but "+(Gr?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Jf=g.taskId.includes(":")?g.taskId.slice(g.taskId.indexOf(":")+1):g.taskId;for(let rt of tt){let Hr=await Wd(rt,de);if(!Hr){console.log(`[job] ${g.jobId} ${rt.name}: no changes \u2014 no delivery`);continue}let es=`codepipe/deliveries/${Jf}/${g.jobId}/${rt.name}`;await qd(rt,Hr,es,Gr,Wi),V.push({name:rt.name,deliveryRef:es,deliverySha:Hr,baseSha:rt.baseSha}),console.log(`[job] ${g.jobId} ${rt.name}: delivered ${Hr.slice(0,10)} \u2192 ${es}`);let qi=await Yd(rt,Hr);if(qi.trim().length>0){let zf=Rr("display",`${rt.name}.diff`),Yi=Rr(B.dir,zf);$b(Rb(Yi),{recursive:!0}),xb(Yi,qi)}}}if(g.role==="resolve-conflict"&&V.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let Y;g.role==="build"&&(Y=rp(B.dir),console.log(`[job] ${g.jobId} build verdict: ok=${Y.ok}`+(Y.failedStep?` failedStep=${Y.failedStep}`:"")));let ue;g.role==="code-review"&&(ue=sp(B.dir),console.log(`[job] ${g.jobId} review verdict: approved=${ue.approved}`));let Fr=M.artifactPaths.length>0?M.artifactPaths:B.listFiles(),Ne=Array.from(new Set(Fr)),zt;if(Jo)try{let Z=g.role==="index"?["adr/SOURCES.md"]:g.role==="backfill"?["adr"]:[],de=await ep(Jo,Z);de.length>0&&(zt=de,console.log(`[job] ${g.jobId} captured ${de.length} knowledge file(s) for Context Repo`))}catch(Z){let de=Z instanceof Error?Z.message:String(Z);console.warn(`[job] ${g.jobId} knowledge capture failed (non-fatal): ${de}`)}let{artifacts:An,omitted:Zo,dropped:Ki}=cp(B.dir,Ne);for(let Z of Zo)console.warn(`[job] ${g.jobId} artifact ${Z.path} (${Z.bytes} bytes) exceeded upload budget \u2014 content omitted`);Ki.length>0&&console.warn(`[job] ${g.jobId} artifact listing truncated: ${Ki.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let _n={jobId:g.jobId,status:"succeeded",artifacts:An,...zt?{contextWrites:zt}:{},...V.length>0?{deliveries:V}:{},log:Tb(M.log),startedAt:R,finishedAt:new Date().toISOString(),usage:M.usage,...M.rateLimit?{rateLimit:M.rateLimit}:{},...Y?{build:Y}:{},...ue?{review:ue}:{}};if($||N.paused)console.warn(`[job] ${g.jobId} skipping result upload \u2014 ${N.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await P.submitResult(_n),console.log(`[job] ${g.jobId} done \u2014 uploaded ${_n.artifacts.length} artifact(s):`);for(let Z of _n.artifacts){let de=Buffer.from(Z.contentBase64,"base64").length;console.log(` \xB7 ${Z.path} (${de} bytes)`)}_n.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(U){let M=U instanceof Error?U.message:String(U);if(N.paused)console.log(`[job] ${g.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if($)console.warn(`[job] ${g.jobId} failed after claim lost (${M}) \u2014 skipping result upload`);else{let V=Ad(U),Y=U instanceof It,ue=U instanceof lt;console.warn(V?`[job] ${g.jobId} failed: ${M} (Claude auth \u2014 token invalid/expired)`:Y?`[job] ${g.jobId} failed: ${M} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:ue?`[job] ${g.jobId} failed: ${M} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${g.jobId} failed: ${M}`),await P.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:M},startedAt:R,finishedAt:new Date().toISOString(),...V?{authError:!0}:{},...Y?{buildInconclusive:!0}:{},...ue?{reviewInconclusive:!0}:{}})}}finally{B.dispose()}}finally{clearInterval(v),pt&&clearInterval(pt),le(),N.chatInbox?.close(),f.delete(g.jobId),E?.cleanup(),S?.cleanup()}}function b(P,g){if(!P.credBundle)return{gitCreds:null,contextGitCreds:null};if(!g)return console.warn(`[job] ${P.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let N;try{N=JSON.parse(ur(g,P.credBundle).toString("utf-8"))}catch(j){return console.warn(`[job] ${P.jobId} failed to open credBundle: ${j instanceof Error?j.message:String(j)}`),{gitCreds:null,contextGitCreds:null}}let $=mi(N);$&&console.log(`[job] ${P.jobId} cred bundle opened \u2014 git creds configured`);let E=Ld(N,P.contextRepo.cloneUrl),S={gitCreds:$,contextGitCreds:E};return N.claudeOauthToken&&(S.claudeOauthToken=N.claudeOauthToken),S}function T(P,g){return P.split(`
|
|
671
805
|
`).map(N=>g+N).join(`
|
|
672
|
-
`)}function
|
|
673
|
-
[${P}] shutting down`),p.abort();let g=[...f.keys()];for(let E of f.values())E.abort.abort();let N=new AbortController,$=setTimeout(()=>N.abort(),3e3);(async()=>(await Promise.all(g.map(async E=>{try{await c.releaseJob(E,`sandbox ${P}`,N.signal),console.log(`[${P}] released job ${E}`)}catch(x){let j=x instanceof Error?x.message:String(x);console.warn(`[${P}] release failed: ${j} (sweeper will reclaim)`)}})),clearTimeout($),y.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>_("SIGINT")),process.on("SIGTERM",()=>_("SIGTERM"));let F=[b("implementation")];e.planningLane!==!1?F.push(b("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(F)}var Co,Bw,Hp=R(()=>{"use strict";Y();Ce();oi();tp();ap();xo();pp();Vi();Cp();Pp();_p();Dp();Gp();Co=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Bw=new Set(["implement","resolve-conflict"])});var br=R(()=>{"use strict";Ku();Hp();xo()});async function vr(t,e,r){return e.host==="github"?Hw(t,e,r):e.host==="gitlab"?zw(t,e,r):Qw(t,e,r)}async function Wp(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await It(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await qp(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await Tt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Yp(e.gitlabToken,t):o}}return e.bitbucket?(await $r(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Vp(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 qp(t,e){let r=!1;try{r=(await It(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function Yp(t,e){let r=!1;try{r=(await Tt(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function Vp(t,e){let r=!1;try{r=(await $r(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function It(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(Fw+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 Hw(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 Kw(n,e,r),i=await qw(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=or(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Yw(n,o.owner,o.name,a.path,i)||await Vw(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 Kw(t,e,r){let n=await It(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await qp(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Ww(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await It(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Ww(t,e){let{status:r,data:n}=await It(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function qw(t,e,r){let{data:n}=await It(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Yw(t,e,r,n,o){let{status:i,data:s}=await It(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Vw(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await It(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Tt(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(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?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 Tt(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Yp(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Tt(n,"GET","/user"),u={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let d=await Tt(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(d.status===404||!d.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);u.namespace_id=d.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await Tt(n,"POST","/projects",u);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=or(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let m=(await Tt(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let d of m)l.add(d.path);if(m.length<100)break}let p=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return p.length>0?await Tt(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function $r(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(Xw+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 Qw(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 $r(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 Vp(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 $r(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=f.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=or(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await $r(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 $r(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 Fw,Jw,Xw,Eo=R(()=>{"use strict";Ut();Fw="https://api.github.com";Jw="https://gitlab.com/api/v4";Xw="https://api.bitbucket.org/2.0"});function Pe(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=Zw[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}var Zw,Po=R(()=>{"use strict";Zw={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as ek}from"node:crypto";import{existsSync as Jp,mkdirSync as tk,readFileSync as zp,readdirSync as rk,rmSync as jo,writeFileSync as nk}from"node:fs";import{homedir as ok}from"node:os";import{dirname as ik,join as ns}from"node:path";function Xp(){return ns(ok(),".codepipe","init-drafts")}function os(t){let e=ek("sha256").update(t).digest("hex").slice(0,16);return ns(Xp(),`${e}.json`)}function Qp(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=sk)}function Zp(t){let e=os(t);if(!Jp(e))return null;try{let r=JSON.parse(zp(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Qp(r.savedAt)?(jo(e,{force:!0}),null):r}catch{return null}}function is(t){jo(os(t),{force:!0})}function ed(){let t=Xp();if(Jp(t))for(let e of rk(t)){let r=ns(t,e);try{let n=JSON.parse(zp(r,"utf-8"));Qp(n.savedAt)&&jo(r,{force:!0})}catch{jo(r,{force:!0})}}}var sk,xr,td=R(()=>{"use strict";sk=24*60*60*1e3;xr=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(){is(this.cwd)}persist(){let e=os(this.cwd);tk(ik(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};nk(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`),
|
|
677
|
-
`))w.length>0&&y.write(`${
|
|
678
|
-
`)};m.stdout?.on("data",h(process.stdout)),m.stderr?.on("data",h(process.stderr))},
|
|
679
|
-
[up] ${m} \u2014 stopping both roles`);for(let{child:
|
|
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
|
-
${
|
|
683
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||ee("farm fingerprint not confirmed \u2014 aborting."),
|
|
806
|
+
`)}function L(P,g,N){let $=g[0]?.workspacePath??"";return P.replace(/\{\{codeDir\}\}/g,$).replace(/\{\{codeRoot\}\}/g,$?$.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,N??"")}function x(P,g,N){let $=P,E=N.includes("::")?"":N.split(":",2)[1]??"",S=j=>{if(!g||!E)return"";try{return gp(Rr(g,"tasks",E,j),"utf-8").trim()}catch{return""}};if($.includes("{{solutionMd}}")){let j=S("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";$=$.replace(/\{\{solutionMd\}\}/g,()=>j)}if($.includes("{{taskDescription}}")){let j=S("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";$=$.replace(/\{\{taskDescription\}\}/g,()=>j)}return $}let A=P=>{if(l)return;l=!0,console.log(`
|
|
807
|
+
[${P}] shutting down`),d.abort();let g=[...f.keys()];for(let E of f.values())E.abort.abort();let N=new AbortController,$=setTimeout(()=>N.abort(),3e3);(async()=>(await Promise.all(g.map(async E=>{try{await c.releaseJob(E,`sandbox ${P}`,N.signal),console.log(`[${P}] released job ${E}`)}catch(S){let j=S instanceof Error?S.message:String(S);console.warn(`[${P}] release failed: ${j} (sweeper will reclaim)`)}})),clearTimeout($),y.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>A("SIGINT")),process.on("SIGTERM",()=>A("SIGTERM"));let O=[k("implementation")];e.planningLane!==!1?O.push(k("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(O)}var Do,Ib,hp=I(()=>{"use strict";q();Ee();gs();Cd();Nd();jo();Ud();li();tp();np();ip();lp();mp();Do=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Ib=new Set(["implement","resolve-conflict"])});var Ir=I(()=>{"use strict";yd();hp();jo()});async function Cr(t,e,r){return e.host==="github"?Pb(t,e,r):e.host==="gitlab"?Lb(t,e,r):Bb(t,e,r)}async function wp(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 bp(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 i=encodeURIComponent(`${t.owner}/${t.name}`);return(await Tt(e.gitlabToken,"GET",`/projects/${i}`)).status!==404?{found:!0}:{found:!1,detail:n?await kp(e.gitlabToken,t):o}}return e.bitbucket?(await Tr(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await $p(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(s){return{found:"unknown",detail:s instanceof Error?s.message:String(s)}}}async function bp(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 kp(t,e){let r=!1;try{r=(await Tt(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function $p(t,e){let r=!1;try{r=(await Tr(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 s=await fetch(Eb+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:i;throw new Error(`GitHub ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function Pb(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 jb(n,e,r),s=await _b(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${s}`);let i=cr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of i)await Nb(n,o.owner,o.name,a.path,s)||await Ob(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,s);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:s}}async function jb(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 bp(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Ab(t,e.owner),s=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let i=await Ct(t,"POST",s,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!i.data)throw new Error("GitHub createRepo: empty response");return{owner:i.data.owner.login,name:i.data.name,sshUrl:i.data.ssh_url}}async function Ab(t,e){let{status:r,data:n}=await Ct(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function _b(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 Nb(t,e,r,n,o){let{status:s,data:i}=await Ct(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return s===404||!i?null:i.sha}async function Ob(t,e,r,n,o,s,i,a){let c={message:s,content:Buffer.from(o,"utf-8").toString("base64"),branch:i};a&&(c.sha=a),await Ct(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Tt(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let s=await fetch(Db+r,o),i=await s.text(),a=i?JSON.parse(i):null;if(s.status>=400&&s.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):i;throw new Error(`GitLab ${e} ${r} \u2192 ${s.status} ${c}`)}return{status:s.status,data:a}}async function Lb(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}`),s,i=await Tt(n,"GET",`/projects/${o}`);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await kp(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Tt(n,"GET","/user"),u={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let p=await Tt(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(p.status===404||!p.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=p.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await Tt(n,"POST","/projects",u);if(!m.data)throw new Error("GitLab create project: empty response");s=m.data}let a=s.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=cr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let m=(await Tt(n,"GET",`/projects/${s.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let p of m)l.add(p.path);if(m.length<100)break}let d=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return d.length>0?await Tt(n,"POST",`/projects/${s.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:d}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:s.path,cloneUrl:s.ssh_url_to_repo,branch:a}}async function Tr(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 s=await fetch(Ub+r,o),i=await s.text(),a=null;try{a=i?JSON.parse(i):null}catch{}if(s.status>=400&&s.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${s.status} ${i}`);return{status:s.status,data:a}}async function Bb(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)}`,s,i=await Tr(n,"GET",o);if(i.status===200&&i.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),s=i.data;else{if(r.mode==="attach")throw new Error(`attach: ${await $p(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 Tr(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`);s=f.data}let a=s.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=cr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await Tr(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 Tr(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 d=s.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:s.slug??e.name,cloneUrl:d??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Eb,Db,Ub,Lo=I(()=>{"use strict";Mt();Eb="https://api.github.com";Db="https://gitlab.com/api/v4";Ub="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=Mb[r];if(!o)return null;let s=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(s.length<2)return null;let i=s[s.length-1].replace(/\.git$/,"");return i?{host:o,owner:s.slice(0,-1).join("/"),repoName:i}:null}var Mb,Uo=I(()=>{"use strict";Mb={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as Fb}from"node:crypto";import{existsSync as vp,mkdirSync as Gb,readFileSync as xp,readdirSync as Hb,rmSync as Bo,writeFileSync as Kb}from"node:fs";import{homedir as Wb}from"node:os";import{dirname as qb,join as wi}from"node:path";function Sp(){return wi(Wb(),".codepipe","init-drafts")}function bi(t){let e=Fb("sha256").update(t).digest("hex").slice(0,16);return wi(Sp(),`${e}.json`)}function Rp(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Yb)}function Ip(t){let e=bi(t);if(!vp(e))return null;try{let r=JSON.parse(xp(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Rp(r.savedAt)?(Bo(e,{force:!0}),null):r}catch{return null}}function ki(t){Bo(bi(t),{force:!0})}function Tp(){let t=Sp();if(vp(t))for(let e of Hb(t)){let r=wi(t,e);try{let n=JSON.parse(xp(r,"utf-8"));Rp(n.savedAt)&&Bo(r,{force:!0})}catch{Bo(r,{force:!0})}}}var Yb,Er,Cp=I(()=>{"use strict";Yb=24*60*60*1e3;Er=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(){ki(this.cwd)}persist(){let e=bi(this.cwd);Gb(qb(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Kb(e,JSON.stringify(r,null,2)+`
|
|
808
|
+
`,{mode:384})}}});function Ep(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 Pp(){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 jp(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 Ap=I(()=>{"use strict"});import{existsSync as Vb}from"node:fs";import{join as Jb}from"node:path";import{simpleGit as zb}from"simple-git";function ek(t){let e=t.split("/");return e[e.length-1]??t}function _p(t){if(t.filter(r=>!Qb.test(ek(r))).length>Xb)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(Zb.has(n))return!0}return!1}async function tk(t){try{let r=(await zb(t).raw(["ls-files"])).split(`
|
|
809
|
+
`).map(n=>n.trim()).filter(Boolean);return _p(r)}catch{return!1}}async function rk(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 s=await o.json();return Array.isArray(s)?_p(s.map(i=>i.name??"").filter(Boolean)):!1}catch{return!1}}async function Np(t,e){for(let r of t)try{let n=e.localRoot!=null?Jb(e.localRoot,r.mountAs??r.name):null;if(n&&Vb(n)?await tk(n):await rk(r,e.tokens))return!0}catch{}return!1}var Xb,Qb,Zb,Op=I(()=>{"use strict";Xb=3,Qb=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,Zb=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Dp}from"node:fs";import{join as Lp}from"node:path";import{simpleGit as Up}from"simple-git";async function $n(t,e,r={}){let n=r.log??nk,o=[];for(let s of e){let i=Lp(t,s.mountAs),a=za(s);if(!Dp(i)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${s.mountAs}/`),o.push({mountAs:s.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${s.mountAs}/`),await Up().clone(a,i),o.push({mountAs:s.mountAs,status:"cloned"})}catch(d){let f=kn(d instanceof Error?d.message:String(d));n.warn(`clone failed for ${s.mountAs}: ${f}`),o.push({mountAs:s.mountAs,status:"error",detail:f})}continue}if(!Dp(Lp(i,".git"))){n.warn(`${s.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:s.mountAs,status:"skipped-not-git"});continue}let c=Up(i),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!ok(l,a)){n.warn(`${s.mountAs}/ origin (${kn(l)||"none"}) != expected (${kn(a)}) \u2014 skipping`),o.push({mountAs:s.mountAs,status:"skipped-origin-mismatch",detail:kn(l)});continue}if(r.dryRun){n.info(`would fetch ${s.mountAs}/`),o.push({mountAs:s.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:s.mountAs,status:"fetched"})}catch(d){let f=kn(d instanceof Error?d.message:String(d));n.warn(`fetch failed for ${s.mountAs}: ${f}`),o.push({mountAs:s.mountAs,status:"error",detail:f})}}return o}function ok(t,e){return Bp(t)===Bp(e)}function Bp(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function kn(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Mp(t={}){let e=Te();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 $n(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 nk,Mo=I(()=>{"use strict";Ve();nk={info:t=>console.log(t),warn:t=>console.warn(t)}});var Gp={};Qf(Gp,{upCommand:()=>$i});import{spawn as sk}from"node:child_process";import{existsSync as Fp}from"node:fs";import{homedir as ik,hostname as ak}from"node:os";import{join as Fo}from"node:path";async function ck(t,e,r){let n=he(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Fe(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 xu(t.hubUrl.replace(/\/$/,""),n.token)}catch(s){return console.warn(`[up] could not verify the worker registration (${s instanceof Error?s.message:String(s)}) \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 ${Fe(e)} still holds its token.
|
|
810
|
+
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`),mc(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function lk(t,e,r){let n=he(e)!==null;if(!await ck(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 So(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(s){throw s instanceof D&&s.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):s instanceof D&&s.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"):s instanceof D?s:new Error(`cannot reach the HUB at ${t.hubUrl} (${s instanceof Error?s.message:String(s)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await Ht({hub:t.hubUrl,token:o,name:r.name??`${ak()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function uk(t,e){let r=he(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=be(r.sealPublicKey);if(!G(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Yn(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 dk(t,e){let r=process.cwd(),n=Fo(r,Ye);if(Kn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Fp(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await J(t.hubUrl,t.cliToken,t.projectId)}catch(d){console.warn(`[up] could not fetch the project summary (${d instanceof Error?d.message:String(d)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let s=await xi(r);if(!Ja(r,s?.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 i=G(t.projectId),a={info:d=>console.log(d),warn:d=>console.warn(d)},c=await Eo({cfg:t,secrets:i,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=Fo(ik(),".codepipe",e?Fo("profiles",e,"context-config"):"context-config");if(Zn(c.contextDir,l,a),!Fp(Fo(c.contextDir,"project.yaml"))){ir(c.contextDir);let d={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};zr(c.contextDir,Qe(d,!0,i?.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 $i(t){let{cfg:e,profile:r}=qn(t.profile);await dk(e,r),await lk(e,r,t),uk(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,p)=>{let h=y=>k=>{for(let w of k.toString("utf-8").split(`
|
|
811
|
+
`))w.length>0&&y.write(`${p} ${w}
|
|
812
|
+
`)};m.stdout?.on("data",h(process.stdout)),m.stderr?.on("data",h(process.stderr))},s=(m,p)=>{let h=sk(process.execPath,[n,...p],{stdio:["ignore","pipe","pipe"],env:process.env});return o(h,m),h};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let i=s("[cli]",[...r?["--profile",r]:[],"daemon"]),a=s("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:i},{name:"worker",child:a}],l=!1,d=m=>{if(!l){l=!0,console.log(`
|
|
813
|
+
[up] ${m} \u2014 stopping both roles`);for(let{child:p}of c)p.exitCode===null&&p.kill(m);setTimeout(()=>{for(let{name:p,child:h}of c)h.exitCode===null&&(console.warn(`[up] ${p} did not stop \u2014 SIGKILL`),h.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>d("SIGINT")),process.on("SIGTERM",()=>d("SIGTERM"));let f=c.map(({name:m,child:p})=>new Promise(h=>{p.on("exit",(y,k)=>h({name:m,code:y??(k?1:0)}))})),u=await Promise.race(f);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),d("SIGTERM")),await Promise.all(f),process.exit(u.code)}var vi=I(()=>{"use strict";Ee();Ir();$e();st();ii();Mt();me();ne();Ve();vn()});import{spawn as pk}from"node:child_process";import{existsSync as Pr,mkdirSync as Kp,readFileSync as Wp,readdirSync as fk,writeFileSync as qp}from"node:fs";import{join as qt,resolve as Yp}from"node:path";import{setTimeout as Si}from"node:timers/promises";import{cancel as mk,confirm as jr,intro as Vp,isCancel as Go,log as C,outro as Ri,password as Ar,select as ut,spinner as Ti,text as ie}from"@clack/prompts";import{simpleGit as Ko}from"simple-git";function ee(t){mk(t),process.exit(1)}function ve(t){return Go(t)&&ee("aborted"),t}function X(t){return Go(t)&&ee("aborted"),typeof t=="string"?t:""}async function Jp(t={}){Vp("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Tp();let r=Ip(e),n,o=!1;r&&Object.keys(r.answers).length>0?ve(await jr({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 Er(e,r),o=!0):(ki(e),n=new Er(e)):n=new Er(e);let s=t.force===!0?null:await xi(e),i=await n.ask("target",async()=>ve(await ut({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;i==="local"&&(a=s,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||Xp(e,t.force===!0));let c=await n.ask("hubUrl",async()=>X(await ie({message:"HUB URL",placeholder:He,initialValue:K("HUB_URL")??He,validate:_=>_.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>_r()),{cliToken:d,accountEmail:f}=await n.ask("bootstrap",()=>Nr(c,l)),u=null;i==="farm"&&(u=await gk(c,d));let m=a?yk(a.parsed.repoName):"",p=await n.ask("projectId",async()=>X(await ie({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:_=>Ot.test(_.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await n.ask("projectName",async()=>X(await ie({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()=>ve(await ut({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),k=await n.ask("trackerProvider",async()=>ve(await ut({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),w=k==="internal",b=null,T,L=!0;if(w){let _,le=Ti();le.start("checking task-key prefixes on your account\u2026");try{_=await Su(c,d,{excludeProjectId:p}),le.stop("prefixes checked")}catch{le.stop("could not reach the HUB",1),ee("Could not verify the task-key prefix against your account \u2014 the HUB is unreachable right now. Prefix uniqueness is required, so init can't continue. Check your connection and re-run `codepipe init` later.")}let Ae=Ma(Ba(h),_);T=await n.ask("trackerPrefix",async()=>X(await ie({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Ae,initialValue:Ae,validate:Ge=>{let dt=Ge.trim();if(!Qt.test(dt))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(_.has(dt.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else b=await n.ask("youtrack",()=>sf()),T=await n.ask("youtrackProjectKey",async()=>X(await ie({message:"YouTrack project key",placeholder:"DEV",validate:_=>_.trim().length>0?void 0:"required"})).trim()),L=await n.ask("youtrackWrites",async()=>ve(await jr({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let x=n.get("tokens")??{},A=()=>n.set("tokens",x),O=await n.ask("repos",()=>kk(x,l,a,{onCred:A,initial:n.get("reposPartial")??[],onProgress:_=>n.set("reposPartial",_)}));n.delete("reposPartial");let P=await $k(await n.ask("contextRepo",()=>rf(p,O,x,l)),p,O,x,l,A,_=>n.set("contextRepo",_)),{spec:g,mode:N}=P,$;w||(C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),$=await n.ask("assigneeLogin",async()=>X(await ie({message:"your YouTrack login (the assignee value)",...b?.login?{initialValue:b.login}:{},validate:_=>_.trim().length>0?void 0:"required"})).trim()));let E=await n.ask("claudeToken",()=>Ck(i==="farm")),S={projectId:p,name:h,automationLevel:y,repos:O,trackerProvider:k,youtrackProjectKey:T};C.step(`${N==="attach"?"attaching to":"provisioning"} Context Repo ${g.owner}/${g.name} (${g.host})\u2026`);let j;try{j=await Cr(S,g,{...nf(x),youtrackWrites:L,...b?{trackerUrl:b.url}:{},mode:N,log:{info:_=>C.message(_),warn:_=>C.warn(_)}})}catch(_){ee(`Context Repo provisioning failed: ${_ instanceof Error?_.message:String(_)}`)}S.contextRepo=j,C.success(`Context Repo ready: ${j.owner}/${j.name}@${j.branch}`),C.step(`registering project on ${c}\u2026`);let F;try{F=await xt(c,d,S)}catch(_){if(_ instanceof D&&_.status===409){C.warn(`project ${p} already exists on HUB \u2014 reusing it`);try{F=await J(c,d,p)}catch(le){throw le instanceof D&&ee(`HUB \u2192 ${le.status} ${le.message}`),le}}else if(_ instanceof D&&_.status===401)n.delete("cliToken"),ee("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(_ instanceof D)ee(`HUB \u2192 ${_.status} ${_.message}`);else throw _}let v=F.contextRepo??j;C.success(`project ${F.projectId} ready (${F.provisioningStatus})`);let R=await Ik(v),H=b?{url:b.url,token:b.token}:void 0;if(i==="farm"){let _=u,le={...x,...R?{contextWrite:R}:{},...E?{claude:{oauthToken:E}}:{},...H?{youtrack:H}:{}},Ae=x.github?.token;if(v.host==="github"&&Ae)try{let B=rd(`devpipe-${p}`);await nd(v,Ae,B.publicKey,`devpipe-${p}`),le.contextSsh={privateKey:B.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(B){C.warn(`could not set up Context Repo SSH deploy key (${B instanceof Error?B.message:String(B)}); the farm will fall back to the token path.`)}let Ge={projectId:p,config:{hubUrl:c,cliToken:d,projectId:p},secrets:le,contextRepo:v,projectConfig:Qe(S,L,b?.url,$||void 0)},dt=at(_.farm.publicKey,JSON.stringify(Ge));C.step(`handing project ${p} to farm ${_.farm.name}\u2026`);let pt;try{pt=await xo(c,d,_.farm.farmId,{projectId:p,sealedBundle:dt})}catch(B){throw B instanceof D&&ee(B.status===409?`farm ${_.farm.name} is offline \u2014 start it and re-run.`:B.status===504?`farm ${_.farm.name} did not respond in time.`:`HUB \u2192 ${B.status} ${B.message}`),B}pt.ok||ee(`farm rejected provisioning: ${pt.error??"unknown error"}`),await Ii(c,d,p,v,Ae,F.repos,null,x),n.clear(),Ri(`done. project ${p} is now hosted on farm ${_.farm.name} (daemon ${pt.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}of(x),await Zp(e,v.cloneUrl,v.branch),tf(e),a&&await bk(e);{let _=qt(e,Ye);ir(_);let le=Qe(S,L,b?.url,$||void 0),Ae=zr(_,le);Ae.length>0&&C.success(`local project config \u2192 .codepipe/{${Ae.join(", ")}}`),Ut(p,le,{info:Ge=>C.message(Ge),warn:Ge=>C.warn(Ge)})}await ef(e,F.repos);let te={hubUrl:c,cliToken:d,projectId:p,...x,...R?{contextWrite:R}:{},...E?{claude:{oauthToken:E}}:{},...H?{youtrack:H}:{}};Q(te),ot({hubUrl:c,cliToken:d,projectId:p,accountEmail:f},p),C.success(`secrets \u2192 ${Je(p)}`),await Ii(c,d,p,v,x.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,F.repos,e,x),n.clear();let jn=`${c}/?project=${encodeURIComponent(p)}`;Qp(jn),Ri(`done. your project on the dashboard (sign in there to work with it):
|
|
814
|
+
${jn}
|
|
815
|
+
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:Vo}=await Promise.resolve().then(()=>(vi(),Gp));await Vo({profile:void 0})}async function Ii(t,e,r,n,o,s=[],i=null,a={}){let c=await jp(n,o);if(!c){let f=!1;try{f=await Np(s,{localRoot:i,tokens:a})}catch{f=!1}if(f){let u=Pp(),m=await ut({message:u.message,options:u.options,initialValue:u.initialValue});if(!Go(m)&&m===u.proceedValue)try{let{jobId:p}=await fn(t,e,r,{reindex:!1,backfill:!0});C.success(`retrospective architecture analysis queued (job ${p}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(p){C.warn(`could not start the retrospective analysis: ${p instanceof Error?p.message:String(p)}. Registration is not affected.`)}}}let l=Ep(c),d=await ut({message:l.message,options:l.options,initialValue:l.initialValue});if(!(Go(d)||d!==l.proceedValue))try{let{jobId:f}=await fn(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 gk(t,e){let r;try{r=await ku(t,e)}catch(c){throw c instanceof D&&ee(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&ee("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=ve(await ut({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),s=n.find(c=>c.farmId===o),i;try{i=$o(s.farmId,s.publicKey)}catch(c){ee(c instanceof Error?c.message:String(c))}return ve(await jr({message:`confirm farm ${s.name} cred-channel fingerprint:
|
|
816
|
+
${i}
|
|
817
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||ee("farm fingerprint not confirmed \u2014 aborting."),ko(s.farmId,i),{farm:s,fingerprint:i}}async function zp(t){Vp(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Xp(e,t.force===!0);let r=X(await ie({message:"HUB URL",initialValue:K("HUB_URL")??He,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await _r(),{cliToken:o,accountEmail:s}=await Nr(r,n);C.step(`fetching project ${t.projectId} from HUB\u2026`);let i;try{i=await J(r,o,t.projectId)}catch(u){throw u instanceof D&&ee(`HUB \u2192 ${u.status} ${u.message}`),u}i.contextRepo||ee(`project ${t.projectId} has no Context Repo on HUB`);let c=i.trackerProvider==="internal"?null:await sf(),l={},d=new Set(i.repos.map(u=>u.host));d.add(i.contextRepo.host);for(let u of d){let m=i.repos.find(p=>p.host===u);await Ho(u,l,m?.owner??i.contextRepo.owner,n,m?.repoName)}of(l),await Zp(e,i.contextRepo.cloneUrl,i.contextRepo.branch),tf(e);{let u=qt(e,Ye);ir(u);let m={projectId:t.projectId,name:i.name,automationLevel:i.automationLevel,repos:i.repos,...i.trackerProvider?{trackerProvider:i.trackerProvider}:{},...i.youtrackProjectKey?{youtrackProjectKey:i.youtrackProjectKey}:{}},p=Qe(m,!0,c?.url),h=zr(u,p);h.length>0&&C.success(`local project config \u2192 .codepipe/{${h.join(", ")}} (defaults \u2014 review and adjust)`),Ut(t.projectId,p,{info:y=>C.message(y),warn:y=>C.warn(y)})}await ef(e,i.repos);let f={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};Q(f),ot({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:s},t.projectId),C.success(`secrets \u2192 ${Je(t.projectId)}`),await Ii(r,o,t.projectId,i.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,i.repos,e,l),Ri("done.")}function Xp(t,e){if(!Pr(t)){Kp(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=fk(t).filter(o=>!r.has(o));n.length!==0&&(e||ee(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function xi(t){if(!Pr(qt(t,".git")))return null;try{let r=(await Ko(t).remote(["get-url","origin"])||"").toString().trim(),n=r?je(r):null;return n?{parsed:n,defaultBranch:await hk(t)}:null}catch{return null}}async function hk(t){let e=Ko(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 yk(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Ot.test(e)?e:""}function wk(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function bk(t){let e=qt(t,".gitignore"),r=Pr(e)?Wp(e,"utf-8"):"";if(wk(r))return;if(!ve(await jr({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
818
|
`)?"":`
|
|
685
|
-
`;
|
|
819
|
+
`;qp(e,r+o+`
|
|
686
820
|
# codepipe workspace (added by \`codepipe init\`)
|
|
687
821
|
.codepipe/
|
|
688
|
-
`),
|
|
822
|
+
`),C.success(`.codepipe/ added to ${Yp(e)}`)}function Qp(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=pk(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function _r(){let t="";try{t=(await Ko().raw(["config","--global","user.email"])||"").trim()}catch{}return X(await ie({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Nr(t,e){C.step(`connecting account ${e}`);let r;try{r=await Ru(t,e)}catch(i){throw i instanceof pn&&ee(`${e} is not authorized on this HUB yet.
|
|
689
823
|
Sign up at ${t} (registration form on the login screen),
|
|
690
824
|
wait for the operator to approve it by email, then re-run
|
|
691
|
-
\`codepipe init\` with the same email.`),
|
|
825
|
+
\`codepipe init\` with the same email.`),i}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&&(Qp(r.authorizeUrl),C.message(`a browser tab was opened to confirm this CLI:
|
|
692
826
|
${r.authorizeUrl}
|
|
693
827
|
`+(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&&
|
|
695
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
828
|
+
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(),s=o+15*6e4;for(;Date.now()<s;){let i;try{i=await Iu(t,r.requestId)}catch(a){C.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Si(5e3);continue}if(i.status==="confirmed"&&i.cliToken){let a=i.email??e;return a!==e&&C.message(`connected as ${a} (the account confirmed in the browser).`),C.success("confirmed"),{cliToken:i.cliToken,accountEmail:a}}if(i.status==="rejected"&&ee("the HUB rejected this account"),i.status==="expired"&&ee("the request expired \u2014 re-run init"),i.status==="waiting_approval"||i.status==="email_confirmed"){n||(n=!0,s=o+24*60*6e4,C.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
829
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Si(5e3);continue}await Si(2e3)}ee("bootstrap timed out")}async function Zp(t,e,r){let n=qt(t,Ye);if(Pr(qt(n,".git"))){C.message(`${n} already cloned \u2014 skipping`);return}Pr(n)&&ee(`${n} exists but is not a git repo \u2014 remove it and re-run`),Kp(n,{recursive:!0}),C.step(`cloning Context Repo \u2192 ${n}`);try{await Ko().clone(e,n,["--branch",r]),C.success(`cloned ${e}`)}catch(o){ee(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function ef(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 $n(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 tf(t){let e=qt(t,Ye,".gitignore"),r="";if(Pr(e)&&(r=Wp(e,"utf-8")),Hp.filter(i=>i.startsWith("#")?!1:!r.split(/\r?\n/).includes(i)).length===0)return;let o=r.endsWith(`
|
|
696
830
|
`)||r.length===0?"":`
|
|
697
|
-
`,
|
|
831
|
+
`,s=Hp.join(`
|
|
698
832
|
`)+`
|
|
699
|
-
`;
|
|
700
|
-
`:"")+
|
|
833
|
+
`;qp(e,r+o+(r?`
|
|
834
|
+
`:"")+s),C.message(`appended runtime entries to ${Yp(e)}`)}async function kk(t,e,r,n={}){let o=[...n.initial??[]],s=n.onCred;if(r&&o.length===0){let{parsed:i,defaultBranch:a}=r;C.message(`this repo: ${i.host}: ${i.owner}/${i.repoName} (mounted in place)`),await Ho(i.host,t,i.owner,e,i.repoName),s?.();let c=X(await ie({message:"repo logical name (used inside Context Repo paths)",placeholder:i.repoName,initialValue:i.repoName,validate:d=>d.trim().length>0?void 0:"required"})).trim(),l=X(await ie({message:"default branch",placeholder:a,initialValue:a,validate:d=>d.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:i.host,owner:i.owner,repoName:i.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;ve(await jr({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=X(await ie({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||je(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=je(a);C.message(`${c.host}: ${c.owner}/${c.repoName}`),await Ho(c.host,t,c.owner,e,c.repoName),s?.();let l=X(await ie({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(),d=X(await ie({message:"default branch (optional)",placeholder:"main"})).trim(),f=X(await ie({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),u={name:l,host:c.host,owner:c.owner,repoName:c.repoName};d&&(u.defaultBranch=d),f&&f!==l&&(u.mountAs=f),o.push(u),n.onProgress?.(o)}return o}async function rf(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=ve(await ut({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 s=e[0]?.host,i=e[0]?.owner,a;if(s&&i){let c=X(await ie({message:`Context Repo \u2014 a name (hosted at ${s}: ${i}/<name>) or a full clone URL`,initialValue:nt(t),validate:d=>{let f=(d??"").trim();if(!f)return"required";if(!je(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=je(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:s,owner:i,name:c}}else{let c=await vk(),l=X(await ie({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),d=X(await ie({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:d}}return{spec:a,mode:o}}function nf(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??rr()}}async function $k(t,e,r,n,o,s,i){let a=t;for(;;){let{spec:c,mode:l}=a;await Ho(c.host,n,c.owner,o),s?.();let d=Ti();d.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await wp(c,nf(n),{explain:l==="attach"});if(f.found===!0)return d.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return d.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(l==="create")return d.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;d.stop(f.detail,1);let u=ve(await ut({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(u==="abort"&&ee("aborted"),u==="create")return a={spec:c,mode:"create"},i(a),a;a=await rf(e,r,n,o),i(a)}}async function vk(){return ve(await ut({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function xn(t,e){let r=Ti();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 of(t){an(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),cn(t.gitlab?.token??process.env.GITLAB_TOKEN),ln(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Ho(t,e,r,n,o){if(!e[t])if(t==="github"){let s=await xk(r);s?e.github=s:C.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let s=await Sk(r,n,o);s?e.bitbucket=s: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 s=await Rk();s?e.gitlab=s:C.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function xk(t){for(;;){let e=X(await Ar({message:`GitHub PAT \u2014 blank to skip
|
|
701
835
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
702
836
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
703
837
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
704
838
|
(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
|
|
839
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await xn("GitHub",()=>ht(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Sk(t,e,r){for(C.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
706
840
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
707
841
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
|
|
708
842
|
read:repository:bitbucket + write:repository:bitbucket +
|
|
709
843
|
read:pullrequest:bitbucket + write:pullrequest:bitbucket
|
|
710
844
|
\u2014 write scopes do NOT include read: pick BOTH scopes of each pair
|
|
711
845
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
712
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let n=X(await
|
|
713
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
846
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let n=X(await ie({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:s=>!s||!s.trim()||s.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=X(await Ar({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 xn("Bitbucket",async()=>{let s=await yt(n,o,t);if(t&&r){let i=await so(n,o,t,r);if(i)throw new Error(i)}return s}))return{email:n,apiToken:o};C.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Rk(){for(;;){let t=X(await Ar({message:`GitLab PAT \u2014 blank to skip
|
|
847
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await xn("GitLab",()=>wt(t))){let e=await Fc(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Ik(t){if(ve(await jr({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
714
848
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
715
849
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
716
|
-
your trusted network.`,initialValue:!1})))for(t.host==="github"?
|
|
850
|
+
your trusted network.`,initialValue:!1})))for(t.host==="github"?C.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
717
851
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
718
|
-
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):
|
|
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=X(await
|
|
720
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=X(await
|
|
721
|
-
`),r=e.find(
|
|
722
|
-
`),a=
|
|
723
|
-
`).replace(/^\n+/,""),y=[`# ADR-${
|
|
852
|
+
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
|
|
853
|
+
(${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=X(await Ar({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await xn("contextWrite",()=>Tk(r,t)))return{token:r};C.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Tk(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(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 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 Ck(t){if(ms()?.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?`
|
|
854
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=X(await Ar({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 sf(){for(;;){let t=X(await ie({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=X(await Ar({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await xn("YouTrack",()=>vt({baseUrl:t,token:e}))){let r=await Dl({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}var Hp,vn=I(()=>{"use strict";Oe();q();Ee();$e();st();Mt();Lo();si();Uo();bt();Gt();Cp();me();Ap();Op();Qs();fo();ne();Mo();Ve();Hp=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});q();Oe();$e();import{Command as U$}from"commander";Gn();import{homedir as tc}from"node:os";import{join as rc}from"node:path";function nc(){Lt(rc(tc(),".devpipe"),rc(tc(),".codepipe"))}$e();ne();async function hc(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 ${er(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");ot({hubUrl:n,cliToken:t.token,projectId:t.project},e);let s={...G(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};Q(s),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${er(e)}`)}gs();$e();import{homedir as ai}from"node:os";import{join as mn}from"node:path";Oe();q();import{existsSync as Zu,readFileSync as Ly,rmSync as Uy}from"node:fs";import{join as pr}from"node:path";import{simpleGit as By}from"simple-git";import"ws";Oe();ne();import{createHash as Nm}from"node:crypto";import{existsSync as Om,readFileSync as Dm}from"node:fs";import{homedir as Lm,hostname as hs}from"node:os";import{join as Um}from"node:path";function kc(t){return Nm("sha256").update(t).digest("hex").slice(0,12)}function Bm(){let t=K("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Um(Lm(),".claude","credentials.json");if(!Om(e))return;let r=JSON.parse(Dm(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 $c(t){let e=Bm(),r=K("ACCOUNT_ID")?.trim(),n=K("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=tr(t);return o?{accountId:`acct-${kc(o)}`,label:n||hs(),...e?{email:e}:{}}:{accountId:`acct-${kc(`host:${hs()}`)}`,label:n||hs(),...e?{email:e}:{}}}import{existsSync as Mm}from"node:fs";import{join as Fm}from"node:path";import{simpleGit as Gm}from"simple-git";async function vc(t,e){if(!Mm(Fm(t,".git")))return{status:"skipped"};let r=Gm(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Hm(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 Hm(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as ws,readFileSync as Tc,readdirSync as qm,watch as Ym}from"node:fs";import{join as Jr}from"node:path";q();import{existsSync as xc,readFileSync as Sc,readdirSync as Km,statSync as Wm}from"node:fs";import{join as ys}from"node:path";import{parse as Rc}from"yaml";function Xn(t){let e=ys(t,"actions"),r=[],n=[];if(!xc(e))return{defs:r,errors:n};let o;try{o=Km(e).sort()}catch{return{defs:r,errors:n}}let s=new Set;for(let i of o){if(!/\.(yml|yaml)$/i.test(i))continue;let a=ys(e,i);try{if(!Wm(a).isFile())continue;let c=ya(i,Rc(Sc(a,"utf-8")));if(s.has(c.id))throw new Error(`duplicate action id "${c.id}"`);s.add(c.id),r.push(c)}catch(c){n.push({file:`actions/${i}`,error:c instanceof Error?c.message:String(c)})}}return{defs:r,errors:n}}function Ic(t){let e={},r=ys(t,"project.yaml");if(!xc(r))return e;let n;try{n=Rc(Sc(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[s,i]of Object.entries(o))!Ie.test(s)||ft(s)||(typeof i=="string"?e[s]=i:(typeof i=="number"||typeof i=="boolean")&&(e[s]=String(i)));return e}var Qn=class{constructor(e,r,n,o,s=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=s}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,Jr(this.contextDir,"prompts"),Jr(this.contextDir,"actions")];for(let n of r)if(ws(n))try{let o=Ym(n,e);o.on("error",s=>{this.log.warn(`[config] fs.watch failed on ${n} \u2014 falling back to periodic reporting: ${s instanceof Error?s.message:String(s)}`);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=Xn(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=Jr(this.contextDir,e);if(!ws(r))return null;try{return Tc(r,"utf-8")}catch{return null}}readPrompts(){let e=Jr(this.contextDir,"prompts"),r={};if(!ws(e))return r;let n;try{n=qm(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let s=o.slice(0,-3);try{r[s]=Tc(Jr(e,o),"utf-8")}catch{}}return r}};it();import{existsSync as Is,readFileSync as Nc,readdirSync as sg}from"node:fs";import{join as Oc}from"node:path";import{simpleGit as ig}from"simple-git";var ag=/^(\d{4})-(.+)\.md$/,cg="0000-template.md";function lg(t){let e=t.split(`
|
|
855
|
+
`),r=e.find(s=>s.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=s=>{let i=new RegExp(`^-\\s*\\*\\*${s}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=i.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function ug(t,e,r,n,o){let s=String(e).padStart(4,"0"),i=t.split(`
|
|
856
|
+
`),a=i.findIndex(k=>k.startsWith("# ")),c=a>=0&&(i[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),d=[],f="",u=null,m=a>=0?a+1:0;for(let k=m;k<i.length;k++){let w=(i[k]??"").trim();if(w===""){m=k+1;continue}let b=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!b)break;let T=(b[1]??"").trim().toLowerCase(),L=(b[2]??"").trim(),x=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(w);x&&(u=parseInt(x[1]??"",10)),T==="tasks"&&(f=L),l.has(T)||d.push(w),m=k+1}let p=f?f.includes(n)?f:`${f}, ${n}`:n,h=i.slice(m).join(`
|
|
857
|
+
`).replace(/^\n+/,""),y=[`# ADR-${s}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${p}`,...d,"",h].join(`
|
|
724
858
|
`);return{content:y.endsWith(`
|
|
725
859
|
`)?y:y+`
|
|
726
|
-
`,supersedes:u}}function
|
|
860
|
+
`,supersedes:u}}function dg(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
861
|
|
|
728
|
-
- **Status:** superseded by ADR-${r}`):n}function
|
|
862
|
+
- **Status:** superseded by ADR-${r}`):n}function pg(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
863
|
`)+`
|
|
730
|
-
`}async function
|
|
731
|
-
`)}async function
|
|
732
|
-
${l.
|
|
733
|
-
${
|
|
734
|
-
${
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
`)
|
|
738
|
-
`)}
|
|
739
|
-
|
|
864
|
+
`}async function Dc(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await ig(t).pull(void 0,void 0,["--rebase"])}catch{}let s=y=>o==="staging"?`adr/DRAFT-${y}.md`:`tasks/${e}/adr/DRAFT-${y}.md`,i=[],a=[];for(let y of r){let k=oe(t,s(y));if(!Is(k)){a.push(y);continue}i.push({slug:y,content:Nc(k,"utf-8")})}let c=Oc(t,"adr"),l=new Map;if(Is(c))for(let y of sg(c)){let k=ag.exec(y);!k||y===cg||l.set(y,{num:parseInt(k[1]??"",10),slug:k[2]??"",content:Nc(Oc(c,y),"utf-8")})}let d=Math.max(0,...[...l.values()].map(y=>y.num))+1,f=new Map,u=[],m=[];for(let y of i){if([...l.entries()].find(([,x])=>x.slug===y.slug&&x.content.includes(e))){m.push(y.slug);continue}let w=d++,b=`${String(w).padStart(4,"0")}-${y.slug}.md`,{content:T,supersedes:L}=ug(y.content,w,y.slug,e,n);if(f.set(b,T),l.set(b,{num:w,slug:y.slug,content:T}),u.push(`adr/${b}`),L!==null){let x=[...l.keys()].find(A=>A.startsWith(`${String(L).padStart(4,"0")}-`));if(x&&x!==b){let A=dg(f.get(x)??l.get(x).content,w);f.set(x,A),l.set(x,{...l.get(x),content:A})}}}let p=[];if(o==="staging")for(let y of i)Is(oe(t,`adr/DRAFT-${y.slug}.md`))&&p.push({path:`adr/DRAFT-${y.slug}.md`,content:"",deleted:!0});if(u.length===0&&p.length===0)return{promoted:u,skipped:m,missing:a};if(u.length>0){let y=[...l.entries()].map(([k,w])=>({num:w.num,file:k,header:lg(w.content)}));f.set("INDEX.md",pg(y))}for(let[y,k]of f.entries())p.push({path:`adr/${y}`,content:k});let h=u.length>0?`adr(${e}): promote ${i.map(y=>y.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Xe(t,p,h),{promoted:u,skipped:m,missing:a}}it();st();q();import{existsSync as Lc,readFileSync as mg}from"node:fs";import{join as Uc}from"node:path";function gg(t){for(let e of[We,Kr]){let r=Uc(t,e);if(Lc(r))try{return Xi(mg(r,"utf-8"))}catch{return 0}}return 0}function hg(t,e,r,n=4){let o=e<n,s=o?Qi(e).filter(i=>!r(i)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:s}}function no(t,e){return hg(e,gg(t),r=>Lc(Uc(t,r)))}q();bt();import{existsSync as Xc,mkdirSync as Kg,mkdtempSync as Wg,rmSync as Qc,writeFileSync as Zc}from"node:fs";import{tmpdir as qg}from"node:os";import{dirname as Yg,join as co}from"node:path";import{simpleGit as Os}from"simple-git";Mt();function Vg(t){return`codepipe/context-migration-v${t}`}function Jg(t){let e=Zi(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 \`${We}\` stamp (renamed from \`${Kr}\``,"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(`
|
|
865
|
+
`)}async function el(t,e,r,n){let o=Os(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let s=no(t,e);if(!s.outdated)return s;let i=Vg(s.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",i]).catch(()=>"")).trim().length===0?await zg(t,e,r,s,i,a,n):n.info(`[ctx] migration branch ${i} 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)}`),s}if(!r)return s;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Le(c),d=await l.findOpenPrByBranch?.(c,i)??null;if(d)return n.info(`[ctx] migration PR already open: ${d.url}`),{...s,migrationPrUrl:d.url};let f=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:i,baseBranch:a,title:`CodePipe: context format v${s.templateVersion} \u2192 v${s.currentVersion}`,body:Jg(s)});return n.info(`[ctx] migration PR opened: ${f.url}`),{...s,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)}`),s}}async function zg(t,e,r,n,o,s,i){let a=Os(t),c=Wg(co(qg(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${s}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},d={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map(cr(l,d).map(h=>[h.path,h.content])),u=0;for(let h of n.missingPaths){if(h===We)continue;let y=f.get(h);if(y==null){i.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let k=co(c,h);Xc(k)||(Kg(Yg(k),{recursive:!0}),Zc(k,y),u++)}Zc(co(c,We),On(n.currentVersion)),u++;let m=co(c,Kr);Xc(m)&&(Qc(m,{force:!0}),u++);let p=Os(c);await p.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await p.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await p.push(["-u","origin",o]),i.info(`[ctx] migration branch ${o} pushed (${u} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Qc(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}q();it();import{existsSync as Xg,readFileSync as Qg,readdirSync as Zg,statSync as eh}from"node:fs";import{join as Ds}from"node:path";var th=/^model\/(?:project\.json|[^/]+\/containers\.json|[^/]+\/(?:components|code)\/[^/]+\.json)$/,tl=`${Dn}/INDEX.json`;function en(t){return th.test(t)}function Us(t,e=()=>{}){let r=new Map,n=Ds(t,Dn);if(!Xg(n))return r;let o=s=>{let i=Ds(t,s);for(let a of Zg(i)){let c=`${s}/${a}`;if(eh(Ds(t,c)).isDirectory()){o(c);continue}if(en(c))try{let l=JSON.parse(Qg(oe(t,c),"utf-8")),{ok:d,errors:f}=ns(l);if(!d){e(`[model] skipping invalid shard ${c}: ${f[0]??"invalid"}`);continue}r.set(c,l)}catch(l){e(`[model] skipping unreadable shard ${c}: ${l instanceof Error?l.message:String(l)}`)}}};return o(Dn),r}function rl(t,e){return t.id<e.id?-1:t.id>e.id?1:0}function Ls(t){if(Array.isArray(t))return t.map(Ls);if(t&&typeof t=="object"){let e=t,r={};for(let n of Object.keys(e).sort())e[n]!==void 0&&(r[n]=Ls(e[n]));return r}return t}function rh(t){let e=new Map,r=[...t].sort((i,a)=>{let c=`${i.repo??""}|${i.level}|${i.container??""}`,l=`${a.repo??""}|${a.level}|${a.container??""}`;return c<l?-1:c>l?1:0});for(let i of r){if(i.repo===null)continue;let a=e.get(i.repo);a||(a={builtFromCommit:null,counts:{system:0,container:0,component:0,code:0}},e.set(i.repo,a)),(i.level==="container"||a.builtFromCommit===null)&&(a.builtFromCommit=i.builtFromCommit??a.builtFromCommit);for(let c of i.nodes)At.includes(c.level)&&(a.counts[c.level]+=1)}let n=t.flatMap(i=>i.nodes).filter(i=>i.level==="system"||i.level==="container"),o=t.filter(i=>i.level==="system"||i.level==="container").flatMap(i=>i.edges),s={modelFormatVersion:1,repos:[...e.entries()].sort(([i],[a])=>i<a?-1:i>a?1:0).map(([i,a])=>({repo:i,builtFromCommit:a.builtFromCommit,counts:a.counts})),nodes:[...n].sort(rl),edges:[...o].sort(rl)};return`${JSON.stringify(Ls(s),null,2)}
|
|
866
|
+
`}function nl(t,e,r=()=>{}){let n=[],o=new Map;for(let i of e){if(i.path===tl)continue;if(!en(i.path)){n.push(i);continue}if(i.deleted){o.set(i.path,null),n.push(i);continue}let a=i.encoding==="base64"?Buffer.from(i.content,"base64").toString("utf-8"):i.content,c;try{c=JSON.parse(a)}catch(u){throw new Error(`model write rejected: ${i.path} is not valid JSON (${u instanceof Error?u.message:String(u)})`)}let{ok:l,errors:d}=ns(c);if(!l)throw new Error(`model write rejected: ${i.path}: ${d.join("; ")}`);let f=c;o.set(i.path,f),n.push({path:i.path,content:aa(f)})}let s=Us(t,r);for(let[i,a]of o)a===null?s.delete(i):s.set(i,a);return n.push({path:tl,content:rh([...s.values()])}),n}import{existsSync as nh,readFileSync as oh,writeFileSync as sh}from"node:fs";import{homedir as ih}from"node:os";import{join as ol}from"node:path";import{parseDocument as ah}from"yaml";function ch(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 lh(t,e){let r=ah(t);return r.set("repos",e.map(ch)),r.toString()}function uh(t,e){let r=[ol(ih(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(ol(e,"project.yaml")),r}function tn(t,e,r){let n=[],o=[];for(let s of uh(t,r))if(nh(s))try{let i=oh(s,"utf-8"),a=lh(i,e);a!==i&&(sh(s,a),n.push(s))}catch(i){o.push({path:s,error:i instanceof Error?i.message:String(i)})}return{updated:n,errors:o}}import{execFileSync as hl}from"node:child_process";it();import{existsSync as dh,readFileSync as ph,statSync as sl}from"node:fs";var lr=2*1024*1024;function Bs(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function lo(t,e){let r=oe(t,e);if(e.split("/").some(s=>s===".git"))throw new Error(`not a context file: ${e}`);if(!dh(r)||!sl(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=sl(r);if(n>lr)throw new Error(`file too large: ${e} is ${n} bytes (limit ${lr})`);let o=ph(r);return Bs(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{homedir as fh}from"node:os";import{existsSync as mh,mkdirSync as gh}from"node:fs";import{join as Ms}from"node:path";import{simpleGit as Fs}from"simple-git";var il=t=>console.log(t);function al(t){il=t}function rn(t,e="info"){il(t,e)}function we(t,e,r){let n=r??Ms(fh(),".codepipe","repos");return Ms(n,t,e)}async function Ft(t,e,r={}){let n=we(t,e.name,r.baseDir),o=r.cloneUrlOverride??on(e);if(!mh(Ms(n,".git"))){gh(n,{recursive:!0});let a=Fs();rn(`[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}
|
|
867
|
+
${l.trim()}`)}}let s=Fs(n);try{await s.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
|
|
868
|
+
${c.trim()}`)}let i=e.defaultBranch??"main";return await s.checkout(["-B",i,`origin/${i}`]).catch(()=>{}),s}async function nn(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var cl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function uo(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:s,commitMessage:i}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&rn(`[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 nn(t,s)||await t.fetch(["origin",s]).catch(()=>{}),!await nn(t,s))throw new Error(`apply_delivery: base commit ${s.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...cl,"commit-tree",c,"-p",s,"-m",i])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function ll(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await nn(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await nn(t,o)){let i=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}let s=await r();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}async function ul(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,branchName:a,baseRef:c,commitMessage:l,defaultBranch:d,force:f}=r,u=await ll(t,s,()=>uo(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;if(await nn(t,m)||(m=`origin/${d??c}`),(await t.revparse([m])).trim()===i)await t.raw(["branch","-f",a,u]),await t.checkout(a);else{await t.checkout(["-B",a,m]);try{await t.raw([...cl,"cherry-pick",u])}catch(k){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let w=k instanceof Error?k.message:String(k);throw new Error(`apply_delivery: cherry-pick of ${s.slice(0,10)} onto ${c} hit conflicts
|
|
869
|
+
${w.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),y=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(y),await t.push([n,"--delete",o]).catch(()=>{}),{commit:h}}async function dl(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,branchName:a,commitMessage:c,push:l}=r,d=await ll(t,s,()=>uo(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:s,baseSha:i,commitMessage:c}));return await t.raw(["branch","-f",a,d]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:d,pushed:l}}async function pl(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:s,deleteBranch:i}=r,a=`origin/${n}`;return s==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):s==="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]),i&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function on(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 fl(t){return(await Fs().listRemote(["--heads",t])).split(`
|
|
870
|
+
`).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 ml(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}async function yl(t,e){return t.kind==="task"?wh(t.taskKey,e):yh(t.nodeId,e)}function hh(t){return t.length===0||t.startsWith("/")||t.includes("\\")?!1:t.split("/").every(e=>e.length>0&&e!=="."&&e!==".."&&e!==".git")}async function yh(t,e){if(!t.startsWith("code:"))throw new Error("not_found");let r=t.indexOf("#"),n=r===-1?t:t.slice(0,r),o=r===-1?void 0:t.slice(r+1),s=n.slice(5),i=s.indexOf(":"),a=i>0?s.slice(0,i):"",c=i>0?s.slice(i+1):"";if(a.length===0||c.length===0)throw new Error("not_found");let l=Us(e.contextDir),d,f=null;for(let x of o!==void 0?[t,n]:[t]){for(let A of l.values()){let O=A.nodes.find(P=>P.id===x);if(O){d=O,f=A.builtFromCommit;break}}if(d)break}let u=d?.source?.path??c,m=d?.source?.range;if(!hh(u))throw new Error("not_found");let p=e.resolveRepoSpec(a);if(!p)throw new Error(`unavailable: repo "${a}" is not configured on this CLI`);await Ft(e.projectId,p,{baseDir:e.baseDir,cloneUrlOverride:e.cloneUrlOverride});let h=we(e.projectId,p.name,e.baseDir),y="HEAD",k=!1,w=null;if(f&&(w=gl(h,f,u),w!==null?y=f:k=!0),w===null&&(w=gl(h,y,u)),w===null)throw new Error("not_found");if(w>lr)throw new Error(`file too large: ${u} is ${w} bytes (limit ${lr})`);let b=bh(h,y,u),T={repo:a,path:u,...o!==void 0?{symbol:o}:{},...f?{builtFromCommit:f}:{},...k?{stale:k}:{}};if(!Bs(b))return{content:b.toString("base64"),encoding:"base64",sizeBytes:b.length,meta:T};let L=b.toString("utf-8");if(m){let x=L.split(`
|
|
871
|
+
`),A=Math.max(1,m.startLine),O=Math.min(x.length,m.endLine);A<=O&&(L=`${x.slice(A-1,O).join(`
|
|
872
|
+
`)}
|
|
873
|
+
`,T.startLine=A,T.endLine=O)}return{content:L,encoding:"utf8",sizeBytes:Buffer.byteLength(L,"utf-8"),meta:T}}async function wh(t,e){if(!/^[A-Za-z][A-Za-z0-9]*-\d+$/.test(t))throw new Error("not_found");let r=`tasks/${t}/task.md`;try{return{...lo(e.contextDir,r),meta:{path:r}}}catch(i){if(!(i instanceof Error)||!i.message.startsWith("file not found"))throw i}let n=e.resolveTracker();if(!n)throw new Error("unavailable: no task source on this CLI");let o=await n.getIssue(t);if(!o)throw new Error("not_found");let s=`# ${o.key}: ${o.title}
|
|
874
|
+
|
|
875
|
+
${o.description??"_(no description)_"}
|
|
876
|
+
`;return{content:s,encoding:"utf8",sizeBytes:Buffer.byteLength(s,"utf-8"),meta:{}}}function gl(t,e,r){try{let n=hl("git",["cat-file","-s",`${e}:${r}`],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),o=parseInt(n.trim(),10);return Number.isFinite(o)?o:null}catch{return null}}function bh(t,e,r){return hl("git",["show",`${e}:${r}`],{cwd:t,stdio:["ignore","pipe","ignore"],maxBuffer:lr+1024*1024})}Ve();Ee();ne();function Rh(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 vl(t,e,r,n){let o=Rh(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 s=JSON.stringify(o),i=[];for(let a of t.sandboxes){let c=Yn(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=at(a.publicKey,s)}catch(d){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${d instanceof Error?d.message:String(d)}`);continue}i.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return i}Ee();ne();bt();Gt();ne();bt();Gt();function Ue(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Zl(t,e){let r=G(t),n=[],o=[],s=()=>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 vt({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:s()})}catch(c){n.push({name:"youtrack",ok:!1,detail:Ue(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Ue(c),checkedAt:s()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:s()});let i=!1;if(r?.github?.token){i=!0;try{let c=await ht(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){n.push({name:"github",ok:!1,detail:Ue(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Ue(c),checkedAt:s()})}}else o.push({kind:"github",present:!1,checkedAt:s()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){i=!0;try{let c=await yt(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){n.push({name:"bitbucket",ok:!1,detail:Ue(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Ue(c),checkedAt:s()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:s()});if(r?.gitlab?.token){i=!0;try{let c=await wt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:s()})}catch(c){n.push({name:"gitlab",ok:!1,detail:Ue(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Ue(c),checkedAt:s()})}}else o.push({kind:"gitlab",present:!1,checkedAt:s()});if(i||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let d of e?.repos??[])if(d.host==="github")try{await oo(c,d.owner,d.repoName),n.push({name:`repo:${d.name}`,ok:!0})}catch(f){n.push({name:`repo:${d.name}`,ok:!1,detail:Ue(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await oo(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(d){n.push({name:"context-repo",ok:!1,detail:Ue(d)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await oo(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:s()})}catch(l){o.push({kind:"contextWrite",present:!0,ok:!1,detail:Ue(l),checkedAt:s()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:s()})}else o.push({kind:"contextWrite",present:!1,checkedAt:s()});let a=tr(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:s()});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:s()});else{let c=await Ws(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:s()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:s()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Ws(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)}}fo();function nu(t){let e=G(t);if(!e)return null;if(!e.sealKey){let r=po();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},Q(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:be(e.sealKey.publicKey)}}async function ou(t,e,r,n){let o;try{o=JSON.parse(ur(n,r).toString("utf-8"))}catch(i){return{ok:!1,detail:`cannot open the sealed credential (${i instanceof Error?i.message:String(i)}) \u2014 wrong channel key?`}}let s=G(t);if(!s)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 i=await ht(o.token);return s.github={token:o.token},dr(s,()=>{process.env.GH_TOKEN=o.token,eu(o.token)}),{ok:!0,detail:`authenticated as ${i}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=await wt(o.token);return s.gitlab={token:o.token},dr(s,()=>{process.env.GITLAB_TOKEN=o.token,tu(o.token)}),{ok:!0,detail:`authenticated as ${i}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let i=await yt(o.email,o.apiToken);return s.bitbucket={email:o.email,apiToken:o.apiToken},dr(s,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,ru(o.apiToken)}),{ok:!0,detail:`authenticated as ${i}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let i=o.url?.trim().replace(/\/$/,"")||s.youtrack?.url;if(!i)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await vt({baseUrl:i,token:o.token});return s.youtrack={url:i,token:o.token},dr(s,()=>{process.env.YOUTRACK_URL=i,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 i=await Ws(o.token);return i==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(s.claude={oauthToken:o.token},dr(s,()=>{}),{ok:!0,...i==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(s.contextWrite={token:o.token},dr(s,()=>{}),{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(i){return{ok:!1,detail:`${i instanceof Error?i.message:String(i)} \u2014 previous credential kept`}}}function dr(t,e){Q(t),e()}q();q();import{spawn as Mh}from"node:child_process";var Fh=124,su=16*1024,iu=4e3;function Gh(t,e,r,n,o,s){let i={...t},a=(c,l)=>{ft(c)||(i[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))i[c]=l;for(let[c,l]of Object.entries(s))i[`INPUT_${c}`]=String(l);return i}async function au(t){let{def:e,onEvent:r}=t,n=Gh(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",s=a=>{o+=a+`
|
|
877
|
+
`,o.length>su&&(o=o.slice(o.length-su))},i=(a,c)=>{let l=c.length>iu?c.slice(0,iu)+"\u2026":c;s(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 d=await Hh(c.run,c.timeout_sec,t.cwd,n,i);if(d!==0)return s(`[${l}] exited with code ${d}`),r({ts:Date.now(),kind:"result",status:"failed",exitCode:d,failedStep:l}),{status:"failed",exitCode:d,failedStep:l,logTail:o}}return r({ts:Date.now(),kind:"result",status:"succeeded",exitCode:0}),{status:"succeeded",exitCode:0,logTail:o}}function Hh(t,e,r,n,o){return new Promise(s=>{let i=Mh("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??ha)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),i.kill("SIGTERM"),setTimeout(()=>i.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let d=m=>{let p="";return{data:h=>{p+=h.toString("utf-8");let y;for(;(y=p.indexOf(`
|
|
878
|
+
`))!==-1;)o(m,p.slice(0,y).replace(/\r$/,"")),p=p.slice(y+1)},flush:()=>{p.length>0&&o(m,p.replace(/\r$/,"")),p=""}}},f=d("stdout"),u=d("stderr");i.stdout?.on("data",f.data),i.stderr?.on("data",u.data),i.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),s(127)}),i.on("close",(m,p)=>{clearTimeout(l),f.flush(),u.flush(),s(a?Fh:m??(p?1:0))})})}ne();q();import{existsSync as Kh,readFileSync as Wh,writeFileSync as qh}from"node:fs";import{join as Yh}from"node:path";import{parseDocument as Vh}from"yaml";async function cu(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let s=xa(o);if(!s.ok)throw new Error(s.error);let i=r.get(o.file)??[];i.push({path:s.field.path,value:s.value}),r.set(o.file,i)}let n=[];for(let[o,s]of r){let i=Yh(t,o);if(!Kh(i))throw new Error(`${o} not found in context repo (${t})`);let a=Vh(Wh(i,"utf-8"));for(let c of s)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);qh(i,a.toString()),n.push(o)}return{files:n}}q();import{existsSync as Jh,readFileSync as zh,writeFileSync as Xh}from"node:fs";import{join as Qh}from"node:path";import{isMap as lu,parseDocument as Zh}from"yaml";async function uu(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||!Ea(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=Qh(t,"project.yaml");if(!Jh(o))throw new Error(`project.yaml not found in context repo (${t})`);let s=Zh(zh(o,"utf-8")),i=s.get("repos"),c=(i&&typeof i=="object"&&"items"in i?i.items:[]).find(l=>lu(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!lu(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),Xh(o,s.toString()),{repoName:r,defaultBranch:n}}import{existsSync as Ys,readFileSync as Vs,writeFileSync as ey}from"node:fs";import{join as mo}from"node:path";import{parseDocument as Js}from"yaml";async function du(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 s=mo(t,"project.yaml");if(!Ys(s))throw new Error(`project.yaml not found in context repo (${t})`);let i=Js(Vs(s,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?i.setIn(["youtrack","stage_field"],a):i.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?i.setIn(["youtrack","reject_columns"],a):i.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");i.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?i.setIn(["youtrack","backlog_column"],a):i.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?i.setIn(["youtrack","assignee"],a):i.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&i.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?i.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?i.setIn(["youtrack","backlog_scope"],"shared"):i.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:i.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let s=mo(t,"regimen.yaml");if(!Ys(s))throw new Error(`regimen.yaml not found in context repo (${t})`);let i=Js(Vs(s,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&i.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;i.setIn(["youtrack","writes","enabled"],a.enabled===!0),i.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),i.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),i.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:i.toString()})}if(r.length===0)return{files:[]};for(let s of r)ey(mo(t,s.path),s.content);return{files:r.map(s=>s.path)}}function go(t){if(!t)return"Stage";try{let e=mo(t,"project.yaml");if(!Ys(e))return"Stage";let n=Js(Vs(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}bt();Gt();import{existsSync as mu,readFileSync as gu}from"node:fs";import{join as hu}from"node:path";import{parseDocument as yu}from"yaml";Gt();var un=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Yl(this.cfg,e)}getIssue(e,r){return Vl(this.cfg,e,r??go(this.contextDir))}listComments(e,r){return Jl(this.cfg,e,r)}downloadAttachment(e){return ql(this.cfg,e)}updateStatus(e,r){return Ll(this.cfg,e,r,go(this.contextDir))}addComment(e,r,n){return Ul(this.cfg,e,r)}createIssue(e){return Fl(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,go(this.contextDir))}editIssue(e,r){return Bl(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Gl(this.cfg,e,r,n)}fetchStateFields(e){return Xl(this.cfg,e)}};q();it();import{existsSync as ay,readFileSync as cy}from"node:fs";import{randomBytes as ly}from"node:crypto";import{existsSync as pu,readFileSync as ty,readdirSync as ry}from"node:fs";q();it();function ho(t,e,r){let n=[];for(let o of r){let s=o.issue.key,i=iy(t,s,o.attachments);n.push({path:`tasks/${s}/task.md`,content:ny(o.issue,e,i)}),n.push({path:`tasks/${s}/comments.jsonl`,content:sy(oy(t,s,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${s}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function yo(t,e,r){if(r.length===0)return;let n=ho(t,e,r),o=r.map(s=>s.issue.key);await Xe(t,n,`sync(${o.join(", ")}): task data`)}function ny(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 s of r)o.push(`- [${s}](attachments/${encodeURI(s)})`);o.push("")}return o.join(`
|
|
879
|
+
`)}function oy(t,e,r){let n=new Map,o=oe(t,`tasks/${e}/comments.jsonl`);if(pu(o))for(let s of ty(o,"utf-8").split(`
|
|
880
|
+
`)){let i=s.trim();if(i)try{let a=JSON.parse(i);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let s of r){if(n.has(s.id))continue;let i={id:s.id,author:s.author,origin:"youtrack",body:s.body,createdAt:new Date(s.createdAt).toISOString()},a=Xt(s.body);a&&(i.parsedCommand=a),n.set(s.id,i)}return[...n.values()].sort((s,i)=>s.createdAt.localeCompare(i.createdAt))}function sy(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
740
881
|
`)+(t.length>0?`
|
|
741
|
-
`:"")}function
|
|
882
|
+
`:"")}function iy(t,e,r){let n=[],o=oe(t,`tasks/${e}/attachments`);if(pu(o))for(let s of ry(o))n.push(s);for(let s of r)n.includes(s.name)||n.push(s.name);return n}io();var dn=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Xr(this.contextDir);let r=e.columns??[];return Vc(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Zr(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Qr(this.contextDir,e);return r?Zr(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return fu(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 Xr(this.contextDir),!Qr(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let s={id:`int-${Date.now().toString(36)}-${ly(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},i=Xt(r);i&&(s.parsedCommand=i);let c=[...fu(this.contextDir,e),s].map(l=>JSON.stringify(l)).join(`
|
|
742
883
|
`)+`
|
|
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}eo();function Oi(t){if(!t)return"youtrack";try{let e=Hl(t,"project.yaml");return Gl(e)&&Kl(Fl(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Je(t){let e=Oi(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=xc(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Rh(n);return i?{ok:!0,kind:e,provider:new on(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=il();return r?{ok:!0,kind:e,provider:new nn(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Rh(t){try{let e=Hl(t,"project.yaml");if(!Gl(e))return null;let r=Kl(Fl(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var lo=new Map;async function uo(t,e){let n=(lo.get(t)??Promise.resolve()).catch(()=>{}).then(e);lo.set(t,n);try{return await n}finally{lo.get(t)===n&&lo.delete(t)}}async function Wl(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;Jr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return W("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return uo(`${i}/${r.name}`,async()=>{let s=await Xr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{commit:c}=await Uc(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return ne({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return W("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return uo(`${i}/${r.name}`,async()=>{let s=await Xr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(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,commitMessage:e.commitMessage,push:e.push});return ne({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return W("no repo spec");let i=De(r),s=await i.createPullRequest(r,e);return ne({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return W("no repo spec");let i=De(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ne({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return W("no repo spec");let i=De(r);return await i.closePR(r,e.prNumber,e.comment),ne({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return W("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return uo(`${i}/${r.name}`,async()=>{let s=await Xr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{mergedSha:c}=await Bc(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ne({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return W("no repo spec");let i=t.cloneUrlOverride??Qr(r),a=(await Mc(i)).filter(p=>Gc(p,e.issueKey)),c=De(r),l=null;if(c.findOpenPrByBranch)for(let p of a){let f=await c.findOpenPrByBranch(r,p).catch(()=>null);if(f){l={number:f.number,url:f.url};break}}return ne({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return W("no repo spec");let i=De(r);return await i.addPRComment(r,e.prNumber,e.body),ne({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=Je({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ne({issueId:t.trackerIssueId,newStatus:e.newStatus})):W("no tracker_issue_id provided"):W(i.error)}case"tracker_comment":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);if(!t.trackerIssueId)return W("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ne({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);if(!e.projectKey)return W("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ne({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return W(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ne({applied:s})}case"set_project_setting":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=await Ol(t.contextDir,e.edits);return ne({files:i.files})}case"tracker_edit":{let i=Je({contextDir:t.contextDir});if(!i.ok)return W(i.error);if(!t.contextDir)return W("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await co(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ne({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=await Ll(t.contextDir,e);return ne({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=await Ul(t.contextDir,e);return ne({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ne({reported:!0})):W("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return W("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ne({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return W("no project workspace on this CLI");if(!r)return W("no repo spec");if(!t.onRunActivity)return W("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Wn(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(d=>d.file===`actions/${e.actionId}.yml`);return W(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Js(c,e.input);if(!l.ok)return W(l.error);let p=nc(t.contextDir),f=M(e.projectId),u={};return f?.github?.token&&(u.GH_TOKEN=f.github.token),f?.gitlab?.token&&(u.GITLAB_TOKEN=f.gitlab.token),f?.bitbucket&&(u.BITBUCKET_EMAIL=f.bitbucket.email,u.BITBUCKET_API_TOKEN=f.bitbucket.apiToken),f?.youtrack&&(u.YOUTRACK_URL=f.youtrack.url,u.YOUTRACK_TOKEN=f.youtrack.token),uo(`${e.projectId}/${r.name}`,async()=>{await Xr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=Ie(e.projectId,r.name,t.baseDir),d=await jl({cwd:m,def:c,input:l.values,variables:p,secrets:f?.secrets??{},credEnv:u,onEvent:h=>i(e.runId,h)});return ne({runId:e.runId,status:d.status,exitCode:d.exitCode,...d.failedStep?{failedStep:d.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return W("no context repo clone on this CLI");let i=Nl(t.contextDir,e.path);return ne({path:e.path,...i})}default:return W(`unsupported action type: ${e.type}`)}}catch(i){return W(i instanceof Error?i.message:String(i))}}function ne(t){return{status:"done",result:t}}function W(t){return{status:"failed",error:t}}Ce();Ui();fe();re();import{existsSync as cu,readFileSync as lu}from"node:fs";import{join as uu}from"node:path";async function pu(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)");fo(e.farmId,e.farmPublicKey);let s=M(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await J(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=uu(r,"project.yaml"),m=uu(r,"regimen.yaml");cu(u)&&cu(m)?c={projectYaml:lu(u,"utf-8"),regimenYaml:lu(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},p=it(e.farmPublicKey,JSON.stringify(l));po(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await go(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:p});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:o(f.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}Ce();Ne();Ce();import{homedir as Uh}from"node:os";import{existsSync as Lh,mkdirSync as Bh,readFileSync as Mh,writeFileSync as Gh}from"node:fs";import{dirname as Fh,join as Hh}from"node:path";function Mi(){return K("RUNNER_PINS")??Hh(Uh(),".codepipe","runner-pins.json")}function du(){let t=Mi();if(!Lh(t))return{};try{return JSON.parse(Mh(t,"utf-8"))}catch{return{}}}function Kh(t){let e=Mi();Bh(Fh(e),{recursive:!0}),Gh(e,JSON.stringify(t,null,2)+`
|
|
745
|
-
`,{mode:384})}function Wh(t){return du()[t]}function Gi(t,e){let r=du();r[t]=e,Kh(r)}function fu(t,e){let r=ye(e),n=Wh(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 ${Mi()}.`);return r}fe();re();var gu=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function mu(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:gu(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 qh={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:gu(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)=>mu(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>mu(t,e,r,"remove-token")},hu={api:qh,fetchProject:J,provisionOnRunner:Vl,teardownOnRunner:Jl};async function yu(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)");fu(e.runnerId,e.runnerPublicKey);let i=M(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).filter(c=>c.host==="github");if(a.length===0)throw new Error("the project has no GitHub repositories \u2014 nothing to connect a runner to");return{githubToken:i,repos:a}}async function wu(t,e,r,n=hu){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 yu(t,e,n),a=[];for(let u of s)await n.api.repoHasAdmin(i,u.owner,u.repoName)||a.push(`${u.owner}/${u.repoName}`);if(a.length>0)return o(`the GitHub token lacks admin access on ${a.join(", ")} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on every repository`);let c=[];for(let u of s)c.push({owner:u.owner,repo:u.repoName,regToken:await n.api.mintRegistrationToken(i,u.owner,u.repoName)});let l={projectId:t.projectId,runners:c},p=it(e.runnerPublicKey,JSON.stringify(l));Gi(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 ku(t,e,r,n=hu){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 yu(t,e,n),a=[];for(let f of s)try{a.push({owner:f.owner,repo:f.repoName,removeToken:await n.api.mintRemoveToken(i,f.owner,f.repoName)})}catch(u){r.warn(`[ghr] remove-token for ${f.owner}/${f.repoName} failed (${u instanceof Error?u.message:u}) \u2014 the runner host will force-remove`),a.push({owner:f.owner,repo:f.repoName})}let c={projectId:t.projectId,runners:a},l=it(e.runnerPublicKey,JSON.stringify(c));Gi(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();Y();Ce();re();var bu=16*1024;function Yh(t){return Se.test(t)?pt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Se}`}function $u(t,e,r,n){let o=Yh(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(ir(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>bu)return{ok:!1,detail:`secret value too large (max ${bu} chars)`};try{return Fa(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function vu(t,e){try{return Ha(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 yo=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=De(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof Dt){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=De(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=Vh(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function Vh(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}Y();var wo=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let r=(this.options.resolveProvider??(()=>Je({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let k=e.stageField?{stageField:e.stageField}:{},C=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},T=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(T){let _=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[F,P]=await Promise.all([_.length>0?r.listIssues({projectKey:e.projectKey,columns:_,...k,...C}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...k})]),g=new Map;for(let N of[...F,...P])g.set(N.id,N);o=[...g.values()]}else{let _=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:_,...k,...C})}}catch(k){this.log.warn(`[yt-sync] listIssues failed: ${k instanceof Error?k.message:String(k)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let k of o){if(s.add(k.id),a.has(k.status))continue;let C=await Su(r,k.id,e.sinceMs,this.log);C&&i.set(k.id,C)}let c=[];for(let k of e.offBoardIssueIds){if(s.has(k))continue;let C=await Su(r,k,e.sinceMs,this.log);if(C&&C.length>0&&i.set(k,C),e.requireAssignee||C&&C.length>0){let G=await Xh(r,k,e.stageField,this.log);if(G)c.push(G);else if(C&&C.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(k=>!a.has(k.status)),{attachmentsByIssue:p,attachmentKeys:f}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let u=[...l,...c].map(k=>({issue:k,comments:i.get(k.id)??[],attachments:p.get(k.id)??[]}));try{await co(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let k of f)this.shippedAttachments.add(k)}catch(k){let C=k instanceof Error?k.message:String(k);this.abandonTick(`context task sync failed: ${C}`);return}let m=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[k,C]of i){let G=C.filter(_=>!m(_.id));if(G.length===0)continue;d.push({issueId:k,comments:G.map(Jh)});let T=G.flatMap(_=>{let F=Yt(_.body);return F?[{commentId:_.id,author:_.author,name:F.name,args:F.args,createdAt:_.createdAt}]:[]});T.length>0&&h.push({issueId:k,commands:T})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(xu),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(xu)}:{},observedAtMs:n};this.send(y);let b=d.reduce((k,C)=>k+C.comments.length,0),w=h.reduce((k,C)=>k+C.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${b} commands=${w} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let p of r.get(s.id)??[])a.push(...p.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let p of a){let f=`${s.id}:${p.id}`;if(this.shippedAttachments.has(f))continue;let u;try{u=await n.downloadAttachment(p.url)}catch(d){this.log.warn(`[yt-sync] attachment ${p.name} (${s.id}) download failed: ${d instanceof Error?d.message:String(d)}`);continue}let m=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 xu(t){let{description:e,...r}=t;return r}function Jh(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 Xh(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 Su(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 Fi="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${xe} (protocol ${Fe})`);let n=d=>e.onEvent?.(d),o=e.workspace;o?.contextDir&&sc(o.contextDir,r);let i=Ru("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Ru("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=mo(t.hubUrl,t.cliToken),h=null,y=new yo(i,$=>{d.readyState===d.OPEN&&d.send(JSON.stringify($))},r),b=new wo(s,$=>{d.readyState===d.OPEN&&d.send(JSON.stringify($))},r,{contextDir:o?.contextDir??null,isSelfComment:$=>f.has($)}),w=null,k=async()=>{try{let $={trackerProvider:Oi(o?.contextDir??null)};try{let j=await J(t.hubUrl,t.cliToken,t.projectId);$={...$,repos:j.repos,contextRepo:j.contextRepo}}catch(j){r.warn(`[readiness] could not fetch project summary for push checks: ${j instanceof Error?j.message:String(j)}`)}let E=await xl(t.projectId,$);if(d.readyState!==d.OPEN)return;let x={type:"cli_readiness",projectId:t.projectId,ready:E.ready,checks:E.checks,creds:E.creds,secretNames:Ka(t.projectId),checkedAt:E.checkedAt};if(d.send(JSON.stringify(x)),E.ready)r.info("[readiness] ready");else{let j=E.checks.filter(B=>!B.ok).map(B=>`${B.name}(${B.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${j.join(", ")}`)}}catch($){r.warn(`[readiness] check failed: ${$ instanceof Error?$.message:String($)}`)}},C=()=>{k(),w=setInterval(()=>void k(),a),typeof w.unref=="function"&&w.unref()},G=()=>{w&&(clearInterval(w),w=null)},T=150,_=new Map,F=$=>{let E=_.get($);if(!E||(E.timer&&clearTimeout(E.timer),_.delete($),E.events.length===0||d.readyState!==d.OPEN))return;let x={type:"run_activity",projectId:t.projectId,runId:$,events:E.events};d.send(JSON.stringify(x))},P=($,E)=>{let x=_.get($);if(x||(x={events:[],timer:null},_.set($,x)),x.events.push(E),E.kind==="result"){F($);return}x.timer||(x.timer=setTimeout(()=>F($),T),x.timer.unref?.())},g=o?.contextDir?new qn(o.contextDir,t.projectId,$=>{d.readyState===d.OPEN&&d.send(JSON.stringify($))},r):null,N=async()=>{let $=o?.contextDir;if(!$)throw new Error("no context repo clone on this CLI");let E;try{E=(await J(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let x=await jc($,t.projectId,E,r);return d.readyState===d.OPEN&&d.send(JSON.stringify(x)),x};return d.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let $=Qa(t.projectId),E=K("ORIGIN")==="farm"?"farm":"local",x=K("FARM_ID"),j=t.accountEmail??$.email,B;try{let S=Il(t.projectId);S&&(B=S.publicKey,r.info(`[cred-channel] key fingerprint: ${S.fingerprint}`))}catch(S){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${S instanceof Error?S.message:String(S)}`)}let v={type:"register",projectId:t.projectId,platformVersion:xe,protocolVersion:Fe,accountId:$.accountId,accountLabel:$.label,origin:E,inFlightActionIds:[...p],...j?{accountEmail:j}:{},...E==="farm"&&x?{farmId:x}:{},...B?{sealPublicKey:B}:{}};d.send(JSON.stringify(v))}),d.on("message",async $=>{let E=$.toString("utf-8");if(E==="pong"||E==="ping")return;let x;try{x=JSON.parse(E)}catch{return}if(!x||typeof x!="object")return;let j=x.type;if(j==="registered"){let v=x;if(v.ok){if(r.info(`[ws] registered for project ${v.projectId}`),n({kind:"registered",projectId:v.projectId??t.projectId}),y.start(),g?.start(),C(),Hi(t,o,r),o?.contextDir)try{let S=Xn(o.contextDir,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.outdated&&(r.warn(`[ctx] context format outdated: v${S.templateVersion} \u2192 v${S.currentVersion}`+(S.missingPaths.length>0?` (missing: ${S.missingPaths.join(", ")})`:"")),l||(l=!0,N().catch(()=>{})))}catch(S){r.warn(`[ctx] context-format detect failed (non-fatal): ${S instanceof Error?S.message:String(S)}`)}}else r.warn(`[ws] register rejected: ${v.reason??"unknown"}`),n({kind:"register_rejected",reason:v.reason??"unknown"}),c=!0,d.close();return}if(j==="hello"){let v=x;h=En(v.protocolVersion);let S=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${v.platformVersion} (protocol ${v.protocolVersion}) \u2014 ${S}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${xe}, protocol ${Fe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Fi}`),n({kind:"incompatible",hubVersion:typeof v.platformVersion=="string"?v.platformVersion:null,hubProtocol:typeof v.protocolVersion=="number"?v.protocolVersion:null,updateCommand:Fi}));return}if(j==="tracking_targets"){y.setTargets(x.targets);return}if(j==="youtrack_sync_request"){b.setRequest(x);return}if(j==="youtrack_force_sync"){b.forceSync();return}if(j==="sync_local"){await ry(x,o,d,r);return}if(j==="provision_repo"){let v=x;r.info(`[repo] provision_repo: ${v.repo.name} (${v.repo.host}:${v.repo.owner}/${v.repo.repoName})`),await ey(t,o,v.repo,r),await Hi(t,o,r);return}if(j==="remove_repo"){let v=x;r.info(`[repo] remove_repo: ${v.repoName}${v.purge?" (purge)":""}`),await Hi(t,o,r),v.purge&&ty(t,o,v.repoName,r);return}if(j==="context_write"){await ny(x,o,d,r);return}if(j==="adr_promote"){await oy(x,o,d,r);return}if(j==="cred_update"){let v=x,S=M(t.projectId),H=S?.sealKey?await Cl(t.projectId,v.kind,v.sealed,S.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},te={type:"cred_update_result",updateId:v.updateId,projectId:t.projectId,ok:H.ok,...H.detail?{detail:H.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(te)),H.ok?(r.info(`[cred] ${v.kind} replaced${H.detail?` \u2014 ${H.detail}`:""}`),k()):r.warn(`[cred] ${v.kind} replacement rejected: ${H.detail??"unknown"}`);return}if(j==="move_to_farm"){let v=x;r.info(`[farm-move] request to move ${t.projectId} onto farm ${v.farmName} (${v.farmId})`);let S=await pu(t,v,o?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.ok?r.info(`[farm-move] done \u2014 farm daemon ${S.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${S.error??"unknown error"}`);return}if(j==="gh_runner_setup"){let v=x;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let S=await wu(t,v,r);d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners connected on ${v.runnerName}`):r.warn(`[ghr] setup failed: ${S.error??"see per-repo statuses"}`);return}if(j==="gh_runner_teardown"){let v=x;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let S=await ku(t,v,r);d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners disconnected from ${v.runnerName}`):r.warn(`[ghr] teardown failed: ${S.error??"unknown error"}`);return}if(j==="tracker_fields_request"){let v=x,S={type:"tracker_fields_result",requestId:v.requestId,projectId:t.projectId,ok:!1},H=Je({contextDir:o?.contextDir??null});if(!H.ok)S.error=H.error;else try{S.fields=await H.provider.fetchStateFields(v.projectKey),S.ok=!0}catch(te){S.error=te instanceof Error?te.message:String(te)}d.readyState===d.OPEN&&d.send(JSON.stringify(S)),S.ok||r.warn(`[yt-fields] listing failed: ${S.error??"unknown"}`);return}if(j==="project_secret_update"||j==="project_secret_delete"){let v=x,S;if(v.type==="project_secret_update"){let te=M(t.projectId);S=te?.sealKey?$u(t.projectId,v.name,v.sealed,te.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else S=vu(t.projectId,v.name);let H={type:"project_secret_update_result",updateId:v.updateId,projectId:t.projectId,ok:S.ok,...S.detail?{detail:S.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(H)),S.ok?(r.info(`[secret] ${v.name} ${v.type==="project_secret_update"?"saved":"deleted"}`+(S.detail?` \u2014 ${S.detail}`:"")),k()):r.warn(`[secret] ${v.name} rejected: ${S.detail??"unknown"}`);return}if(j==="sandbox_keys"){let v=M(t.projectId);if(!v){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let S=Xt(t.projectId),H=qc(x,v,S,r);for(let te of H)d.readyState===d.OPEN&&d.send(JSON.stringify(te));return}if(j!=="dispatch_action")return;let B=x;if(h===!1){let v=`refused: HUB protocol incompatible with CLI v${xe} (protocol ${Fe})`;d.send(JSON.stringify({type:"action_result",actionId:B.actionId,status:"failed",error:v})),r.warn(`[exec] ${B.actionId} (${B.action.type}) \u2192 REFUSED: ${v}`),r.warn(`[exec] update the CLI to clear this: ${Fi}`),n({kind:"action",actionId:B.actionId,actionType:B.action.type,ok:!1,error:v});return}p.add(B.actionId);try{let v=await Wl({action:B.action,repo:B.repo,trackerIssueId:B.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:g?()=>g.reportNow():void 0,refreshContextStatus:o?.contextDir?N:void 0,onRunActivity:P}).catch(te=>({status:"failed",error:te instanceof Error?te.message:String(te)}));B.action.type==="tracker_comment"&&v.status==="done"&&"result"in v&&typeof v.result?.commentId=="string"&&f.add(v.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:B.actionId,...v}));let S=v.status!=="failed",H=!S&&"error"in v?v.error:void 0;S?r.info(`[exec] ${B.actionId} (${B.action.type}) \u2192 done`):r.warn(`[exec] ${B.actionId} (${B.action.type}) \u2192 FAILED: ${H??"?"}`),n({kind:"action",actionId:B.actionId,actionType:B.action.type,ok:S,...H?{error:H}:{}})}finally{p.delete(B.actionId)}}),d.on("close",($,E)=>{let x=E?.toString("utf-8")??"";if(r.info(`[ws] closed code=${$}${x?` reason=${x}`:""}`),y.stop(),b.stop(),g?.stop(),G(),x==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:$}),!c&&setTimeout(()=>{u=m()},2e3)}),d.on("error",$=>r.warn(`[ws] error: ${$.message}`)),d}return{stop(){c=!0,u.close()}}}async function Hi(t,e,r){try{let n=await J(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Vr(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 ey(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?cn(e.root,o):Ie(t.projectId,r.name);if(Tu(cn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await Zh().clone(Qr(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 ty(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?cn(e.root,o):Ie(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Tu(cn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Qh(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 ry(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=cn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Za(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 ny(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await ot(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function oy(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 fc(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 Ru(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}fe();re();nt();Wi();tt();oo();async function Lu(t={profile:void 0}){let{cfg:e,profile:r}=Mn(t.profile),n=M(e.projectId);n&&Fr(n),en(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),tn(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),rn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=ln(qi(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Hn("CLI_LOG",i,o);if(s.enabled){let u=new Zt(s);Kn(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=Ln(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=ln(qi(),".codepipe",r?ln("profiles",r,"context"):"context");if(await Bi(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Du(()=>$o({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 Bi(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=ln(qi(),".codepipe",r?ln("profiles",r,"context-config"):"context-config");Yn(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(()=>{})}br();ke();fe();async function Kp(t={profile:void 0}){let e=Te(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=mo(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`)")}yn();import{readFileSync as Fk}from"node:fs";Y();ke();nt();Eo();Ut();wt();Lt();fe();re();function pe(t){throw new Error(t)}function de(t,e){return(typeof t!="string"||t.trim().length===0)&&pe(`config: '${e}' must be a non-empty string`),t.trim()}function kn(t,e){if(t==null)return;typeof t!="string"&&pe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Hk(t){(!t||typeof t!="object")&&pe("config: expected a JSON object");let e=t,r=de(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||pe("config: 'hubUrl' must start with http(s)://");let n=de(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&pe("config: 'project' is required");let i=o,s=de(i.id,"project.id");At.test(s)||pe("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=de(i.name,"project.name"),c=de(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&pe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||pe("config: 'project.repos' must be an array");let p=l.map((w,k)=>{(!w||typeof w!="object")&&pe(`config: project.repos[${k}] must be an object`);let C=w,G=de(C.host,`project.repos[${k}].host`);G!=="github"&&G!=="bitbucket"&&G!=="gitlab"&&pe(`config: project.repos[${k}].host must be 'github', 'bitbucket' or 'gitlab'`);let T={name:de(C.name,`project.repos[${k}].name`),host:G,owner:de(C.owner,`project.repos[${k}].owner`),repoName:de(C.repoName,`project.repos[${k}].repoName`)},_=kn(C.defaultBranch,`project.repos[${k}].defaultBranch`);_&&(T.defaultBranch=_);let F=kn(C.mountAs,`project.repos[${k}].mountAs`);return F&&(T.mountAs=F),T}),f=i.contextRepo;(!f||typeof f!="object")&&pe("config: 'project.contextRepo' is required");let u=f,m=kn(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&pe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:m,owner:de(u.owner,"project.contextRepo.owner"),name:kn(u.name,"project.contextRepo.name")??et(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:d}},y=kn(i.youtrackProjectKey,"project.youtrackProjectKey");y&&(h.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&pe("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&pe("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites);let b=e.secrets;if(b!==void 0){(typeof b!="object"||b===null)&&pe("config: 'secrets' must be an object");let w=b,k={};if(w.github){let C=w.github;k.github={token:de(C.token,"secrets.github.token")}}if(w.bitbucket){let C=w.bitbucket;k.bitbucket={email:de(C.email,"secrets.bitbucket.email"),apiToken:de(C.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let C=w.gitlab;k.gitlab={token:de(C.token,"secrets.gitlab.token")}}if(w.youtrack){let C=w.youtrack;k.youtrack={url:de(C.url,"secrets.youtrack.url").replace(/\/$/,""),token:de(C.token,"secrets.youtrack.token")}}if(w.contextWrite){let C=w.contextWrite;k.contextWrite={token:de(C.token,"secrets.contextWrite.token")}}h.secrets=k}return h}async function Kk(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Wk(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 Zn(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 _d(t){let e=!t.configPath||t.configPath==="-"?await Kk():Fk(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){pe(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=Hk(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 Wk(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 vr(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Qt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){pe(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let p;try{p=await vt(o,i,a)}catch(u){if(u instanceof O&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await J(o,i,s.id);else if(u instanceof O)pe(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let f={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(Q(f),rt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${qe(s.id)}`),Ot(s.id,Ve(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await an(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 Nd,intro as Od,isCancel as Dd,log as fs,outro as qk,password as Ud}from"@clack/prompts";async function Yk(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Ld(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Yk(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Od("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),fs.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Ud({message:"Claude OAuth token"});Dd(i)&&(Nd("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),qa({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Fn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Te(t.profile);if(!e){Od(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),fs.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Ud({message:"Claude OAuth token"});Dd(i)&&(Nd("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=M(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},Q(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(fs.success("Claude OAuth token saved."),qk("It will be sealed into job bundles when a SANDBOX (re)connects."))}Y();ke();nt();Eo();Ut();Po();fe();re();import{cancel as Vk,confirm as Jk,intro as zk,isCancel as Bd,log as he,outro as Xk,select as Md,text as Ct}from"@clack/prompts";function Gd(t){Vk(t),process.exit(1)}function Er(t){return Bd(t)&&Gd("aborted"),t}function bn(t){return Bd(t)&&Gd("aborted"),typeof t=="string"?t:""}async function Qk(t,e){let r=Er(await Md({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=bn(await Ct({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=bn(await Ct({message:"Context Repo name",placeholder:et(t),initialValue:et(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Fd(t={profile:void 0}){let e=Te(t.profile);zk(`codepipe project add \u2192 ${e.hubUrl}`);let r=Er(await Ct({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>At.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Er(await Ct({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=Er(await Md({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=Er(await Ct({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Er(await Jk({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=bn(await Ct({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:b=>!b||!b.trim()||Pe(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=Pe(u);he.message(`${m.host}: ${m.owner}/${m.repoName}`);let d=bn(await Ct({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:b=>b.trim().length>0?void 0:"required"})).trim(),h=bn(await Ct({message:"default branch (optional)",placeholder:"main"})).trim(),y={name:d,host:m.host,owner:m.owner,repoName:m.repoName};h&&(y.defaultBranch=h),a.push(y)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Qk(r,a),p=M(e.projectId);he.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await vr(c,l,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??Qt(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>he.message(u),warn:u=>he.warn(u)}})}catch(u){he.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=f,he.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await vt(e.hubUrl,e.cliToken,c);he.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Ot(r,Ve(c,s,p?.youtrack?.url),{info:m=>he.message(m),warn:m=>he.warn(m)}),u.contextRepo&&(he.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),he.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&he.error(` error: ${u.provisioningError}`),Xk("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)}}br();ke();fe();re();tt();yn();import{existsSync as Zk,rmSync as eb}from"node:fs";import{confirm as tb,intro as rb,isCancel as nb,log as Et,outro as ob,spinner as ib}from"@clack/prompts";function ze(t){Et.error(t),process.exit(1)}var Hd=t=>t.trim().replace(/\/+$/,"");async function Kd(t){rb("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Re()?.spec.projectId??void 0;e||ze("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Oe(e);r||ze(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Hd(r.hubUrl),o=r.projectId,i=Hd(t.hub);i.startsWith("http")||ze("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&ze(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let b=ib();b.start(`reading project ${o} from ${n}\u2026`);try{l=await J(n,r.cliToken,o),b.stop(`read project ${o} (${l.name})`)}catch(w){throw b.stop("could not read the source project",1),w instanceof O&&ze(`source HUB ${n} \u2192 ${w.status} ${w.message}. The source HUB must be reachable with a valid token to move a project.`),w}}l.contextRepo||ze(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let p=M(o),f=(t.account??r.accountEmail??await Ir()).trim().toLowerCase();if(Et.message(`move project '${o}'
|
|
884
|
+
`;return await Xe(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:s.id}}async createIssue(e){let r=new Date().toISOString(),n=await Jc(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,s=>{let i=s.links.filter(a=>!(a.type===o&&a.targetKey===n));return i.push({type:o,targetKey:n}),{...s,links:i}})}async fetchStateFields(e){return[{name:"Status",values:us.statusColumns}]}async mutateRecord(e,r,n){let o=Qr(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let s={...r(o),updated:new Date().toISOString()},i=Zr(this.contextDir,s,{withDescription:!0});n!==void 0&&(n.trim().length>0?i.description=n:delete i.description);let a=[{path:qr(e),content:Ns(s)},...ho(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])];await Xe(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Bn,status:r.targetStatus,links:[],created:n,updated:n},s=Zr(this.contextDir,o);return r.body.trim().length>0&&(s.description=r.body),[{path:qr(e),content:Ns(o)},...ho(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])]}};function fu(t,e){let r=oe(t,`tasks/${e}/comments.jsonl`);if(!ay(r))return[];let n=[];for(let o of cy(r,"utf-8").split(`
|
|
885
|
+
`)){let s=o.trim();if(s)try{let i=JSON.parse(s);i&&typeof i.id=="string"&&typeof i.body=="string"&&n.push(i)}catch{}}return n}io();function zs(t){if(!t)return"youtrack";try{let e=hu(t,"project.yaml");return mu(e)&&yu(gu(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Be(t){let e=zs(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=qc(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let s=uy(n);return s?{ok:!0,kind:e,provider:new dn(n,s,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Ol();return r?{ok:!0,kind:e,provider:new un(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function uy(t){try{let e=hu(t,"project.yaml");if(!mu(e))return null;let r=yu(gu(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var wo=new Map;async function bo(t,e){let n=(wo.get(t)??Promise.resolve()).catch(()=>{}).then(e);wo.set(t,n);try{return await n}finally{wo.get(t)===n&&wo.delete(t)}}async function wu(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;rn(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return W("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return bo(`${s}/${r.name}`,async()=>{let i=await Ft(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=we(s,r.name,t.baseDir),{commit:c}=await ul(i,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return se({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return W("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return bo(`${s}/${r.name}`,async()=>{let i=await Ft(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=we(s,r.name,t.baseDir),{commit:c,pushed:l}=await dl(i,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return se({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return W("no repo spec");let s=Le(r),i=await s.createPullRequest(r,e);return se({url:i.url,number:i.number,host:s.name})}case"merge_pr":{if(!r)return W("no repo spec");let s=Le(r),i=await s.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return se({prNumber:e.prNumber,host:s.name,...i.mergedSha?{mergedSha:i.mergedSha}:{}})}case"close_pr":{if(!r)return W("no repo spec");let s=Le(r);return await s.closePR(r,e.prNumber,e.comment),se({prNumber:e.prNumber,host:s.name})}case"merge_branch":{if(!r)return W("no repo spec");let s=e.taskId.split(":",2)[0]??"?";return bo(`${s}/${r.name}`,async()=>{let i=await Ft(s,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=we(s,r.name,t.baseDir),{mergedSha:c}=await pl(i,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return se({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return W("no repo spec");let s=t.cloneUrlOverride??on(r),a=(await fl(s)).filter(d=>ml(d,e.issueKey)),c=Le(r),l=null;if(c.findOpenPrByBranch)for(let d of a){let f=await c.findOpenPrByBranch(r,d).catch(()=>null);if(f){l={number:f.number,url:f.url};break}}return se({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return W("no repo spec");let s=Le(r);return await s.addPRComment(r,e.prNumber,e.body),se({prNumber:e.prNumber,host:s.name})}case"tracker_status":{let s=Be({contextDir:t.contextDir});return s.ok?t.trackerIssueId?(await s.provider.updateStatus(t.trackerIssueId,e.newStatus),se({issueId:t.trackerIssueId,newStatus:e.newStatus})):W("no tracker_issue_id provided"):W(s.error)}case"tracker_comment":{let s=Be({contextDir:t.contextDir});if(!s.ok)return W(s.error);if(!t.trackerIssueId)return W("no tracker_issue_id provided");let i=await s.provider.addComment(t.trackerIssueId,e.body,e.author);return se({issueId:t.trackerIssueId,commentId:i.id})}case"create_tracker_issue":{let s=Be({contextDir:t.contextDir});if(!s.ok)return W(s.error);if(!e.projectKey)return W("no projectKey in create_tracker_issue action");let{id:i,key:a}=await s.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return se({issueKey:a,issueId:i})}case"apply_tracker_links":{let s=Be({contextDir:t.contextDir});if(!s.ok)return W(s.error);let i=0;for(let a of e.links)try{await s.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),i++}catch(c){return W(`${c instanceof Error?c.message:String(c)} (applied ${i}/${e.links.length})`)}return se({applied:i})}case"set_project_setting":{if(!t.contextDir)return W("no context repo clone on this CLI");let s=await cu(t.contextDir,e.edits);return se({files:s.files})}case"tracker_edit":{let s=Be({contextDir:t.contextDir});if(!s.ok)return W(s.error);if(!t.contextDir)return W("no context repo clone on this CLI");await s.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let i=await s.provider.getIssue(e.issueKey);return i&&await yo(t.contextDir,e.projectId,[{issue:i,comments:[],attachments:[]}]),se({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return W("no context repo clone on this CLI");let s=await du(t.contextDir,e);return se({files:s.files})}case"set_repo_default_branch":{if(!t.contextDir)return W("no context repo clone on this CLI");let s=await uu(t.contextDir,e);return se({repoName:s.repoName,defaultBranch:s.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),se({reported:!0})):W("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return W("no context repo clone on this CLI");let s=await t.refreshContextStatus();return se({outdated:s.outdated,templateVersion:s.templateVersion})}case"run_action":{if(!t.contextDir)return W("no project workspace on this CLI");if(!r)return W("no repo spec");if(!t.onRunActivity)return W("no run-activity stream on this CLI");let s=t.onRunActivity,{defs:i,errors:a}=Xn(t.contextDir),c=i.find(m=>m.id===e.actionId);if(!c){let m=a.find(p=>p.file===`actions/${e.actionId}.yml`);return W(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=wa(c,e.input);if(!l.ok)return W(l.error);let d=Ic(t.contextDir),f=G(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),bo(`${e.projectId}/${r.name}`,async()=>{await Ft(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=we(e.projectId,r.name,t.baseDir),p=await au({cwd:m,def:c,input:l.values,variables:d,secrets:f?.secrets??{},credEnv:u,onEvent:h=>s(e.runId,h)});return se({runId:e.runId,status:p.status,exitCode:p.exitCode,...p.failedStep?{failedStep:p.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return W("no context repo clone on this CLI");let s=lo(t.contextDir,e.path);return se({path:e.path,...s})}default:return W(`unsupported action type: ${e.type}`)}}catch(s){return W(s instanceof Error?s.message:String(s))}}function se(t){return{status:"done",result:t}}function W(t){return{status:"failed",error:t}}Ee();Qs();me();ne();import{existsSync as Ou,readFileSync as Du}from"node:fs";import{join as Lu}from"node:path";async function Uu(t,e,r,n){let o=s=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let s=be(e.farmPublicKey);if(s!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");$o(e.farmId,e.farmPublicKey);let i=G(t.projectId);if(!i)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await J(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=Lu(r,"project.yaml"),m=Lu(r,"regimen.yaml");Ou(u)&&Ou(m)?c={projectYaml:Du(u,"utf-8"),regimenYaml:Du(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:{...i.github?{github:i.github}:{},...i.bitbucket?{bitbucket:i.bitbucket}:{},...i.gitlab?{gitlab:i.gitlab}:{},...i.youtrack?{youtrack:i.youtrack}:{},...i.claude?{claude:i.claude}:{},...i.contextWrite?{contextWrite:i.contextWrite}:{},...i.contextSsh?{contextSsh:i.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},d=at(e.farmPublicKey,JSON.stringify(l));ko(e.farmId,s),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${s}) \u2014 handing off`);let f=await xo(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:d});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(s){return o(s instanceof Error?s.message:String(s))}}Ee();Oe();Ee();import{homedir as vy}from"node:os";import{existsSync as xy,mkdirSync as Sy,readFileSync as Ry,writeFileSync as Iy}from"node:fs";import{dirname as Ty,join as Cy}from"node:path";function ti(){return K("RUNNER_PINS")??Cy(vy(),".codepipe","runner-pins.json")}function Bu(){let t=ti();if(!xy(t))return{};try{return JSON.parse(Ry(t,"utf-8"))}catch{return{}}}function Ey(t){let e=ti();Sy(Ty(e),{recursive:!0}),Iy(e,JSON.stringify(t,null,2)+`
|
|
886
|
+
`,{mode:384})}function Py(t){return Bu()[t]}function ri(t,e){let r=Bu();r[t]=e,Ey(r)}function Mu(t,e){let r=be(e),n=Py(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 ${ti()}.`);return r}me();ne();var Gu=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Fu(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Gu(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let s=await o.json();if(!s.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return s.token}var jy={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Gu(t)});if(!n.ok)throw new Error(`github GET /repos/${e}/${r}: HTTP ${n.status}`);return(await n.json()).permissions?.admin===!0},mintRegistrationToken:(t,e,r)=>Fu(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Fu(t,e,r,"remove-token")},Hu={api:jy,fetchProject:J,provisionOnRunner:$u,teardownOnRunner:vu};async function Ku(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(be(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Mu(e.runnerId,e.runnerPublicKey);let s=G(t.projectId)?.github?.token;if(!s)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:s,repos:a}}async function Wu(t,e,r,n=Hu){let o=s=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{let{githubToken:s,repos:i}=await Ku(t,e,n),a=[];for(let u of i)await n.api.repoHasAdmin(s,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 i)c.push({owner:u.owner,repo:u.repoName,regToken:await n.api.mintRegistrationToken(s,u.owner,u.repoName)});let l={projectId:t.projectId,runners:c},d=at(e.runnerPublicKey,JSON.stringify(l));ri(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:d});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(s){return o(s instanceof Error?s.message:String(s))}}async function qu(t,e,r,n=Hu){let o=s=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:s});try{let{githubToken:s,repos:i}=await Ku(t,e,n),a=[];for(let f of i)try{a.push({owner:f.owner,repo:f.repoName,removeToken:await n.api.mintRemoveToken(s,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=at(e.runnerPublicKey,JSON.stringify(c));ri(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle sealed for runner host ${e.runnerName} \u2014 handing off`);let d=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:d.ok,...d.error?{error:d.error}:{}}}catch(s){return o(s instanceof Error?s.message:String(s))}}me();q();Ee();ne();var Yu=16*1024;function Ay(t){return Ie.test(t)?ft(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ie}`}function Vu(t,e,r,n){let o=Ay(e);if(o)return{ok:!1,detail:o};let s;try{let i=JSON.parse(ur(n,r).toString("utf-8"));if(typeof i.value!="string"||i.value.length===0)return{ok:!1,detail:"payload has no value"};s=i.value}catch(i){return{ok:!1,detail:`cannot open the sealed secret (${i instanceof Error?i.message:String(i)}) \u2014 wrong channel key?`}}if(s.length>Yu)return{ok:!1,detail:`secret value too large (max ${Yu} chars)`};try{return dc(t,e,s),{ok:!0}}catch(i){return{ok:!1,detail:i instanceof Error?i.message:String(i)}}}function Ju(t,e){try{return pc(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)}}}ne();bt();var Ro=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 i of r.prs){let a=Le(i.repoSpec);try{let c=await a.getPullRequest(i.repoSpec,i.number);n.push({number:i.number,url:i.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof Bt){this.log.warn(`[track] task=${e} pr=${i.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${i.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(i=>`${i.number}:${i.state}:${i.merged?1:0}:${i.ci}:${i.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let i=0;i<n.length;i++){let a=n[i];if(a.ci!=="failed")continue;let c=Le(r.prs[i].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[i].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 s=_y(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function _y(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 Io=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??(()=>Be({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 b=e.stageField?{stageField:e.stageField}:{},T=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},x=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(x){let A=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[O,P]=await Promise.all([A.length>0?r.listIssues({projectKey:e.projectKey,columns:A,...b,...T}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...b})]),g=new Map;for(let N of[...O,...P])g.set(N.id,N);o=[...g.values()]}else{let A=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:A,...b,...T})}}catch(b){this.log.warn(`[yt-sync] listIssues failed: ${b instanceof Error?b.message:String(b)}`);return}let s=new Map,i=new Set,a=new Set(e.doneColumns??[]);for(let b of o){if(i.add(b.id),a.has(b.status))continue;let T=await Xu(r,b.id,e.sinceMs,this.log);T&&s.set(b.id,T)}let c=[];for(let b of e.offBoardIssueIds){if(i.has(b))continue;let T=await Xu(r,b,e.sinceMs,this.log);if(T&&T.length>0&&s.set(b,T),e.requireAssignee||T&&T.length>0){let L=await Dy(r,b,e.stageField,this.log);if(L)c.push(L);else if(T&&T.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(b=>!a.has(b.status)),{attachmentsByIssue:d,attachmentKeys:f}=await this.collectAttachments(l,s,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(b=>({issue:b,comments:s.get(b.id)??[],attachments:d.get(b.id)??[]}));try{await yo(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let b of f)this.shippedAttachments.add(b)}catch(b){let T=b instanceof Error?b.message:String(b);this.abandonTick(`context task sync failed: ${T}`);return}let m=this.options.isSelfComment??(()=>!1),p=[],h=[];for(let[b,T]of s){let L=T.filter(A=>!m(A.id));if(L.length===0)continue;p.push({issueId:b,comments:L.map(Ny)});let x=L.flatMap(A=>{let O=Xt(A.body);return O?[{commentId:A.id,author:A.author,name:O.name,args:O.args,createdAt:A.createdAt}]:[]});x.length>0&&h.push({issueId:b,commands:x})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(zu),commentsBatch:p,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(zu)}:{},observedAtMs:n};this.send(y);let k=p.reduce((b,T)=>b+T.comments.length,0),w=h.reduce((b,T)=>b+T.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${k} 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,s=[];for(let i of e){let a=[...i.attachments??[]];for(let d of r.get(i.id)??[])a.push(...d.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let d of a){let f=`${i.id}:${d.id}`;if(this.shippedAttachments.has(f))continue;let u;try{u=await n.downloadAttachment(d.url)}catch(p){this.log.warn(`[yt-sync] attachment ${d.name} (${i.id}) download failed: ${p instanceof Error?p.message:String(p)}`);continue}let m=Oy(d.name);l.has(m)&&(m=`${d.id}-${m}`),l.add(m),c.push({name:m,contentBase64:u.toString("base64")}),s.push(f)}c.length>0&&o.set(i.id,c)}return{attachmentsByIssue:o,attachmentKeys:s}}};function zu(t){let{description:e,...r}=t;return r}function Ny(t){let{body:e,...r}=t;return r}function Oy(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 Dy(t,e,r,n){try{return await t.getIssue(e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Xu(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var ni="npm i -g @code-partner/codepipe@latest";function To(t,e={}){let r=e.log??{info:p=>console.log(p),warn:p=>console.warn(p)};r.info(`codepipe-cli v${Re} (protocol ${Ke})`);let n=p=>e.onEvent?.(p),o=e.workspace;o?.contextDir&&Ec(o.contextDir,r);let s=Qu("CLI_TRACKING_POLL_INTERVAL_SEC"),i=Qu("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let p=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(p)&&p>0?p*1e3:6e5})(),c=!1,l=!1,d=new Set,f=new Set,u=m();function m(){let p=vo(t.hubUrl,t.cliToken),h=null,y=new Ro(s,$=>{p.readyState===p.OPEN&&p.send(JSON.stringify($))},r),k=new Io(i,$=>{p.readyState===p.OPEN&&p.send(JSON.stringify($))},r,{contextDir:o?.contextDir??null,isSelfComment:$=>f.has($)}),w=null,b=async()=>{try{let $={trackerProvider:zs(o?.contextDir??null)};try{let j=await J(t.hubUrl,t.cliToken,t.projectId);$={...$,repos:j.repos,contextRepo:j.contextRepo}}catch(j){r.warn(`[readiness] could not fetch project summary for push checks: ${j instanceof Error?j.message:String(j)}`)}let E=await Zl(t.projectId,$);if(p.readyState!==p.OPEN)return;let S={type:"cli_readiness",projectId:t.projectId,ready:E.ready,checks:E.checks,creds:E.creds,secretNames:fc(t.projectId),checkedAt:E.checkedAt};if(p.send(JSON.stringify(S)),E.ready)r.info("[readiness] ready");else{let j=E.checks.filter(F=>!F.ok).map(F=>`${F.name}(${F.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${j.join(", ")}`)}}catch($){r.warn(`[readiness] check failed: ${$ instanceof Error?$.message:String($)}`)}},T=()=>{b(),w=setInterval(()=>void b(),a),typeof w.unref=="function"&&w.unref()},L=()=>{w&&(clearInterval(w),w=null)},x=150,A=new Map,O=$=>{let E=A.get($);if(!E||(E.timer&&clearTimeout(E.timer),A.delete($),E.events.length===0||p.readyState!==p.OPEN))return;let S={type:"run_activity",projectId:t.projectId,runId:$,events:E.events};p.send(JSON.stringify(S))},P=($,E)=>{let S=A.get($);if(S||(S={events:[],timer:null},A.set($,S)),S.events.push(E),E.kind==="result"){O($);return}S.timer||(S.timer=setTimeout(()=>O($),x),S.timer.unref?.())},g=o?.contextDir?new Qn(o.contextDir,t.projectId,$=>{p.readyState===p.OPEN&&p.send(JSON.stringify($))},r):null,N=async()=>{let $=o?.contextDir;if(!$)throw new Error("no context repo clone on this CLI");let E;try{E=(await J(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let S=await el($,t.projectId,E,r);return p.readyState===p.OPEN&&p.send(JSON.stringify(S)),S};return p.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let $=$c(t.projectId),E=K("ORIGIN")==="farm"?"farm":"local",S=K("FARM_ID"),j=t.accountEmail??$.email,F;try{let R=nu(t.projectId);R&&(F=R.publicKey,r.info(`[cred-channel] key fingerprint: ${R.fingerprint}`))}catch(R){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${R instanceof Error?R.message:String(R)}`)}let v={type:"register",projectId:t.projectId,platformVersion:Re,protocolVersion:Ke,accountId:$.accountId,accountLabel:$.label,origin:E,inFlightActionIds:[...d],...j?{accountEmail:j}:{},...E==="farm"&&S?{farmId:S}:{},...F?{sealPublicKey:F}:{}};p.send(JSON.stringify(v))}),p.on("message",async $=>{let E=$.toString("utf-8");if(E==="pong"||E==="ping")return;let S;try{S=JSON.parse(E)}catch{return}if(!S||typeof S!="object")return;let j=S.type;if(j==="registered"){let v=S;if(v.ok){if(r.info(`[ws] registered for project ${v.projectId}`),n({kind:"registered",projectId:v.projectId??t.projectId}),y.start(),g?.start(),T(),oi(t,o,r),o?.contextDir)try{let R=no(o.contextDir,t.projectId);p.readyState===p.OPEN&&p.send(JSON.stringify(R)),R.outdated&&(r.warn(`[ctx] context format outdated: v${R.templateVersion} \u2192 v${R.currentVersion}`+(R.missingPaths.length>0?` (missing: ${R.missingPaths.join(", ")})`:"")),l||(l=!0,N().catch(()=>{})))}catch(R){r.warn(`[ctx] context-format detect failed (non-fatal): ${R instanceof Error?R.message:String(R)}`)}}else r.warn(`[ws] register rejected: ${v.reason??"unknown"}`),n({kind:"register_rejected",reason:v.reason??"unknown"}),c=!0,p.close();return}if(j==="hello"){let v=S;h=Nn(v.protocolVersion);let R=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${v.platformVersion} (protocol ${v.protocolVersion}) \u2014 ${R}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Re}, protocol ${Ke}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${ni}`),n({kind:"incompatible",hubVersion:typeof v.platformVersion=="string"?v.platformVersion:null,hubProtocol:typeof v.protocolVersion=="number"?v.protocolVersion:null,updateCommand:ni}));return}if(j==="tracking_targets"){y.setTargets(S.targets);return}if(j==="youtrack_sync_request"){k.setRequest(S);return}if(j==="youtrack_force_sync"){k.forceSync();return}if(j==="sync_local"){await Gy(S,o,p,r);return}if(j==="provision_repo"){let v=S;r.info(`[repo] provision_repo: ${v.repo.name} (${v.repo.host}:${v.repo.owner}/${v.repo.repoName})`),await My(t,o,v.repo,r),await oi(t,o,r);return}if(j==="remove_repo"){let v=S;r.info(`[repo] remove_repo: ${v.repoName}${v.purge?" (purge)":""}`),await oi(t,o,r),v.purge&&Fy(t,o,v.repoName,r);return}if(j==="context_write"){await Hy(S,o,p,r);return}if(j==="adr_promote"){await Wy(S,o,p,r);return}if(j==="model_detail_request"){await Ky(S,o,t,p,r);return}if(j==="cred_update"){let v=S,R=G(t.projectId),H=R?.sealKey?await ou(t.projectId,v.kind,v.sealed,R.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},te={type:"cred_update_result",updateId:v.updateId,projectId:t.projectId,ok:H.ok,...H.detail?{detail:H.detail}:{}};p.readyState===p.OPEN&&p.send(JSON.stringify(te)),H.ok?(r.info(`[cred] ${v.kind} replaced${H.detail?` \u2014 ${H.detail}`:""}`),b()):r.warn(`[cred] ${v.kind} replacement rejected: ${H.detail??"unknown"}`);return}if(j==="move_to_farm"){let v=S;r.info(`[farm-move] request to move ${t.projectId} onto farm ${v.farmName} (${v.farmId})`);let R=await Uu(t,v,o?.contextDir,r);p.readyState===p.OPEN&&p.send(JSON.stringify(R)),R.ok?r.info(`[farm-move] done \u2014 farm daemon ${R.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${R.error??"unknown error"}`);return}if(j==="gh_runner_setup"){let v=S;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let R=await Wu(t,v,r);p.readyState===p.OPEN&&p.send(JSON.stringify(R)),R.ok?r.info(`[ghr] runners connected on ${v.runnerName}`):r.warn(`[ghr] setup failed: ${R.error??"see per-repo statuses"}`);return}if(j==="gh_runner_teardown"){let v=S;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${v.runnerName} (${v.runnerId})`);let R=await qu(t,v,r);p.readyState===p.OPEN&&p.send(JSON.stringify(R)),R.ok?r.info(`[ghr] runners disconnected from ${v.runnerName}`):r.warn(`[ghr] teardown failed: ${R.error??"unknown error"}`);return}if(j==="tracker_fields_request"){let v=S,R={type:"tracker_fields_result",requestId:v.requestId,projectId:t.projectId,ok:!1},H=Be({contextDir:o?.contextDir??null});if(!H.ok)R.error=H.error;else try{R.fields=await H.provider.fetchStateFields(v.projectKey),R.ok=!0}catch(te){R.error=te instanceof Error?te.message:String(te)}p.readyState===p.OPEN&&p.send(JSON.stringify(R)),R.ok||r.warn(`[yt-fields] listing failed: ${R.error??"unknown"}`);return}if(j==="project_secret_update"||j==="project_secret_delete"){let v=S,R;if(v.type==="project_secret_update"){let te=G(t.projectId);R=te?.sealKey?Vu(t.projectId,v.name,v.sealed,te.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else R=Ju(t.projectId,v.name);let H={type:"project_secret_update_result",updateId:v.updateId,projectId:t.projectId,ok:R.ok,...R.detail?{detail:R.detail}:{}};p.readyState===p.OPEN&&p.send(JSON.stringify(H)),R.ok?(r.info(`[secret] ${v.name} ${v.type==="project_secret_update"?"saved":"deleted"}`+(R.detail?` \u2014 ${R.detail}`:"")),b()):r.warn(`[secret] ${v.name} rejected: ${R.detail??"unknown"}`);return}if(j==="sandbox_keys"){let v=G(t.projectId);if(!v){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let R=tr(t.projectId),H=vl(S,v,R,r);for(let te of H)p.readyState===p.OPEN&&p.send(JSON.stringify(te));return}if(j!=="dispatch_action")return;let F=S;if(h===!1){let v=`refused: HUB protocol incompatible with CLI v${Re} (protocol ${Ke})`;p.send(JSON.stringify({type:"action_result",actionId:F.actionId,status:"failed",error:v})),r.warn(`[exec] ${F.actionId} (${F.action.type}) \u2192 REFUSED: ${v}`),r.warn(`[exec] update the CLI to clear this: ${ni}`),n({kind:"action",actionId:F.actionId,actionType:F.action.type,ok:!1,error:v});return}d.add(F.actionId);try{let v=await wu({action:F.action,repo:F.repo,trackerIssueId:F.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:g?()=>g.reportNow():void 0,refreshContextStatus:o?.contextDir?N:void 0,onRunActivity:P}).catch(te=>({status:"failed",error:te instanceof Error?te.message:String(te)}));F.action.type==="tracker_comment"&&v.status==="done"&&"result"in v&&typeof v.result?.commentId=="string"&&f.add(v.result.commentId),p.send(JSON.stringify({type:"action_result",actionId:F.actionId,...v}));let R=v.status!=="failed",H=!R&&"error"in v?v.error:void 0;R?r.info(`[exec] ${F.actionId} (${F.action.type}) \u2192 done`):r.warn(`[exec] ${F.actionId} (${F.action.type}) \u2192 FAILED: ${H??"?"}`),n({kind:"action",actionId:F.actionId,actionType:F.action.type,ok:R,...H?{error:H}:{}})}finally{d.delete(F.actionId)}}),p.on("close",($,E)=>{let S=E?.toString("utf-8")??"";if(r.info(`[ws] closed code=${$}${S?` reason=${S}`:""}`),y.stop(),k.stop(),g?.stop(),L(),S==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:$}),!c&&setTimeout(()=>{u=m()},2e3)}),p.on("error",$=>r.warn(`[ws] error: ${$.message}`)),p}return{stop(){c=!0,u.close()}}}async function oi(t,e,r){try{let n=await J(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:s}=tn(t.projectId,n.repos,e?.contextDir);for(let i of o)r.info(`[repo] restaged repo set in ${i}`);for(let i of s)r.warn(`[repo] could not restage ${i.path}: ${i.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function My(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 s=e?pr(e.root,o):we(t.projectId,r.name);if(Zu(pr(s,".git"))){n.info(`[repo] ${r.name} already present at ${s}`);return}try{await By().clone(on(r),s),n.info(`[repo] cloned ${r.name} \u2192 ${s}`)}catch(i){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${i instanceof Error?i.message.trim():String(i)}`)}}function Fy(t,e,r,n){let o=e?.repos.find(i=>i.name===r)?.mountAs??r,s=e?pr(e.root,o):we(t.projectId,r);if(e&&s===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Zu(pr(s,".git"))){n.info(`[repo] no local clone to purge for ${r} (${s})`);return}try{Uy(s,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${s}`)}catch(i){n.warn(`[repo] purge of ${s} failed: ${i instanceof Error?i.message:String(i)}`)}}async function Gy(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 s=e.repos.find(l=>l.name===o.repoName),i=pr(e.root,s?.mountAs??o.repoName),a=s?.defaultBranch??o.defaultBranch,c=await vc(i,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 Hy(t,e,r,n){let o=(s,i)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:s};i&&(a.error=i),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{if(t.files.some(s=>en(s.path))){let s=t.files.filter(a=>en(a.path)).length,i=nl(e.contextDir,t.files,n.warn);await Xe(e.contextDir,i,t.message),n.info(`[ctx] context_write ${t.id}: committed ${s} model shard(s) + INDEX`)}else await Xe(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`);o("done")}catch(s){let i=s instanceof Error?s.message:String(s);n.warn(`[ctx] context_write ${t.id} failed: ${i}`),o("failed",i)}}async function Ky(t,e,r,n,o){let s=c=>{n.readyState===n.OPEN&&n.send(JSON.stringify(c))},i=c=>{o.warn(`[model] model_detail ${t.requestId} failed: ${c}`),s({type:"model_detail_result",requestId:t.requestId,status:"failed",error:c})},a=e?.contextDir;if(!a){i("unavailable: no working copy on this CLI");return}try{let c=await yl(t.detail,{contextDir:a,projectId:r.projectId,resolveRepoSpec:d=>ps(Ly(pr(a,"project.yaml"),"utf-8")).repos.find(u=>u.name===d)??null,resolveTracker:()=>{let d=Be({contextDir:a});return d.ok?d.provider:null}});s({type:"model_detail_result",requestId:t.requestId,status:"ok",...c});let l=t.detail.kind==="code"?t.detail.nodeId:t.detail.taskKey;o.info(`[model] model_detail ${t.requestId}: served ${t.detail.kind} ${l} (${c.sizeBytes} bytes)`)}catch(c){let l=c instanceof Error?c.message:String(c);i(l==="not_found"||l.startsWith("unavailable:")?l:`cli_error: ${l}`)}}async function Wy(t,e,r,n){let o=(s,i)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:s};i&&(a.error=i),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 s=t.source??"task",i=await Dc(e.contextDir,t.taskKey,t.slugs,void 0,s);if(n.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let a=l=>s==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${i.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);return}o("done")}catch(s){let i=s instanceof Error?s.message:String(s);n.warn(`[adr] adr_promote ${t.id} failed: ${i}`),o("failed",i)}}function Qu(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}me();ne();st();ii();Ve();fo();async function dd(t={profile:void 0}){let{cfg:e,profile:r}=qn(t.profile),n=G(e.projectId);n&&Vr(n),an(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),cn(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),ln(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=mn(ai(),".codepipe","logs"),s=r?`cli-daemon-${r}`:"cli-daemon",i=Jn("CLI_LOG",s,o);if(i.enabled){let u=new nr(i);zn(u),console.log(`[log] file logging \u2192 ${u.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=Kn(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=mn(ai(),".codepipe",r?mn("profiles",r,"context"):"context");if(await ei(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await ld(()=>Eo({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 ei(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=mn(ai(),".codepipe",r?mn("profiles",r,"context-config"):"context-config");Zn(a.contextDir,m,{info:p=>console.log(p),warn:p=>console.warn(p)})}}let l=To(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))}}),d=!1;function f(u){d||(d=!0,console.log(`
|
|
887
|
+
[${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}Ir();$e();me();async function yp(t={profile:void 0}){let e=Ce(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=vo(e.hubUrl,e.cliToken),n=await new Promise(s=>{let i=[],a=!1,c=setTimeout(()=>{i.push("timeout"),r.close(),s({ok:!1,events:i})},5e3);r.on("open",()=>{i.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let d=l.toString("utf-8");if(i.push(`msg:${d}`),d!=="pong")try{let f=JSON.parse(d);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",l=>i.push(`error:${l.message}`)),r.on("close",(l,d)=>{i.push(`close:${l}:${d?.toString()||""}`),clearTimeout(c),s({ok:a,events:i})}),setTimeout(()=>r.close(),1500)});for(let s of n.events)console.log(` ${s}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let s=await J(e.hubUrl,e.cliToken,e.projectId);if(s.duplicateIntake){let i=s.duplicateIntake;console.warn(`warning: project \xAB${i.withProjectId}\xBB watches the same YouTrack columns (${i.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=he(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`)")}vn();import{readFileSync as Ek}from"node:fs";q();$e();st();Lo();Mt();bt();Gt();me();ne();function pe(t){throw new Error(t)}function fe(t,e){return(typeof t!="string"||t.trim().length===0)&&pe(`config: '${e}' must be a non-empty string`),t.trim()}function Sn(t,e){if(t==null)return;typeof t!="string"&&pe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Pk(t){(!t||typeof t!="object")&&pe("config: expected a JSON object");let e=t,r=fe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||pe("config: 'hubUrl' must start with http(s)://");let n=fe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&pe("config: 'project' is required");let s=o,i=fe(s.id,"project.id");Ot.test(i)||pe("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=fe(s.name,"project.name"),c=fe(s.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&pe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=s.repos;Array.isArray(l)||pe("config: 'project.repos' must be an array");let d=l.map((w,b)=>{(!w||typeof w!="object")&&pe(`config: project.repos[${b}] must be an object`);let T=w,L=fe(T.host,`project.repos[${b}].host`);L!=="github"&&L!=="bitbucket"&&L!=="gitlab"&&pe(`config: project.repos[${b}].host must be 'github', 'bitbucket' or 'gitlab'`);let x={name:fe(T.name,`project.repos[${b}].name`),host:L,owner:fe(T.owner,`project.repos[${b}].owner`),repoName:fe(T.repoName,`project.repos[${b}].repoName`)},A=Sn(T.defaultBranch,`project.repos[${b}].defaultBranch`);A&&(x.defaultBranch=A);let O=Sn(T.mountAs,`project.repos[${b}].mountAs`);return O&&(x.mountAs=O),x}),f=s.contextRepo;(!f||typeof f!="object")&&pe("config: 'project.contextRepo' is required");let u=f,m=Sn(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&pe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let p={host:m,owner:fe(u.owner,"project.contextRepo.owner"),name:Sn(u.name,"project.contextRepo.name")??nt(i)},h={hubUrl:r,cliToken:n,project:{id:i,name:a,automationLevel:c,repos:d,contextRepo:p}},y=Sn(s.youtrackProjectKey,"project.youtrackProjectKey");y&&(h.project.youtrackProjectKey=y),s.index!==void 0&&(typeof s.index!="boolean"&&pe("config: 'project.index' must be a boolean"),h.project.index=s.index),s.youtrackWrites!==void 0&&(typeof s.youtrackWrites!="boolean"&&pe("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=s.youtrackWrites);let k=e.secrets;if(k!==void 0){(typeof k!="object"||k===null)&&pe("config: 'secrets' must be an object");let w=k,b={};if(w.github){let T=w.github;b.github={token:fe(T.token,"secrets.github.token")}}if(w.bitbucket){let T=w.bitbucket;b.bitbucket={email:fe(T.email,"secrets.bitbucket.email"),apiToken:fe(T.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let T=w.gitlab;b.gitlab={token:fe(T.token,"secrets.gitlab.token")}}if(w.youtrack){let T=w.youtrack;b.youtrack={url:fe(T.url,"secrets.youtrack.url").replace(/\/$/,""),token:fe(T.token,"secrets.youtrack.token")}}if(w.contextWrite){let T=w.contextWrite;b.contextWrite={token:fe(T.token,"secrets.contextWrite.token")}}h.secrets=b}return h}async function jk(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Ak(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await ht(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(s=>s.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await yt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let s=await so(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(s)throw new Error(`Bitbucket: ${s}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await wt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await vt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function af(t){let e=!t.configPath||t.configPath==="-"?await jk():Ek(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){pe(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=Pk(r),{hubUrl:o,cliToken:s,project:i}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${i.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await Ak(n));let a={projectId:i.id,name:i.name,automationLevel:i.automationLevel,repos:i.repos};i.youtrackProjectKey&&(a.youtrackProjectKey=i.youtrackProjectKey),console.log(`provisioning Context Repo ${i.contextRepo.owner}/${i.contextRepo.name} (${i.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Cr(a,i.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??rr(),youtrackWrites:i.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){pe(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let d;try{d=await xt(o,s,a)}catch(u){if(u instanceof D&&u.status===409)console.log(`project ${i.id} already exists on HUB \u2014 reusing it`),d=await J(o,s,i.id);else if(u instanceof D)pe(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${d.projectId} ready (${d.provisioningStatus})`);let f={hubUrl:o,cliToken:s,projectId:i.id,...n.secrets??{}};if(Q(f),ot({hubUrl:o,cliToken:s,projectId:i.id},i.id),console.log(`config + secrets written (profile ${i.id}) \u2192 ${Je(i.id)}`),Ut(i.id,Qe(a,i.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:u=>console.log(u),warn:u=>console.warn(u)}),i.index)try{let{jobId:u}=await fn(o,s,i.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 ${i.id} daemon`)}$e();ne();import{cancel as cf,intro as lf,isCancel as uf,log as Ci,outro as _k,password as df}from"@clack/prompts";async function Nk(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function pf(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Nk(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){lf("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ci.message("Run `claude setup-token` and paste the token below (input hidden).");let s=await df({message:"Claude OAuth token"});uf(s)&&(cf("aborted"),process.exit(1)),e=s.trim()}e||(console.error("login: no token provided"),process.exit(1)),gc({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Vn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ce(t.profile);if(!e){lf(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ci.message("Run `claude setup-token` and paste the token below (input hidden).");let s=await df({message:"Claude OAuth token"});uf(s)&&(cf("aborted"),process.exit(1)),e=s.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=G(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}.`):(Ci.success("Claude OAuth token saved."),_k("It will be sealed into job bundles when a SANDBOX (re)connects."))}q();$e();st();Lo();Mt();Uo();me();ne();import{cancel as Ok,confirm as Dk,intro as Lk,isCancel as ff,log as ye,outro as Uk,select as mf,text as Et}from"@clack/prompts";function gf(t){Ok(t),process.exit(1)}function Or(t){return ff(t)&&gf("aborted"),t}function Rn(t){return ff(t)&&gf("aborted"),typeof t=="string"?t:""}async function Bk(t,e){let r=Or(await mf({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(i=>i.host===r)?.owner??e[0]?.owner??"",o=Rn(await Et({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:i=>i.trim().length>0?void 0:"required"})).trim(),s=Rn(await Et({message:"Context Repo name",placeholder:nt(t),initialValue:nt(t),validate:i=>i.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:s}}async function hf(t={profile:void 0}){let e=Ce(t.profile);Lk(`codepipe project add \u2192 ${e.hubUrl}`);let r=Or(await Et({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>Ot.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Or(await Et({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=Or(await mf({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=Or(await Et({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),i=Or(await Dk({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=Rn(await Et({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:k=>!k||!k.trim()||je(k)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!u)break;let m=je(u);ye.message(`${m.host}: ${m.owner}/${m.repoName}`);let p=Rn(await Et({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:k=>k.trim().length>0?void 0:"required"})).trim(),h=Rn(await Et({message:"default branch (optional)",placeholder:"main"})).trim(),y={name:p,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};s&&(c.youtrackProjectKey=s);let l=await Bk(r,a),d=G(e.projectId);ye.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Cr(c,l,{githubToken:d?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:d?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:d?.bitbucket??rr(),youtrackWrites:i,trackerUrl:d?.youtrack?.url,log:{info:u=>ye.message(u),warn:u=>ye.warn(u)}})}catch(u){ye.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=f,ye.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await xt(e.hubUrl,e.cliToken,c);ye.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Ut(r,Qe(c,i,d?.youtrack?.url),{info:m=>ye.message(m),warn:m=>ye.warn(m)}),u.contextRepo&&(ye.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),ye.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&ye.error(` error: ${u.provisioningError}`),Uk("done")}catch(u){u instanceof D?(ye.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&ye.message(JSON.stringify(u.payload,null,2))):ye.error(u instanceof Error?u.message:String(u)),process.exit(1)}}Ir();$e();me();ne();Ve();vn();import{existsSync as Mk,rmSync as Fk}from"node:fs";import{confirm as Gk,intro as Hk,isCancel as Kk,log as Pt,outro as Wk,spinner as qk}from"@clack/prompts";function Ze(t){Pt.error(t),process.exit(1)}var yf=t=>t.trim().replace(/\/+$/,"");async function wf(t){Hk("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Te()?.spec.projectId??void 0;e||Ze("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=De(e);r||Ze(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=yf(r.hubUrl),o=r.projectId,s=yf(t.hub);s.startsWith("http")||Ze("--hub must be an http(s):// URL");let i=t.toProfile??e,a=t.project??o,c=i===e;c&&a===o&&s===n&&Ze(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let k=qk();k.start(`reading project ${o} from ${n}\u2026`);try{l=await J(n,r.cliToken,o),k.stop(`read project ${o} (${l.name})`)}catch(w){throw k.stop("could not read the source project",1),w instanceof D&&Ze(`source HUB ${n} \u2192 ${w.status} ${w.message}. The source HUB must be reachable with a valid token to move a project.`),w}}l.contextRepo||Ze(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let d=G(o),f=(t.account??r.accountEmail??await _r()).trim().toLowerCase();if(Pt.message(`move project '${o}'
|
|
747
888
|
from : ${n} (profile ${e})
|
|
748
|
-
to : ${
|
|
889
|
+
to : ${s} (profile ${i}, project ${a}, account ${f})
|
|
749
890
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
750
891
|
\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 '${
|
|
752
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await
|
|
753
|
-
`)}async function
|
|
892
|
+
`+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${i}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let k=await Gk({message:"Continue?",initialValue:!0});(Kk(k)||!k)&&Ze("aborted")}!c&&a===o&&Pt.warn(`source and destination share the same project id, so they share one secrets file (${Je(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 Nr(s,f),p={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Pt.step(`registering project on ${s}\u2026`);let h;try{h=await xt(s,u,p)}catch(k){if(k instanceof D&&k.status===409){Pt.warn(`project ${a} already exists on ${s} \u2014 reusing it`);try{h=await J(s,u,a)}catch(w){throw w instanceof D&&Ze(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if(k instanceof D&&k.status===403)Ze(`project ${a} already exists on ${s} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(k instanceof D)Ze(`target HUB \u2192 ${k.status} ${k.message}`);else throw k}Pt.success(`project ${h.projectId} ready on ${s} (${h.provisioningStatus})`),ot({hubUrl:s,cliToken:u,projectId:a,accountEmail:m},i);let y={...d??{},hubUrl:s,cliToken:u,projectId:a};if(delete y.sandboxPins,Q(y),Pt.success(`profile '${i}' \u2192 ${Je(a)}`),c){let k=Fe(i);Mk(k)&&(Fk(k),Pt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}Wk(`done. next: \`codepipe up --profile ${i}\` \u2014 starts the daemon and a worker on ${s}.`)}$e();import{existsSync as Ei,rmSync as Yk,statSync as Vk}from"node:fs";import{join as Wo,relative as Jk,resolve as zk}from"node:path";import{cancel as Xk,intro as kf,isCancel as Qk,log as ae,outro as $f,text as Yt}from"@clack/prompts";import{simpleGit as vf}from"simple-git";Uo();me();ne();Ve();function xe(t){Xk(t),process.exit(1)}function Vt(t){return Qk(t)&&xe("aborted"),typeof t=="string"?t:""}async function bf(t){try{let e=await vf(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function Zk(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function e$(t,e){let r=G(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(Zk(r,e)){ae.message(`reusing existing ${e} credentials`);return}if(ae.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Vt(await Yt({message:"Atlassian account email (Bitbucket)",validate:s=>s.trim()?void 0:"required"})).trim(),o=Vt(await Yt({message:"Bitbucket API token (scoped)",validate:s=>s.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Vt(await Yt({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}}Q(r),ae.success(`saved ${e} credentials`)}async function xf(t){let e=Ce(t.profile);kf(`codepipe repo add \u2192 project ${e.projectId}`);let r=Te()??void 0,n;try{n=(await J(e.hubUrl,e.cliToken,e.projectId)).repos}catch(w){xe(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await bf(process.cwd());w?(o=process.cwd(),ae.message(`using the current directory (${w})`)):o=Vt(await Yt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:b=>b.trim()?void 0:"required"})).trim()}let s=null,i,a,c,l;if(Ei(o)&&Vk(o).isDirectory()){s=zk(o);let w=await bf(s);w||xe(`${s} is not a git repository (no origin remote)`);let b=je(w);b||xe(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=b,i=w,ae.message(`${a}: ${c}/${l} (already cloned at ${s})`)}else{let w=je(o);w||xe(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,i=o,ae.message(`${a}: ${c}/${l}`)}let d=Vt(await Yt({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===d)&&xe(`a repo named "${d}" is already registered`);let f=Vt(await Yt({message:"default branch (optional)",placeholder:"main"})).trim(),u=d;if(s&&r&&(s===r.root||s.startsWith(r.root+"/"))){let w=Jk(r.root,s);u=w===""?".":w}let m=Vt(await Yt({message:"mount_as (directory relative to the workspace root)",placeholder:u,initialValue:u})).trim()||u;n.some(w=>(w.mountAs??w.name)===m)&&xe(`mount_as "${m}" is already used by another repo`),await e$(e,a);let p={name:d,host:a,owner:c,repoName:l,mountAs:m,...f?{defaultBranch:f}:{}};if(!s){let w=r?Wo(r.root,m):we(e.projectId,d);if(Ei(Wo(w,".git")))ae.message(`already cloned at ${w}`);else{ae.info(`cloning ${i} \u2192 ${w} \u2026`);try{await vf().clone(i,w),ae.success(`cloned into ${w}`)}catch(b){xe(`clone failed: ${b instanceof Error?b.message.trim():String(b)}
|
|
893
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await _u(e.hubUrl,e.cliToken,e.projectId,p)}catch(w){w instanceof D&&xe(`HUB \u2192 ${w.status} ${w.message}`),xe(w instanceof Error?w.message:String(w))}let{updated:y,errors:k}=tn(e.projectId,h.repos,r?.contextDir);for(let w of y)ae.message(`updated ${w}`);for(let w of k)ae.warn(`could not update ${w.path}: ${w.error}`);ae.success(`added "${d}" \u2014 project now has ${h.repos.length} repo(s)`),$f("done")}async function Sf(t){let e=Ce(t.profile);kf(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Te()??void 0,n;try{let c=(await J(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await Nu(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof D&&(a.status===404&&xe(`no repo named "${t.name}" in this project`),xe(`HUB \u2192 ${a.status} ${a.message}`)),xe(a instanceof Error?a.message:String(a))}let{updated:s,errors:i}=tn(e.projectId,o.repos,r?.contextDir);for(let a of s)ae.message(`updated ${a}`);for(let a of i)ae.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ae.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Wo(r.root,n):we(e.projectId,t.name);if(Ei(Wo(a,".git")))try{Yk(a,{recursive:!0,force:!0}),ae.message(`deleted local clone ${a}`)}catch(c){ae.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ae.message(`no local clone found to purge (${a})`)}ae.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),$f("done")}async function Rf(t){let e=Ce(t.profile),r;try{r=(await J(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,s=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${s} \u2192 ${o}`)}}Mo();vi();import{existsSync as Lf,mkdirSync as s$,readFileSync as i$,writeFileSync as a$}from"node:fs";import{homedir as c$}from"node:os";import{dirname as l$,join as Uf}from"node:path";import*as Lr from"node:readline";me();ne();Ve();Mo();me();import{existsSync as Ai,readFileSync as t$,writeFileSync as r$}from"node:fs";import{join as Tn}from"node:path";import{simpleGit as ji}from"simple-git";var If=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],n$="apply-queue.json";function Tf(t){return Tn(t,n$)}function Dr(t){let e=Tf(t);if(!Ai(e))return{};try{return JSON.parse(t$(e,"utf-8"))}catch{return{}}}function Cf(t,e){r$(Tf(t),JSON.stringify(e,null,2)+`
|
|
894
|
+
`)}async function Ef(t,e,r,n,o){let s;try{s=await Eu(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(u){return{ok:!1,message:`claim failed: ${u instanceof Error?u.message:String(u)}`}}let i=[];for(let u of s.repos){let m=t.spec.repos.find(k=>k.name===u.repoName);if(!m)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let p=Tn(t.root,m.mountAs);if(!Ai(Tn(p,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await ji(p).status()).isClean())return{ok:!1,message:`${m.mountAs}/ has uncommitted changes \u2014 commit or stash first`};i.push({claimRepo:u,spec:m,dir:p})}let a=[];for(let u of i){let m=ji(u.dir),p=await o$(m),h=u.claimRepo;try{await m.fetch()}catch(w){return await Pi(a,o),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${In(w)}`}}let y=`origin/${h.baseRef}`,k;try{k=await uo(m,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(w){return await Pi(a,o),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${In(w)}`}}a.push({git:m,dir:u.dir,mountAs:u.spec.mountAs,originalRef:p,branch:h.branchName,baseSha:y,deliveryCommit:k,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([...If,"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([...If,"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 Pi(a,o),{ok:!1,message:`apply failed in ${u.mountAs}: ${In(m)} (rolled back all repos)`}}let l=Dr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Cf(t.contextDir,l);let d=c.map(u=>u.mountAs).join(", "),f=n==="apply"?`review, push branch '${s.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 ${d}
|
|
754
895
|
${f}
|
|
755
|
-
or: /abort ${r} --reason "..."`}}function
|
|
756
|
-
\u26A0 unfinished local apply: ${n.map(
|
|
757
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=
|
|
758
|
-
`))}async function
|
|
759
|
-
`)}`:" (none)");return}if(r==="set"){let
|
|
760
|
-
`),t.unread+=1,
|
|
761
|
-
bye.`),setTimeout(()=>process.exit(0),150))}function
|
|
896
|
+
or: /abort ${r} --reason "..."`}}function _i(t,e){let r=Dr(t);r[e]&&(delete r[e],Cf(t,r))}async function Pi(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}: ${In(n)} \u2014 check manually`)}}async function Pf(t,e,r){let o=Dr(t.contextDir)[e];if(o){for(let s of o.repos){let i=Tn(t.root,s.mountAs);if(!Ai(Tn(i,".git")))continue;let a=ji(i),c=t.spec.repos.find(d=>d.mountAs===s.mountAs),l=c?`origin/${c.defaultBranch}`:s.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",s.branch]).catch(()=>{})}catch(d){r.warn(`rollback failed in ${s.mountAs}: ${In(d)} \u2014 check manually`)}}_i(t.contextDir,e)}}async function o$(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function In(t){return t instanceof Error?t.message.trim():String(t)}var qo=Uf(c$(),".codepipe","history"),jf=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Bf=500,Af=40;async function Mf(){let t=Te();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=G(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)),Vr(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=Dr(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
|
|
897
|
+
\u26A0 unfinished local apply: ${n.map(i=>`${i} (${r[i].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
|
|
898
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=Lr.createInterface({input:process.stdin,output:process.stdout,completer:u$,history:P$(),removeHistoryDuplicates:!0}),s={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};al(i=>Jt(s,i)),s.daemon=To({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:i=>Jt(s,i),warn:i=>Jt(s,i)},onEvent:i=>S$(s,i),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(i=>({name:i.name,mountAs:i.mountAs,defaultBranch:i.defaultBranch}))}}),Oi(s),o.prompt(),o.on("line",async i=>{let a=i.trim();if(a.length>0)try{if(await d$(s,a)){Df(s);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}s.unread=0,Oi(s),o.prompt()}),o.on("close",()=>{Df(s)})}function u$(t){let e=jf.filter(r=>r.startsWith(t));return[e.length?e:jf,t]}async function d$(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return p$(),!1;case"/status":return await f$(t),!1;case"/tasks":return await m$(t,n),!1;case"/task":return await g$(t,n),!1;case"/sync":return await h$(t),!1;case"/logs":return R$(t,n),!1;case"/monitor":return I$(t),!1;case"/apply":return await _f(t,n,"apply"),!1;case"/unstash":return await _f(t,n,"unstash"),!1;case"/applied":return await y$(t,n),!1;case"/abort":return await w$(t,n),!1;case"/approve":return await Nf(t,n,"approve"),!1;case"/merge":return await Nf(t,n,"merge"),!1;case"/login":return k$(t,n),!1;case"/secret":return $$(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function p$(){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(`
|
|
899
|
+
`))}async function f$(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let r of t.ws.spec.repos){let n=Lf(Uf(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function m$(t,e){let r=T$(e,"--phase");try{let n=await Tu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(s=>s.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let s of o)console.log(` ${s.key.padEnd(10)} ${s.phase.padEnd(16)} ${s.title}`)}catch(n){En(n)}}async function g$(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Cu(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){En(n)}}async function h$(t){let e=await $n(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 _f(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Ef(t.ws,t.secrets,n,r,{info:s=>console.log(s),warn:s=>console.warn(s)});console.log(` ${o.message}`)}async function y$(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=Dr(t.ws.contextDir)[r],s=C$(e,"--pr");if(s.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let i=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of s){let l=c.indexOf("="),d,f;if(l>0?(d=c.slice(0,l),f=c.slice(l+1)):(f=c,d=o?.repos.length===1?b$(t,o.repos[0].mountAs):i.length===1?i[0]:""),!d){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:d,url:f,number:Number(u[1])})}try{let c=await Pu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);_i(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){En(c)}}async function Nf(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Au(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){En(o)}}async function w$(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=E$(e,"--reason")||"local apply aborted";await Pf(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await ju(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){En(o)}}function b$(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function k$(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},Q(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 $$(t,e){let[r,n,...o]=e;if(r==="list"){let s=[];t.secrets.github&&s.push("github.token"),t.secrets.bitbucket&&s.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&s.push("youtrack.url","youtrack.token"),console.log(s.length?` ${s.join(`
|
|
900
|
+
`)}`:" (none)");return}if(r==="set"){let s=o.join(" ");if(!n||!s){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}v$(t.secrets,n,s),Q(t.secrets),Vr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}x$(t.secrets,n),Q(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function v$(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 x$(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 S$(t,e){switch(e.kind){case"connected":t.connection="connecting",Jt(t,"[hub] connected");break;case"registered":t.connection="registered",Jt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Cn(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Jt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Cn(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Cn(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?Jt(t,`[hub] action ${e.actionType} done`):Cn(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Jt(t,e){t.logBuffer.push(e),t.logBuffer.length>Bf&&t.logBuffer.shift(),t.follow&&Cn(t,e)}function R$(t,e){let r=e[0];if(r==="follow"||r==="on"){Ni(t,!0);return}if(r==="off"){Ni(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)||Af)):Af,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let s of o)console.log(` ${s}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function I$(t){Ni(t,!t.follow)}function Ni(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Cn(t,e){Lr.cursorTo(process.stdout,0),Lr.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
901
|
+
`),t.unread+=1,Oi(t),t.rl.prompt(!0)}function Oi(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Of=!1;function Df(t){Of||(Of=!0,j$(t.rl),t.daemon.stop(),console.log(`
|
|
902
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function T$(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function C$(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 E$(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function En(t){t instanceof D?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function P$(){if(!Lf(qo))return[];try{return i$(qo,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function j$(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{s$(l$(qo),{recursive:!0}),a$(qo,r.slice().reverse().join(`
|
|
762
903
|
`)+`
|
|
763
|
-
`)}catch{}}br();Y();Ne();br();ke();fe();yn();import{hostname as Wb}from"node:os";import{cancel as qb,confirm as mf,intro as Yb,isCancel as yf,log as Ar,multiselect as Vb,outro as gf,password as Jb,select as $s,text as vs}from"@clack/prompts";function Rn(t){qb(t),process.exit(1)}function _r(t){return yf(t)&&Rn("aborted"),t}function Bo(t){return yf(t)&&Rn("aborted"),typeof t=="string"?t:""}function xs(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function hf(t,e){try{let{secret:r}=await ho(t,e);return r}catch(r){throw r instanceof O&&r.status===404&&Rn("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 zb(t,e){if(_r(await $s({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 Li(t,e);if(o.length>0)return _r(await Vb({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}));Ar.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Ar.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Bo(await vs({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 Ss(t){Yb("codepipe worker \u2014 set up this machine as a runner");let e=ge(t.profile);e&&(Ar.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),_r(await mf({message:"re-register this worker?",initialValue:!1}))||Rn("keeping the existing registration"));let r=Oe(t.profile)??Oe(),n=Bo(await vs({message:"HUB URL",placeholder:Ge,initialValue:K("HUB_URL")??r?.hubUrl??Ge,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=_r(await $s({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 hf(n,a),Ar.success("account-issued registration token minted");else if(i==="login"){let u=await Ir();a=(await Cr(n,u)).cliToken,s=await hf(n,a),Ar.success("account-issued registration token minted")}else s=Bo(await Jb({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Rn("a registration token is required");let c=await zb(n,a),l=Bo(await vs({message:"worker name",initialValue:Wb(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=_r(await $s({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await Bt({hub:n,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Ar.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!_r(await mf({message:"start the claim-loop now?",initialValue:!0}))){gf("registered. start later with `codepipe worker`.");return}gf("starting the claim-loop\u2026"),await mn(t.profile?{profile:t.profile}:{})}function Qb(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return K("PROFILE")}var se=Qb();ja(se);Na();var ve=new Xb;ve.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(xe).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await ff()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await _d({configPath:t.config,skipVerify:t.skipVerify===!0}):await vd({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Ya({...t,profile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await xd({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ve.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Lu({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await fd({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Ld({profile:se,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ve.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Kp({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await ss({profile:se,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var wf=ve.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");wf.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??K("HUB_URL")??Oe(se)?.hubUrl??Ge,r=t.token??K("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&xs()){await Ss({profile:se});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=K("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??K("WORKER_NAME"),i=t.llm??K("WORKER_LLM");await Bt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...se?{profile:se}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});wf.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ge(se)&&xs()){await Ss({profile:se});return}await mn(se?{profile:se}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var kf=ve.command("project").description("Manage CodePipe projects");kf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Fd({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});kf.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 Kd({...t,cliProfile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Rs=ve.command("repo").description("Manage the project's git repositories");Rs.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 Jd({profile:se,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Rs.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:se,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Rs.command("list").description("List the project's repos").action(async()=>{try{await Xd({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ve.parseAsync();
|
|
904
|
+
`)}catch{}}Ir();q();Oe();Ir();$e();me();vn();import{hostname as A$}from"node:os";import{cancel as _$,confirm as Ff,intro as N$,isCancel as Kf,log as Ur,multiselect as O$,outro as Gf,password as D$,select as Di,text as Li}from"@clack/prompts";function Pn(t){_$(t),process.exit(1)}function Br(t){return Kf(t)&&Pn("aborted"),t}function Yo(t){return Kf(t)&&Pn("aborted"),typeof t=="string"?t:""}function Ui(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Hf(t,e){try{let{secret:r}=await So(t,e);return r}catch(r){throw r instanceof D&&r.status===404&&Pn("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 L$(t,e){if(Br(await Di({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 Zs(t,e);if(o.length>0)return Br(await O$({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(s=>({value:s.id,label:`${s.id} \u2014 ${s.name}`})),required:!0}));Ur.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Ur.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Yo(await Li({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 Bi(t){N$("codepipe worker \u2014 set up this machine as a runner");let e=he(t.profile);e&&(Ur.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Br(await Ff({message:"re-register this worker?",initialValue:!1}))||Pn("keeping the existing registration"));let r=De(t.profile)??De(),n=Yo(await Li({message:"HUB URL",placeholder:He,initialValue:K("HUB_URL")??r?.hubUrl??He,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,s=Br(await Di({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"})),i,a=null;if(s==="local")a=r.cliToken,i=await Hf(n,a),Ur.success("account-issued registration token minted");else if(s==="login"){let u=await _r();a=(await Nr(n,u)).cliToken,i=await Hf(n,a),Ur.success("account-issued registration token minted")}else i=Yo(await D$({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),i||Pn("a registration token is required");let c=await L$(n,a),l=Yo(await Li({message:"worker name",initialValue:A$(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),d=Br(await Di({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:i,name:l,projects:c,...d?{llm:d}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Ur.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Br(await Ff({message:"start the claim-loop now?",initialValue:!0}))){Gf("registered. start later with `codepipe worker`.");return}Gf("starting the claim-loop\u2026"),await bn(t.profile?{profile:t.profile}:{})}function B$(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return K("PROFILE")}var ce=B$();ec(ce);nc();var Se=new U$;Se.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Re).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 Mf()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Se.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 af({configPath:t.config,skipVerify:t.skipVerify===!0}):await Jp({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Se.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 hc({...t,profile:ce})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Se.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 zp({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Se.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await dd({profile:ce})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Se.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 Mp({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Se.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 pf({profile:ce,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Se.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await yp({profile:ce})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Se.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 $i({profile:ce,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Wf=Se.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Wf.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??K("HUB_URL")??De(ce)?.hubUrl??He,r=t.token??K("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ui()){await Bi({profile:ce});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=K("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??K("WORKER_NAME"),s=t.llm??K("WORKER_LLM");await Ht({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...s?{llm:s}:{},...ce?{profile:ce}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Wf.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!he(ce)&&Ui()){await Bi({profile:ce});return}await bn(ce?{profile:ce}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var qf=Se.command("project").description("Manage CodePipe projects");qf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await hf({profile:ce})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});qf.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 wf({...t,cliProfile:ce})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Mi=Se.command("repo").description("Manage the project's git repositories");Mi.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 xf({profile:ce,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Mi.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 Sf({profile:ce,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Mi.command("list").description("List the project's repos").action(async()=>{try{await Rf({profile:ce})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Se.parseAsync();
|