@code-partner/codepipe 0.5.4-dev.163.g9de1d88 → 0.5.4-dev.164.g3d62ed9
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 +159 -154
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Df=Object.defineProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var Lf=(t,e)=>{for(var r in e)Df(t,r,{get:e[r],enumerable:!0})};var Te,We,Xo=S(()=>{"use strict";Te="0.5.4-dev.164.g3d62ed9",We="https://hub.dev.codepipe.dev"});function _n(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Uf&&t<=qe}var qe,Uf,Us=S(()=>{"use strict";Xo();qe=4,Uf=4});var Bs=S(()=>{"use strict";Xo()});function Nn(t=3){return`# CodePipe Context Repo format version.
|
|
3
3
|
# Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
|
|
4
4
|
template_version: ${t}
|
|
5
|
-
`}function Bs(t){if(!t)return 0;let e=/^\s*template_version:\s*(\d+)\s*$/m.exec(t),r=e?parseInt(e[1]??"",10):NaN;return Number.isFinite(r)&&r>=0?r:0}function Ms(t,e=Us){let r=[];for(let n of e)if(!(n.version<=t))for(let o of n.addedPaths)r.includes(o)||r.push(o);return r}function Gs(t,e=Us){return e.filter(r=>r.version>t)}var We,Fr,Us,Fs=R(()=>{"use strict";We=".codepipe-context.yaml",Fr=".devpipe-context.yaml",Us=[{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"]}]});var Hs=R(()=>{"use strict"});var Nf,m$,Ks=R(()=>{"use strict";Nf=[{id:"intake",label:"Intake",phases:["INTAKE"]},{id:"analysis",label:"Analysis",phases:["ANALYZING","ESTIMATING"]},{id:"ready",label:"Ready",phases:["READY"]},{id:"implementation",label:"Implementation",phases:["IMPLEMENTING","BUILD"]},{id:"delivery",label:"Delivery",phases:["READY_TO_APPLY","APPLYING"]}],m$=Nf.flatMap(t=>t.phases)});function Nt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ws,Xo=R(()=>{"use strict";Ws=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});var Ye,qs,qe,On,Of,Qo,Ys,Zo=R(()=>{"use strict";Ye="claude",qs=[Ye],qe="opus",On="sonnet",Of="haiku",Qo=[qe,On,Of],Ys={analyze:qe,implement:qe,"resolve-conflict":qe,rework:qe,estimate:On,build:On,"code-review":qe,draft:On,index:qe,backfill:qe,analysis:qe,chat:qe}});function ft(t){return Df.has(t)?!0:Lf.some(e=>t.startsWith(e))}function Dn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ot(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ei(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Qs(t,e){let r=Dn(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Ot(r.id,"id")??n;if(!Vs.test(o))throw new Error(`id must match ${Vs} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Ot(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let f=Dn(r.env,"env");s={};for(let[u,m]of Object.entries(f)){if(!Ie.test(u))throw new Error(`env name "${u}" must match ${Ie}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${u} must be a scalar`);s[u]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Js)throw new Error(`too many params (max ${Js})`);let f=new Set;a=c.map((u,m)=>Uf(u,m,f))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>zs)throw new Error(`too many steps (max ${zs})`);let d=l.map((f,u)=>{let m=Dn(f,`steps[${u}]`),p=Ot(m.run,`steps[${u}].run`);if(!p||p.trim().length===0)throw new Error(`steps[${u}].run is required`);let h=Ot(m.name,`steps[${u}].name`),y=ei(m.timeout_sec,`steps[${u}].timeout_sec`);if(y!==void 0&&(!Number.isInteger(y)||y<=0))throw new Error(`steps[${u}].timeout_sec must be a positive integer`);return{run:p,...h?{name:h}:{},...y!==void 0?{timeout_sec:y}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:d}}function Uf(t,e,r){let n=Dn(t,`params[${e}]`),o=Ot(n.name,`params[${e}].name`);if(!o||!Ie.test(o))throw new Error(`params[${e}].name must match ${Ie}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(p=>typeof p=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=Ot(n.label,`params[${e}].label`),c=Ot(n.help,`params[${e}].help`),l=n.required===!0,d=ei(n.min,`params[${e}].min`),f=ei(n.max,`params[${e}].max`),u=n.default;if(u!=null&&typeof u!="string"&&typeof u!="number"&&typeof u!="boolean")throw new Error(`params[${e}].default must be a scalar`);return{name:o,type:i,...a?{label:a}:{},...c?{help:c}:{},...l?{required:!0}:{},...s?{enum:s}:{},...d!==void 0?{min:d}:{},...f!==void 0?{max:f}:{},...u!=null?{default:u}:{}}}function Zs(t,e){let r=t.params??[],n=new Map(r.map(i=>[i.name,i]));for(let i of Object.keys(e))if(!n.has(i))return{ok:!1,error:`unknown param: ${i}`};let o={};for(let i of r){let s=e[i.name];if(s==null||typeof s=="string"&&s.trim()==="")if(i.default!==void 0)s=i.default;else{if(i.required)return{ok:!1,error:`${i.name} is required`};continue}switch(i.type){case"string":{if(typeof s!="string")return{ok:!1,error:`${i.name} must be a string`};o[i.name]=s;break}case"enum":{if(typeof s!="string"||!(i.enum??[]).includes(s))return{ok:!1,error:`${i.name} must be one of: ${(i.enum??[]).join(", ")}`};o[i.name]=s;break}case"number":{let a=typeof s=="number"?s:typeof s=="string"?Number(s):NaN;if(!Number.isFinite(a))return{ok:!1,error:`${i.name} must be a number`};if(i.min!==void 0&&a<i.min)return{ok:!1,error:`${i.name} must be \u2265 ${i.min}`};if(i.max!==void 0&&a>i.max)return{ok:!1,error:`${i.name} must be \u2264 ${i.max}`};o[i.name]=a;break}case"boolean":{let a=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:null;if(a===null)return{ok:!1,error:`${i.name} must be a boolean`};o[i.name]=a;break}}}return{ok:!0,values:o}}var Ie,Df,Lf,Xs,Vs,Js,zs,ti=R(()=>{"use strict";Ie=/^[A-Z][A-Z0-9_]*$/,Df=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Lf=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Xs=600,Vs=/^[a-z0-9-]+$/,Js=32,zs=64});function na(t=Bf){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...na(r.groups));return e}function Mf(t,e){let r=JSON.stringify(e);return na().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function oa(t){let e=Mf(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>ea)return{ok:!1,error:`${e.id} must have \u2264 ${ea} entries`};let s={};for(let[a,c]of i){if(!Ie.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Ie}`};if(ft(a))return{ok:!1,error:`${e.id}: name "${a}" is reserved`};if(typeof c!="string")return{ok:!1,error:`${e.id}: value of "${a}" must be a string`};if(c.length>ta)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${ta} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var ea,ta,ra,Bf,ia=R(()=>{"use strict";ti();Xo();Zo();ea=64,ta=2e3,ra=2e3,Bf=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{id:"llm",label:"LLM",fields:[{id:"llm.provider",file:"regimen.yaml",path:["llm","provider"],type:"enum",label:"Provider",nullable:!1,suggestions:[...qs],help:"LLM backend for this project. Currently only claude is available."}],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Qo],help:"Overrides the recommended defaults for every role not listed below."},...Ws.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Qo],help:`recommended: ${Ys[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:ra,help:'e.g. "English, imperative mood, first line \u2264 72 chars, start with the issue key". Empty \u21D2 "<KEY>: <task title>".'},{id:"apply.pr_style",file:"project.yaml",path:["apply","pr_style"],type:"string",label:"PR description style",nullable:!0,multiline:!0,maxLength:ra,help:'e.g. "Russian, implementation details, bullet list of what was done". Empty \u21D2 the default PR body.'}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]}]});var sa=R(()=>{"use strict"});var aa=R(()=>{"use strict"});var ca=R(()=>{"use strict"});var la=R(()=>{"use strict"});function ua(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}function nt(t){return`${t}${Gf}`}var Dt,Gf,da=R(()=>{"use strict";Dt=/^[a-z][a-z0-9-]{1,30}$/,Gf="-codepipe-ctx"});var pa=R(()=>{"use strict"});var fa=R(()=>{"use strict"});function zt(t){for(let e of Ff){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Ff,ma=R(()=>{"use strict";Ff=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}]});var ga=R(()=>{"use strict"});var ha=R(()=>{"use strict"});var ya=R(()=>{"use strict"});function wa(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function ba(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=wa(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Xt.test(r))return r;let n=wa(t);return Xt.test(n)?n:ri}function $a(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),i=t.slice(0,10-o.length)+o;if(!r.has(i.toUpperCase()))return i}return t}function Kr(t){return`tasks/${t}/issue.yaml`}var ka,Ln,ri,Xt,ni,C$,Un,Hr,va=R(()=>{"use strict";ka=["bug","feature","epic"],Ln="feature",ri="TASK",Xt=/^[A-Z][A-Z0-9]{1,9}$/;ni={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},C$=ni.backlog,Un="tracker/config.yaml",Hr="tracker/counter"});var xa=R(()=>{"use strict"});function Qt(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function Bn(t){switch(t){case Wr.gitlab:return"oauth2";case Wr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Wr,Lt,Sa=R(()=>{"use strict";Wr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Lt="x-bitbucket-api-token-auth"});var Ra=R(()=>{"use strict"});var Ia=R(()=>{"use strict";xa();Sa();Ra()});var Ta,K=R(()=>{"use strict";Ds();Ls();Fs();Hs();Ks();Xo();Zo();ia();ti();sa();aa();ca();la();da();pa();fa();ma();ga();ha();ya();va();Ia();Ta=20});function G(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Te=R(()=>{"use strict"});import{existsSync as Ca,renameSync as Hf}from"node:fs";function Ut(t,e,r=n=>console.error(n)){if(Ca(e)||!Ca(t))return!1;try{return Hf(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Mn=R(()=>{"use strict"});import{existsSync as Gn,readFileSync as Pa,readdirSync as Kf,writeFileSync as Wf}from"node:fs";import{dirname as qf,join as mt}from"node:path";import{parse as Yf}from"yaml";function Vf(t=process.cwd()){let e=t;for(;;){if(Gn(mt(e,Ve,"project.yaml")))return e;if(Gn(mt(e,oi,"project.yaml")))return Ut(mt(e,oi),mt(e,Ve))&&zf(e),e;let r=qf(e);if(r===e)return null;e=r}}function Jf(t){let e=mt(t,Ve);return Gn(e)?e:mt(t,oi)}function zf(t){let e=mt(t,".gitignore");if(!Gn(e))return;let r=Pa(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
|
|
6
|
-
`);n!==r&&
|
|
7
|
-
`,{mode:384})}function
|
|
8
|
-
`,{mode:384})}function
|
|
9
|
-
`,{mode:384})}function
|
|
5
|
+
`}function Gs(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 Fs(t,e=Ms){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 Hs(t,e=Ms){return e.filter(r=>r.version>t)}var Ye,Gr,Ms,Ks=S(()=>{"use strict";Ye=".codepipe-context.yaml",Gr=".devpipe-context.yaml",Ms=[{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",Ye]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Ye]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]}]});var Ws=S(()=>{"use strict"});var Bf,k$,qs=S(()=>{"use strict";Bf=[{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"]}],k$=Bf.flatMap(t=>t.phases)});function _t(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ys,Qo=S(()=>{"use strict";Ys=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function Vs(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Xs(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Gf.every(o=>e.some(i=>Vs(o,i.id))))return null;let n=[...e].sort((o,i)=>{let s=o.createdAt??"",a=i.createdAt??"";return s!==a?s<a?1:-1:o.id<i.id?1:-1});for(let o of Mf){let i=n.find(s=>Vs(o,s.id));if(i)return i.id}return n[0].id}var Ve,Js,Le,Fr,zs,Zo,ei,Mf,Gf,ti=S(()=>{"use strict";Ve="claude",Js=[Ve],Le="opus",Fr="sonnet",zs="haiku",Zo=[Le,Fr,zs],ei={analyze:Le,implement:Le,"resolve-conflict":Le,rework:Le,estimate:Fr,build:Fr,"code-review":Le,draft:Fr,index:Le,backfill:Le,analysis:Le,chat:Le},Mf=[Le,Fr,zs],Gf=Array.from(new Set(Object.values(ei)))});function ft(t){return Ff.has(t)?!0:Hf.some(e=>t.startsWith(e))}function On(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Nt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ri(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function ra(t,e){let r=On(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Nt(r.id,"id")??n;if(!Qs.test(o))throw new Error(`id must match ${Qs} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Nt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let f=On(r.env,"env");s={};for(let[u,m]of Object.entries(f)){if(!Ce.test(u))throw new Error(`env name "${u}" must match ${Ce}`);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>Zs)throw new Error(`too many params (max ${Zs})`);let f=new Set;a=c.map((u,m)=>Kf(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>ea)throw new Error(`too many steps (max ${ea})`);let d=l.map((f,u)=>{let m=On(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=ri(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:i,...s?{env:s}:{},...a?{params:a}:{},steps:d}}function Kf(t,e,r){let n=On(t,`params[${e}]`),o=Nt(n.name,`params[${e}].name`);if(!o||!Ce.test(o))throw new Error(`params[${e}].name must match ${Ce}`);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(p=>typeof p=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=Nt(n.label,`params[${e}].label`),c=Nt(n.help,`params[${e}].help`),l=n.required===!0,d=ri(n.min,`params[${e}].min`),f=ri(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}:{},...d!==void 0?{min:d}:{},...f!==void 0?{max:f}:{},...u!=null?{default:u}:{}}}function na(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 Ce,Ff,Hf,ta,Qs,Zs,ea,ni=S(()=>{"use strict";Ce=/^[A-Z][A-Z0-9_]*$/,Ff=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Hf=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];ta=600,Qs=/^[a-z0-9-]+$/,Zs=32,ea=64});function aa(t=Wf){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...aa(r.groups));return e}function qf(t,e){let r=JSON.stringify(e);return aa().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function ca(t){let e=qf(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>oa)return{ok:!1,error:`${e.id} must have \u2264 ${oa} entries`};let s={};for(let[a,c]of i){if(!Ce.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Ce}`};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>ia)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${ia} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var oa,ia,sa,Wf,la=S(()=>{"use strict";ni();Qo();ti();oa=64,ia=2e3,sa=2e3,Wf=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{id:"llm",label:"LLM",fields:[{id:"llm.provider",file:"regimen.yaml",path:["llm","provider"],type:"enum",label:"Provider",nullable:!1,suggestions:[...Js],help:"LLM backend for this project. Currently only claude is available."}],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Zo],help:"Overrides the recommended defaults for every role not listed below."},...Ys.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Zo],help:`recommended: ${ei[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:sa,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:sa,help:'e.g. "Russian, implementation details, bullet list of what was done". Empty \u21D2 the default PR body.'}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]}]});var ua=S(()=>{"use strict"});var da=S(()=>{"use strict"});var pa=S(()=>{"use strict"});var fa=S(()=>{"use strict"});function ma(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 ot(t){return`${t}${Yf}`}var Ot,Yf,ga=S(()=>{"use strict";Ot=/^[a-z][a-z0-9-]{1,30}$/,Yf="-codepipe-ctx"});var ha=S(()=>{"use strict"});var ya=S(()=>{"use strict"});function Jt(t){for(let e of Vf){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Vf,wa=S(()=>{"use strict";Vf=[{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 ba=S(()=>{"use strict"});var ka=S(()=>{"use strict"});var $a=S(()=>{"use strict"});function va(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Sa(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=va(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(zt.test(r))return r;let n=va(t);return zt.test(n)?n:oi}function Ra(t,e){let r=new Set([...e].map(n=>n.toUpperCase()));if(!r.has(t.toUpperCase()))return t;for(let n=1;n<1e4;n++){let o=String(n),i=t.slice(0,10-o.length)+o;if(!r.has(i.toUpperCase()))return i}return t}function Kr(t){return`tasks/${t}/issue.yaml`}var xa,Dn,oi,zt,ii,N$,Ln,Hr,Ia=S(()=>{"use strict";xa=["bug","feature","epic"],Dn="feature",oi="TASK",zt=/^[A-Z][A-Z0-9]{1,9}$/;ii={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},N$=ii.backlog,Ln="tracker/config.yaml",Hr="tracker/counter"});var Ta=S(()=>{"use strict"});function Xt(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function Un(t){switch(t){case Wr.gitlab:return"oauth2";case Wr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Wr,Dt,Ca=S(()=>{"use strict";Wr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Dt="x-bitbucket-api-token-auth"});var Pa=S(()=>{"use strict"});var Ea=S(()=>{"use strict";Ta();Ca();Pa()});var ja,W=S(()=>{"use strict";Us();Bs();Ks();Ws();qs();Qo();ti();la();ni();ua();da();pa();fa();ga();ha();ya();wa();ba();ka();$a();Ia();Ea();ja=20});function M(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Pe=S(()=>{"use strict"});import{existsSync as Aa,renameSync as Jf}from"node:fs";function Lt(t,e,r=n=>console.error(n)){if(Aa(e)||!Aa(t))return!1;try{return Jf(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Bn=S(()=>{"use strict"});import{existsSync as Mn,readFileSync as _a,readdirSync as zf,writeFileSync as Xf}from"node:fs";import{dirname as Qf,join as mt}from"node:path";import{parse as Zf}from"yaml";function em(t=process.cwd()){let e=t;for(;;){if(Mn(mt(e,Je,"project.yaml")))return e;if(Mn(mt(e,si,"project.yaml")))return Lt(mt(e,si),mt(e,Je))&&rm(e),e;let r=Qf(e);if(r===e)return null;e=r}}function tm(t){let e=mt(t,Je);return Mn(e)?e:mt(t,si)}function rm(t){let e=mt(t,".gitignore");if(!Mn(e))return;let r=_a(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&&Xf(e,n)}function Ee(t=process.cwd()){let e=em(t);if(!e)return null;let r=tm(e),n=nm(_a(mt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Na(t,e,r){return zf(t).filter(o=>o!==".DS_Store").length===0?!0:e?r.some(o=>o.host===e.host&&o.owner===e.owner&&o.repoName===e.repoName):!1}function Gn(t,e=process.cwd()){try{let r=Ee(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function nm(t){let e=Zf(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 d=a.host,f=d==="bitbucket"?"bitbucket":d==="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 Oa(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 Je,si,it=S(()=>{"use strict";Bn();Je=".codepipe",si=".devpipe"});import{homedir as Da}from"node:os";import{mkdirSync as om,readFileSync as im,writeFileSync as sm,existsSync as ai}from"node:fs";import{dirname as Ua,join as Fn,resolve as am}from"node:path";import{fileURLToPath as cm}from"node:url";function Ba(t){let e=Fn(La,".env");if(ai(e)&&process.loadEnvFile(e),t){let r=Fn(La,"profiles",t,".env");ai(r)&&process.loadEnvFile(r)}}function Qt(t){let e=M("CONFIG");return e||(t?Fn(Da(),".codepipe","profiles",t,"config.json"):Fn(Da(),".codepipe","config.json"))}function Ue(t){let e=Qt(t);if(!ai(e))return null;let r=im(e,"utf-8");return JSON.parse(r)}function st(t,e){let r=Qt(e);om(Ua(r),{recursive:!0}),sm(r,JSON.stringify(t,null,2)+`
|
|
7
|
+
`,{mode:384})}function Hn(t){if(t)return{cfg:je(t),profile:t};let e;try{e=Ee()?.spec.projectId||void 0}catch{}if(e){let r=Ue(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:je(void 0),profile:void 0}}function je(t){let e=Ue(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 ${Qt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var La,$e=S(()=>{"use strict";Pe();it();La=am(Ua(cm(import.meta.url)),"..")});import{homedir as Ha}from"node:os";import{existsSync as Ka,mkdirSync as Wa,readFileSync as qa,writeFileSync as Ya}from"node:fs";import{dirname as Va,join as Ja}from"node:path";function za(t,e,r){let n=L(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},Q(n)}function Xa(t,e){let r=L(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],Q(r),!0)}function Qa(t){return Object.keys(L(t)?.secrets??{}).sort()}function Kn(t,e,r){let n=L(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,Q(n),"pinned")}function Za(t,e){let r=L(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],Q(r),!0):!1}function ze(t){return Ja(Ha(),".codepipe","secrets",`${t}.json`)}function L(t){let e=ze(t);return Ka(e)?JSON.parse(qa(e,"utf-8")):null}function Q(t){let e=ze(t.projectId);Wa(Va(e),{recursive:!0}),Ya(e,JSON.stringify(t,null,2)+`
|
|
8
|
+
`,{mode:384})}function Wn(){return Ja(Ha(),".codepipe","shared.json")}function ci(){let t=Wn();return Ka(t)?JSON.parse(qa(t,"utf-8")):null}function ec(t){let e=Wn();Wa(Va(e),{recursive:!0}),Ya(e,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function Zt(t){let e=L(t)?.claude?.oauthToken;return e||ci()?.claude?.oauthToken}function qr(t){let e=(r,n)=>{n&&!process.env[r]&&(process.env[r]=n)};e("GH_TOKEN",t.github?.token),e("BITBUCKET_EMAIL",t.bitbucket?.email),e("BITBUCKET_API_TOKEN",t.bitbucket?.apiToken),e("GITLAB_TOKEN",t.gitlab?.token),e("YOUTRACK_URL",t.youtrack?.url),e("YOUTRACK_TOKEN",t.youtrack?.token)}function er(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var ne=S(()=>{"use strict"});import{appendFileSync as lm,existsSync as rc,mkdirSync as um,renameSync as nc,statSync as dm,unlinkSync as pm}from"node:fs";import{Writable as fm}from"node:stream";import{join as mm}from"node:path";function qn(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=gm(process.env[`${t}_MAX_BYTES`]??String(oc.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):oc.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function gm(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),n=(e[2]??"").toLowerCase();return n==="g"?r*1024**3:n==="m"?r*1024**2:n==="k"?r*1024:r}function Yn(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...i)=>{n(...i);try{t.writeLine(hm(o,i))}catch{}};return console.log=r(e.log,"INFO"),console.warn=r(e.warn,"WARN"),console.error=r(e.error,"ERROR"),()=>{console.log=e.log,console.warn=e.warn,console.error=e.error}}function hm(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:ym(o)).join(" ");return`${r} ${t} ${n}`}function ym(t){try{return JSON.stringify(t)}catch{return String(t)}}var oc,tr,li=S(()=>{"use strict";oc={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},tr=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&um(e.dir,{recursive:!0}),this.currentPath=mm(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
|
|
10
10
|
`)?e:e+`
|
|
11
|
-
`;
|
|
11
|
+
`;lm(this.currentPath,r,"utf-8")}asWritable(){return new fm({write:(e,r,n)=>{try{let o=typeof e=="string"?e:e.toString("utf-8");for(let i of o.split(/\r?\n/))i&&this.writeLine(i);n()}catch(o){n(o)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!rc(this.currentPath)||dm(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;rc(n)&&(r>=this.cfg.maxFiles?pm(n):nc(n,`${this.currentPath}.${r+1}`))}nc(this.currentPath,`${this.currentPath}.1`)}}}});import{existsSync as gt,mkdirSync as fc,readFileSync as fi,writeFileSync as rr}from"node:fs";import{homedir as Am}from"node:os";import{join as Xe}from"node:path";import{simpleGit as _m}from"simple-git";function Vr(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Xe(t,o);gt(s)||(rr(s,i),r.push(o))}return r}function Ut(t,e,r){let n=Xe(Am(),".codepipe","profiles",t,"context-config");return fc(n,{recursive:!0}),rr(Xe(n,"project.yaml"),e.projectYaml),rr(Xe(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 nr){let o=Xe(e,n),i=Xe(t,n);if(!(!gt(o)||gt(i)))try{rr(i,fi(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${n}: ${s instanceof Error?s.message:String(s)}`)}}}function or(t){let e=Xe(t,".gitignore"),r=gt(e)?fi(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(nr.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
12
12
|
`)?"":`
|
|
13
|
-
`;return
|
|
13
|
+
`;return rr(e,r+i+Nm.join(`
|
|
14
14
|
`)+`
|
|
15
|
-
`),!0}async function
|
|
16
|
-
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;
|
|
17
|
-
`)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);
|
|
15
|
+
`),!0}async function mc(t,e){try{if(!gt(Xe(t,".git")))return;let r=_m(t),n=(await r.raw(["ls-files","--",...nr])).split(`
|
|
16
|
+
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;or(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 hi(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 mi(t){let e=new Map;for(let r of nr){let n=Xe(t,r);gt(n)&&e.set(r,fi(n))}return e}function gi(t,e){fc(t,{recursive:!0});for(let[r,n]of e){let o=Xe(t,r);gt(o)||rr(o,n)}}var nr,Nm,at=S(()=>{"use strict";ht();nr=["project.yaml","regimen.yaml"];Nm=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Om,mkdirSync as Dm,rmSync as Lm,writeFileSync as yi}from"node:fs";import{dirname as Um,isAbsolute as Bm,join as yc,normalize as Zn}from"node:path";import{simpleGit as wc}from"simple-git";async function wi(t,e){let r=Zn(t),o=(Qn.get(r)??Promise.resolve()).catch(()=>{}).then(e);Qn.set(r,o);try{return await o}finally{Qn.get(r)===o&&Qn.delete(r)}}async function ct(t,e,r){return wi(t,()=>bi(t,e,r))}async function bi(t,e,r){if(!Om(yc(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=ue(t,a.path);if(a.deleted){Lm(c,{force:!0});continue}Dm(Um(c),{recursive:!0}),a.encoding==="base64"?yi(c,Buffer.from(a.content,"base64")):yi(c,a.content)}let n=wc(t),o=e.filter(a=>!a.deleted).map(a=>a.path),i=e.filter(a=>a.deleted).map(a=>a.path);for(let a=0;a<o.length;a+=Xn)await n.raw(["add","-A","-f","--",...o.slice(a,a+Xn)]);for(let a=0;a<i.length;a+=Xn)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+Xn)]);await n.raw(["reset","-q","--",...nr]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await hi(t))}async function hi(t){let e=wc(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=gc;n++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let i=await Fm(e);if(i.length>0&&i.every(a=>Mm.has(a)||hc.test(a))){for(let a of i)hc.test(a)?await Gm(e,t,a):await e.raw(["checkout","--theirs","--",a]);await e.add(i),await e.raw(["-c","core.editor=true","rebase","--continue"])}else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${i.join(", ")||"unknown files"} \u2014 concurrent writers edited the same entry; resolve manually in the Context Repo`)}}throw new Error(`context push failed after ${gc} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Gm(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
|
|
17
|
+
`)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);yi(ue(e,r),i.join(`
|
|
18
18
|
`)+(i.length>0?`
|
|
19
|
-
`:""))}async function
|
|
20
|
-
`).map(r=>r.trim()).filter(Boolean)}function
|
|
21
|
-
`+t.slice(t.length-e)}async function yt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let i=(await n.json()).login??"ok",s=n.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(c.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function ro(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o;try{o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(o.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!o.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${o.status} ${o.statusText}`);if((await o.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function wt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o;try{o=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(o.ok)return t;if(o.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await Jm(o);throw o.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):o.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):o.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${o.status} ${o.statusText}${i}`)}async function Jm(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function no(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=$c.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${$c.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function kt(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(n){throw new Error(`cannot reach gitlab.com (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function vc(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}function zm(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}function ki(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 $i(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new bi(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new vi(e)}return new xi}var Mt,$c,bi,$i,vi,xi,bt=R(()=>{"use strict";Mt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};$c=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];bi=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new Mt(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},$i=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new Mt(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let d=await i.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(s.ok){let d=await s.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}`,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??[],d=[];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 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}
|
|
19
|
+
`:""))}async function Fm(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
20
|
+
`).map(r=>r.trim()).filter(Boolean)}function ue(t,e){if(Bm(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Zn(yc(t,e)),n=Zn(t+"/");if(r!==Zn(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var gc,Mm,hc,Xn,Qn,ht=S(()=>{"use strict";at();gc=3,Mm=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),hc=/^tasks\/[^/]+\/comments\.jsonl$/,Xn=500,Qn=new Map});function Sc(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
21
|
+
`+t.slice(t.length-e)}async function yt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let i=(await n.json()).login??"ok",s=n.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(c.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function to(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o;try{o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(o.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!o.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${o.status} ${o.statusText}`);if((await o.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function wt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o;try{o=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(o.ok)return t;if(o.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await tg(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 tg(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ro(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=Rc.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: ${Rc.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function bt(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(n){throw new Error(`cannot reach gitlab.com (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function Ic(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 rg(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 $i(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 Be(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new xi(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new vi(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Si(e)}return new Ri}var Bt,Rc,vi,xi,Si,Ri,kt=S(()=>{"use strict";Bt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};Rc=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];vi=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 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 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()}`)}},xi=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 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 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 d=await i.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(s.ok){let d=await s.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}`,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??[],d=[];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 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
22
|
|
|
23
|
-
${
|
|
23
|
+
${Sc(y,8e3)}`)}}return d.length===0?void 0:Sc(d.join(`
|
|
24
24
|
|
|
25
|
-
`),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},
|
|
25
|
+
`),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Si=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new 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 i=await o.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=rg(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let d=await a.json().catch(()=>null);s=d?.sha??d?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};Ri=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($i(e,r,"merge"))}async closePR(e,r,n){throw new Error($i(e,r,"close"))}async addPRComment(e,r,n){throw new Error($i(e,r,"comment"))}}});import{existsSync as $t,readFileSync as ir,readdirSync as Cc}from"node:fs";import{join as Ii}from"node:path";import{simpleGit as Pc}from"simple-git";import{parse as Ec}from"yaml";function jc(t){try{let e=ue(t,Ln);if(!$t(e))return null;let r=Ec(ir(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!zt.test(n)?null:{prefix:n}}catch{return null}}function Ac(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
26
26
|
# The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
|
|
27
27
|
# later would orphan existing tasks/<KEY>/ directories.
|
|
28
28
|
prefix: ${t}
|
|
@@ -30,15 +30,15 @@ prefix: ${t}
|
|
|
30
30
|
# Statuses are the built-in default set for now:
|
|
31
31
|
# Backlog | To Do | In Progress | Review | Done | Rejected
|
|
32
32
|
# A configurable status set / pipeline mapping is a planned extension.
|
|
33
|
-
`}function
|
|
34
|
-
`}function
|
|
33
|
+
`}function Ti(t=0){return`${t}
|
|
34
|
+
`}function ng(t){return t==="depends_on"||t==="subtask"}function og(t){let e;try{e=Ec(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=xa.includes(r.type)?r.type:Dn,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;ng(l.type)&&typeof l.target=="string"&&l.target&&o.push({type:l.type,targetKey:l.target})}let i=typeof r.created=="string"?r.created:new Date(0).toISOString(),s=typeof r.updated=="string"?r.updated:i,a=typeof r.assignee=="string"&&r.assignee.trim().length>0?r.assignee.trim():void 0;return{key:r.key,title:r.title,type:n,status:typeof r.status=="string"&&r.status?r.status:"Backlog",...a?{assignee:a}:{},links:o,created:i,updated:s}}function Ci(t){let e=[`key: ${t.key}`,`title: ${JSON.stringify(t.title)}`,`type: ${t.type}`,`status: ${JSON.stringify(t.status)}`];if(t.assignee&&e.push(`assignee: ${JSON.stringify(t.assignee)}`),t.links.length>0){e.push("links:");for(let r of t.links)e.push(` - type: ${r.type}`,` target: ${r.targetKey}`)}return e.push(`created: ${t.created}`,`updated: ${t.updated}`),e.join(`
|
|
35
35
|
`)+`
|
|
36
|
-
`}function zr(t,e){let r=
|
|
36
|
+
`}function zr(t,e){let r=ue(t,Kr(e));return $t(r)?og(ir(r,"utf-8")):null}function _c(t){let e=Ii(t,"tasks");if(!$t(e))return[];let r=[];for(let n of Cc(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=zr(t,n.name);o&&r.push(o)}return r}function ig(t,e){let r=ue(t,`tasks/${e}/task.md`);if(!$t(r))return;let n=ir(r,"utf-8").split(`
|
|
37
37
|
`),o=n.indexOf("---");if(o<0)return;let i=n.slice(o+1),s=i.lastIndexOf("## Attachments");s>=0&&i.slice(s+1).every(d=>d.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(d.trim()))&&(i=i.slice(0,s));let a=i.join(`
|
|
38
|
-
`).trim();if(!(!a||a==="_(no description)_"))return a}function Xr(t,e,r={}){let n=r.withDescription?
|
|
38
|
+
`).trim();if(!(!a||a==="_(no description)_"))return a}function Xr(t,e,r={}){let n=r.withDescription?ig(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:sg(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function sg(t){return t.charAt(0).toUpperCase()+t.slice(1)}function ag(t){let e=ue(t,Hr);if(!$t(e))return 0;let r=Number.parseInt(ir(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function cg(t,e){let r=Ii(t,"tasks");if(!$t(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of Cc(r,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=n.exec(i.name);if(!s)continue;let a=Number.parseInt(s[1],10);Number.isFinite(a)&&a>o&&(o=a)}return o}function lg(t,e){return Math.max(ag(t),cg(t,e))+1}async function Nc(t,e,r,n){return wi(t,()=>ug(t,e,r,n))}async function ug(t,e,r,n){if(!$t(Ii(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Jr(t);let o=null;for(let i=0;i<Tc;i++){let s=lg(t,e),a=`${e}-${s}`,c=[...r(a),{path:Hr,content:Ti(s)}];try{return await bi(t,c,n(a)),a}catch(l){if(o=l,await pg(t,n(a)),await Jr(t),dg(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Tc} attempts: ${o instanceof Error?o.message:String(o)}`)}function dg(t,e){for(let r of e){let n=ue(t,r.path);if(!$t(n)||(r.encoding==="base64"?ir(n).toString("base64"):ir(n,"utf-8"))!==r.content)return!1}return!0}async function Jr(t){let e=Pc(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 pg(t,e){let r=Pc(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
|
|
39
39
|
`)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
|
|
40
40
|
`).some(i=>i.trim()===e.split(`
|
|
41
|
-
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var
|
|
41
|
+
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Tc,no=S(()=>{"use strict";W();ht();Tc=5});function sr(t,e,r,n){return[{path:"README.md",content:xg(t,e)},{path:".gitignore",content:yg()},{path:"CLAUDE.md",content:bg(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:wg()},{path:"knowledge/README.md",content:kg()},{path:"knowledge/build.yaml",content:vg()},{path:"actions/README.md",content:$g()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:hg()},{path:"adr/README.md",content:fg()},{path:"adr/0000-template.md",content:mg()},{path:"adr/INDEX.md",content:gg()},{path:Ye,content:Nn()},...t.trackerProvider==="internal"?[{path:Ln,content:Ac(t.youtrackProjectKey??oi)},{path:Hr,content:Ti()}]:[]]}function fg(){return`# ADR \u2014 architecture decision records
|
|
42
42
|
|
|
43
43
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
44
44
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -66,7 +66,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
66
66
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
67
67
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
68
68
|
open a PR to this repository.
|
|
69
|
-
`}function
|
|
69
|
+
`}function mg(){return`# ADR-NNNN: <title>
|
|
70
70
|
|
|
71
71
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
72
72
|
- **Date:** YYYY-MM-DD
|
|
@@ -88,12 +88,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
88
88
|
## Alternatives considered
|
|
89
89
|
|
|
90
90
|
- **<alternative>** \u2014 why it was rejected.
|
|
91
|
-
`}function
|
|
91
|
+
`}function gg(){return`# ADR index
|
|
92
92
|
|
|
93
93
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
94
94
|
|
|
95
95
|
(no accepted ADRs yet)
|
|
96
|
-
`}function
|
|
96
|
+
`}function hg(){return`# Audit
|
|
97
97
|
|
|
98
98
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
99
99
|
project appends only to its own file \u2014
|
|
@@ -102,14 +102,14 @@ project appends only to its own file \u2014
|
|
|
102
102
|
|
|
103
103
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
104
104
|
shared aggregate here.
|
|
105
|
-
`}function
|
|
105
|
+
`}function Qe(t,e,r,n,o="auto",i=Ve,s){let a=t.trackerProvider==="internal";return{projectYaml:a?Sg(t,o):Rg(t,r,n,o),regimenYaml:Ig(t.automationLevel,a?!0:e,a,i,s)}}function yg(){return`# codepipe project config is local to each member's workspace
|
|
106
106
|
project.yaml
|
|
107
107
|
regimen.yaml
|
|
108
108
|
|
|
109
109
|
# codepipe runtime
|
|
110
110
|
session.log
|
|
111
111
|
apply-queue.json
|
|
112
|
-
`}function
|
|
112
|
+
`}function wg(){return`# Index prompt
|
|
113
113
|
|
|
114
114
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
115
115
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -166,7 +166,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
166
166
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
167
167
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
168
168
|
empty or unavailable, say so briefly rather than inventing content.
|
|
169
|
-
`}function
|
|
169
|
+
`}function bg(t){return`# Project context for the CodePipe agent
|
|
170
170
|
|
|
171
171
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
172
172
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -194,7 +194,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
194
194
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
195
195
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
196
196
|
only after the analysis is approved.
|
|
197
|
-
`}function
|
|
197
|
+
`}function kg(){return`# Knowledge
|
|
198
198
|
|
|
199
199
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
200
200
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -211,7 +211,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
211
211
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
212
212
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
213
213
|
any merge conflict in it as noise (either side converges on the next run).
|
|
214
|
-
`}function
|
|
214
|
+
`}function $g(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
|
|
215
215
|
|
|
216
216
|
One \`<id>.yml\` per action. Every file here appears as a button on the
|
|
217
217
|
project's **RUN** tab; an action with \`params\` opens a small wizard first.
|
|
@@ -250,7 +250,7 @@ steps:
|
|
|
250
250
|
Parameter values are passed to the commands **only as env vars** \u2014 reference
|
|
251
251
|
them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
|
|
252
252
|
command text itself.
|
|
253
|
-
`}function
|
|
253
|
+
`}function vg(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
254
254
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
255
255
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
256
256
|
#
|
|
@@ -266,7 +266,7 @@ command text itself.
|
|
|
266
266
|
# - name: test
|
|
267
267
|
# run: npm test
|
|
268
268
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
269
|
-
`}function
|
|
269
|
+
`}function xg(t,e){return`# ${e.name}
|
|
270
270
|
|
|
271
271
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
272
272
|
|
|
@@ -292,7 +292,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
292
292
|
pipeline \u2014 don't edit them by hand.
|
|
293
293
|
|
|
294
294
|
Automation level: **${t.automationLevel}**.
|
|
295
|
-
`}function
|
|
295
|
+
`}function Sg(t,e="auto"){return`# Project description for CodePipe.
|
|
296
296
|
id: ${t.projectId}
|
|
297
297
|
name: ${t.name}
|
|
298
298
|
|
|
@@ -315,15 +315,15 @@ branch:
|
|
|
315
315
|
pattern: codepipe/<TASK_ID>
|
|
316
316
|
|
|
317
317
|
repos:
|
|
318
|
-
${
|
|
319
|
-
`}function
|
|
318
|
+
${Oc(t)}
|
|
319
|
+
`}function Oc(t){return t.repos.length===0?` [] # add repos here
|
|
320
320
|
`:t.repos.map(e=>` - name: ${e.name}
|
|
321
321
|
host: ${e.host}
|
|
322
322
|
owner: ${e.owner}
|
|
323
323
|
repo: ${e.repoName}
|
|
324
324
|
mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
|
|
325
325
|
default_branch: ${e.defaultBranch}`:"")).join(`
|
|
326
|
-
`)}function
|
|
326
|
+
`)}function Rg(t,e,r,n="auto"){let o=e?`
|
|
327
327
|
tracker_url: ${e}`:`
|
|
328
328
|
# tracker_url: https://your.youtrack.cloud`,i=r?`require_assignee: true
|
|
329
329
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -371,7 +371,7 @@ ${jc(t)}
|
|
|
371
371
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
372
372
|
${i}`:` # project_key: \u2026
|
|
373
373
|
# tracker_url: https://your.youtrack.cloud
|
|
374
|
-
poll_interval_sec: 60`,a=
|
|
374
|
+
poll_interval_sec: 60`,a=Oc(t);return`# Project description for CodePipe.
|
|
375
375
|
id: ${t.projectId}
|
|
376
376
|
name: ${t.name}
|
|
377
377
|
|
|
@@ -402,7 +402,36 @@ branch:
|
|
|
402
402
|
|
|
403
403
|
repos:
|
|
404
404
|
${a}
|
|
405
|
-
`}function
|
|
405
|
+
`}function Ig(t,e,r=!1,n=Ve,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
|
|
406
|
+
# model in the recommended per-role split, so CodePipe set a single default
|
|
407
|
+
# your subscription can serve for all roles. Tune per role later from the
|
|
408
|
+
# dashboard (Project Settings \u2192 llm.models) or by editing this file.
|
|
409
|
+
models:
|
|
410
|
+
default: ${o}`:` # Per-role model selection (Claude cost optimization). Run cheap,
|
|
411
|
+
# mechanical roles on a smaller model and architectural / code roles on the
|
|
412
|
+
# capable one. Values are aliases (opus | sonnet | haiku) \u2014 Claude Code
|
|
413
|
+
# resolves each to the current version of that tier \u2014 or a pinned id
|
|
414
|
+
# (e.g. claude-opus-4-8). The values below are the recommended defaults and
|
|
415
|
+
# are also what applies when this whole section is omitted.
|
|
416
|
+
models:
|
|
417
|
+
# Catch-all for any role not listed below.
|
|
418
|
+
default: opus
|
|
419
|
+
# Architectural analysis of the task.
|
|
420
|
+
analyze: opus
|
|
421
|
+
# Writing the implementation.
|
|
422
|
+
implement: opus
|
|
423
|
+
# Re-implementing after rework feedback.
|
|
424
|
+
rework: opus
|
|
425
|
+
# Informational implementation estimate.
|
|
426
|
+
estimate: sonnet
|
|
427
|
+
# Driving / repairing the lint/build/test run (BUILD phase).
|
|
428
|
+
build: sonnet
|
|
429
|
+
# Reviewing the implemented change before the PR (CODE_REVIEW phase).
|
|
430
|
+
code-review: opus
|
|
431
|
+
# Drafting a new issue from the Quick-task panel.
|
|
432
|
+
draft: sonnet
|
|
433
|
+
# One-shot repository indexing at registration.
|
|
434
|
+
index: opus`;return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
|
|
406
435
|
automation:
|
|
407
436
|
level: ${t}
|
|
408
437
|
|
|
@@ -414,11 +443,11 @@ ${r?` # The built-in tracker is CodePipe's own \u2014 these switches stay on (t
|
|
|
414
443
|
# These flags are set from a dedicated 'codepipe init' question and do
|
|
415
444
|
# NOT depend on automation.level \u2014 the two are orthogonal axes (writes vs gates).`}
|
|
416
445
|
writes:
|
|
417
|
-
enabled: ${
|
|
418
|
-
status_changes: ${
|
|
419
|
-
pr_comment: ${
|
|
446
|
+
enabled: ${s}
|
|
447
|
+
status_changes: ${s}
|
|
448
|
+
pr_comment: ${s}
|
|
420
449
|
# Mirror dashboard comments back into YouTrack. Off without enabled.
|
|
421
|
-
dashboard_mirror: ${
|
|
450
|
+
dashboard_mirror: ${s}
|
|
422
451
|
# YT column (Stage) for new drafts published from PLAN.
|
|
423
452
|
# Backlog by default \u2192 the task shows up in the TODO section, not straight in WORK.
|
|
424
453
|
draft_target_status: Backlog
|
|
@@ -433,10 +462,10 @@ gates:
|
|
|
433
462
|
# 'assisted' requires a manual Run/Approve at each. Names and modes mirror
|
|
434
463
|
# docs/PIPELINE.md so a future per-gate parser stays config-compatible.
|
|
435
464
|
# Modes: always | auto_below_hours | never.
|
|
436
|
-
G1_estimate: { mode: ${
|
|
437
|
-
G2_solution: { mode: ${
|
|
438
|
-
G3_implementation: { mode: ${
|
|
439
|
-
G4_apply: { mode: ${
|
|
465
|
+
G1_estimate: { mode: ${i?"never":"always"} }
|
|
466
|
+
G2_solution: { mode: ${i?"never":"always"} }
|
|
467
|
+
G3_implementation: { mode: ${i?"never":"always"} }
|
|
468
|
+
G4_apply: { mode: ${i?"never":"always"} }
|
|
440
469
|
# The first ACTUALLY consumed key of the gates block. When true (the
|
|
441
470
|
# default), a task taken from a source stage lands in the QUEUE section
|
|
442
471
|
# (QUEUED) and waits for a single Confirm; the Confirm pulls in the
|
|
@@ -502,31 +531,7 @@ llm:
|
|
|
502
531
|
# LLM backend for this project. Currently only \`claude\` is supported;
|
|
503
532
|
# this line is the anchor for future providers.
|
|
504
533
|
provider: ${n}
|
|
505
|
-
|
|
506
|
-
# mechanical roles on a smaller model and architectural / code roles on the
|
|
507
|
-
# capable one. Values are aliases (opus | sonnet | haiku) \u2014 Claude Code
|
|
508
|
-
# resolves each to the current version of that tier \u2014 or a pinned id
|
|
509
|
-
# (e.g. claude-opus-4-8). The values below are the recommended defaults and
|
|
510
|
-
# are also what applies when this whole section is omitted.
|
|
511
|
-
models:
|
|
512
|
-
# Catch-all for any role not listed below.
|
|
513
|
-
default: opus
|
|
514
|
-
# Architectural analysis of the task.
|
|
515
|
-
analyze: opus
|
|
516
|
-
# Writing the implementation.
|
|
517
|
-
implement: opus
|
|
518
|
-
# Re-implementing after rework feedback.
|
|
519
|
-
rework: opus
|
|
520
|
-
# Informational implementation estimate.
|
|
521
|
-
estimate: sonnet
|
|
522
|
-
# Driving / repairing the lint/build/test run (BUILD phase).
|
|
523
|
-
build: sonnet
|
|
524
|
-
# Reviewing the implemented change before the PR (CODE_REVIEW phase).
|
|
525
|
-
code-review: opus
|
|
526
|
-
# Drafting a new issue from the Quick-task panel.
|
|
527
|
-
draft: sonnet
|
|
528
|
-
# One-shot repository indexing at registration.
|
|
529
|
-
index: opus
|
|
534
|
+
${a}
|
|
530
535
|
|
|
531
536
|
# Concurrency is not a per-project setting: it is the operator-set per-account
|
|
532
537
|
# sandbox quota (how many runners the account may occupy), enforced by the HUB
|
|
@@ -541,19 +546,19 @@ llm:
|
|
|
541
546
|
# # the previous task's branch (auto-merge without reworking the
|
|
542
547
|
# # tail of the chain).
|
|
543
548
|
# mode: parallel
|
|
544
|
-
`}var
|
|
545
|
-
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Vg(t,e,r){return new Promise((n,o)=>{let i=vt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new el(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function ji(t,e,r){return new Promise(n=>{let o=vt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function Jg(t){try{let e=await fetch(t);return e.ok?new el(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function il(t,e=443,r=rl){let n=`${t}:${e}`,o=Zc.get(n);if(o)return o;let i=zg(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Zc.set(n,i),i}async function zg(t,e,r){if(!tl)return!1;let n=8e3;if(await ji(t,e,n))return!0;let o=await Vg(t,e,n),i=vt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Yg(o);if(!c)break;let l=await Jg(c);if(!l)break;if(s.push(l.toString()),vt.setDefaultCACertificates([...i,...s]),await ji(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return ji(t,e,n)}var tl,Qc,Zc,rl,sl=R(()=>{"use strict";Te();tl=typeof vt.getCACertificates=="function"&&typeof vt.setDefaultCACertificates=="function",Qc=!1,Zc=new Map,rl=t=>console.warn(t)});function ul(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function je(t,e,r){nl();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,i={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,i)}catch(s){if(ol(s)&&await il(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Xg(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Qg(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function Ai(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Qg(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await je(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&&Xg(l.status,d)){await al(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${d}`)}if(c<o){await al(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function xt(t){let e;try{e=await je(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 je(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Zg(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=cl.get(o);if(i)return i;let s=await je(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(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 cl.set(o,l.id),l.id}async function pl(t,e,r,n=rn){let o=await Zg(t,e,r,n);await Ai(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function fl(t,e,r){return await(await Ai(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function ml(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Ai(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function gl(t,e){let r=ll.get(e);if(r)return r;let n=await je(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return ll.set(e,i.id),i.id}async function hl(t,e,r,n,o,i=rn){let s=await gl(t,e),a=await je(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function yl(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await je(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 bl(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function $l(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function vl(t,e){let r=e.stageField??rn,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${kl}&$top=200`,s=await je(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Rl(c,r))}async function xl(t,e,r=rn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${kl}`,o=await je(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Rl(await o.json(),r)}async function Sl(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${th}&$top=500`,o=await je(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=bl(s.attachments);return c&&(a.attachments=c),a})}function rh(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Rl(t,e=rn){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=bl(t.attachments);a&&(s.attachments=a);let c=rh(t.links);return c&&(s.links=c),s}async function Il(t,e){let r=await nh(t,e);return r.length>0?r:oh(t,e)}async function nh(t,e){let r=await gl(t,e),n=await je(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:Tl(s.bundle)});return i}async function oh(t,e){let r=`project: ${e}`,n=await je(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:Tl(s.projectCustomField?.bundle)});return i}function Tl(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var al,rn,cl,ll,wl,eh,kl,th,Ft=R(()=>{"use strict";sl();al=t=>new Promise(e=>setTimeout(e,t));rn="Stage",cl=new Map;ll=new Map;wl="attachments(id,name,url,size,mimeType)",eh="links(direction,linkType(name),issues(idReadable))",kl=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${wl},${eh}`,th=`id,text,created,author(login),${wl}`});function nn(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function on(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function sn(t,e=process.env){if(!t)return!1;let r=`https://${Lt}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Ni(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function Pl(t,e=process.env){return Ni(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>nn(t,e),e)}function El(t,e=process.env){return Ni(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>on(t,e),e)}function jl(t,e=process.env){return Ni(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Lt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>sn(t,e),e)}var co=R(()=>{"use strict";K()});import{homedir as _h}from"node:os";import{existsSync as Nh,mkdirSync as Oh,readFileSync as Dh,writeFileSync as Lh}from"node:fs";import{dirname as Uh,join as Bh}from"node:path";function Bi(){return G("FARM_PINS")??Bh(_h(),".codepipe","farm-pins.json")}function Xl(){let t=Bi();if(!Nh(t))return{};try{return JSON.parse(Dh(t,"utf-8"))}catch{return{}}}function Mh(t){let e=Bi();Oh(Uh(e),{recursive:!0}),Lh(e,JSON.stringify(t,null,2)+`
|
|
546
|
-
`,{mode:384})}function
|
|
549
|
+
`}var Mt=S(()=>{"use strict";W();no()});import{createCipheriv as Wg,createDecipheriv as qg,createHash as Yg,createPrivateKey as Vg,createPublicKey as Ai,diffieHellman as Xc,generateKeyPairSync as Qc,hkdfSync as Zc,randomBytes as Jg}from"node:crypto";function so(){let{publicKey:t,privateKey:e}=Qc("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(Yg("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function lt(t,e){let r=Ai({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Qc("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Xc({privateKey:o,publicKey:r}),c=Buffer.from(Zc("sha256",a,Buffer.concat([i,s]),el,32)),l=Jg(12),d=Wg("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:i.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 cr(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=Vg({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Ai({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Ai(n).export({type:"spki",format:"der"}),a=Xc({privateKey:n,publicKey:o}),c=Buffer.from(Zc("sha256",a,Buffer.concat([i,s]),el,32)),l=qg("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 el,Ae=S(()=>{"use strict";el=Buffer.from("devpipe-sealedbox-v1","utf-8")});import{X509Certificate as ol}from"node:crypto";import{readFileSync as Xg}from"node:fs";import vt from"node:tls";function Qg(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function al(t=sl){if(rl)return;rl=!0;let e=M("EXTRA_CA_FILE");if(!(!e||!il))try{let r=Qg(Xg(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}vt.setDefaultCACertificates([...vt.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function cl(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 Zg(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
550
|
+
`)){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 i=vt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new ol(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function _i(t,e,r){return new Promise(n=>{let o=vt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function th(t){try{let e=await fetch(t);return e.ok?new ol(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function ll(t,e=443,r=sl){let n=`${t}:${e}`,o=nl.get(n);if(o)return o;let i=rh(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return nl.set(n,i),i}async function rh(t,e,r){if(!il)return!1;let n=8e3;if(await _i(t,e,n))return!0;let o=await eh(t,e,n),i=vt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Zg(o);if(!c)break;let l=await th(c);if(!l)break;if(s.push(l.toString()),vt.setDefaultCACertificates([...i,...s]),await _i(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 _i(t,e,n)}var il,rl,nl,sl,ul=S(()=>{"use strict";Pe();il=typeof vt.getCACertificates=="function"&&typeof vt.setDefaultCACertificates=="function",rl=!1,nl=new Map,sl=t=>console.warn(t)});function ml(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function _e(t,e,r){al();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(cl(s)&&await ll(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function nh(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function oh(){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 Ni(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=oh(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await _e(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&&nh(l.status,d)){await dl(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${d}`)}if(c<o){await dl(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function xt(t){let e;try{e=await _e(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 gl(t){try{let e=await _e(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function ih(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=pl.get(o);if(i)return i;let s=await _e(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(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 pl.set(o,l.id),l.id}async function hl(t,e,r,n=rn){let o=await ih(t,e,r,n);await Ni(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 yl(t,e,r){return await(await Ni(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function wl(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Ni(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function bl(t,e){let r=fl.get(e);if(r)return r;let n=await _e(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 fl.set(e,i.id),i.id}async function kl(t,e,r,n,o,i=rn){let s=await bl(t,e),a=await _e(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 $l(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await _e(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 Sl(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 Rl(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 Il(t,e){let r=e.stageField??rn,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${xl}&$top=200`,s=await _e(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Pl(c,r))}async function Tl(t,e,r=rn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${xl}`,o=await _e(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Pl(await o.json(),r)}async function Cl(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${ah}&$top=500`,o=await _e(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=Sl(s.attachments);return c&&(a.attachments=c),a})}function ch(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 Pl(t,e=rn){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Sl(t.attachments);a&&(s.attachments=a);let c=ch(t.links);return c&&(s.links=c),s}async function El(t,e){let r=await lh(t,e);return r.length>0?r:uh(t,e)}async function lh(t,e){let r=await bl(t,e),n=await _e(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:jl(s.bundle)});return i}async function uh(t,e){let r=`project: ${e}`,n=await _e(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:jl(s.projectCustomField?.bundle)});return i}function jl(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var dl,rn,pl,fl,vl,sh,xl,ah,Gt=S(()=>{"use strict";ul();dl=t=>new Promise(e=>setTimeout(e,t));rn="Stage",pl=new Map;fl=new Map;vl="attachments(id,name,url,size,mimeType)",sh="links(direction,linkType(name),issues(idReadable))",xl=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${vl},${sh}`,ah=`id,text,created,author(login),${vl}`});function Me(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Al(t,e){let r=L(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await xt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:Me(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Me(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await yt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"github",ok:!1,detail:Me(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Me(c),checkedAt:i()})}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await wt(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"bitbucket",ok:!1,detail:Me(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Me(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await bt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"gitlab",ok:!1,detail:Me(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Me(c),checkedAt:i()})}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let d of e?.repos??[])if(d.host==="github")try{await to(c,d.owner,d.repoName),n.push({name:`repo:${d.name}`,ok:!0})}catch(f){n.push({name:`repo:${d.name}`,ok:!1,detail:Me(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await to(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(d){n.push({name:"context-repo",ok:!1,detail:Me(d)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await to(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){o.push({kind:"contextWrite",present:!0,ok:!1,detail:Me(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=Zt(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Oi(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Oi(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)}}async function _l(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1000",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});if(n.status!==200)return null;let i=(await n.json())?.data;if(!Array.isArray(i))return null;let s=[];for(let a of i){let c=a?.id;if(typeof c!="string"||c.trim().length===0)continue;let l=a?.created_at;s.push({id:c,...typeof l=="string"?{createdAt:l}:{}})}return s}catch{return null}finally{clearTimeout(r)}}var ao=S(()=>{"use strict";ne();kt();Gt()});function nn(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function on(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function sn(t,e=process.env){if(!t)return!1;let r=`https://${Dt}:${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 Di(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 Nl(t,e=process.env){return Di(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>nn(t,e),e)}function Ol(t,e=process.env){return Di(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>on(t,e),e)}function Dl(t,e=process.env){return Di(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Dt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>sn(t,e),e)}var co=S(()=>{"use strict";W()});import{homedir as Bh}from"node:os";import{existsSync as Mh,mkdirSync as Gh,readFileSync as Fh,writeFileSync as Hh}from"node:fs";import{dirname as Kh,join as Wh}from"node:path";function Gi(){return M("FARM_PINS")??Wh(Bh(),".codepipe","farm-pins.json")}function ru(){let t=Gi();if(!Mh(t))return{};try{return JSON.parse(Fh(t,"utf-8"))}catch{return{}}}function qh(t){let e=Gi();Gh(Kh(e),{recursive:!0}),Hh(e,JSON.stringify(t,null,2)+`
|
|
551
|
+
`,{mode:384})}function Yh(t){return ru()[t]}function go(t,e){let r=ru();r[t]=e,qh(r)}function ho(t,e){let r=be(e),n=Yh(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 ${Gi()}.`);return r}var Fi=S(()=>{"use strict";Pe();Ae()});import{setTimeout as Vh}from"node:timers/promises";import Jh from"ws";function yo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Jh(r)}async function St(t,e,r){return Ge(t,e,"/projects",r)}async function nu(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function wo(t,e,r,n){return Ge(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function ou(t,e,r,n){return Ge(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function iu(t,e,r,n){return Ge(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function su(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new N(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function bo(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Hi(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function au(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Hi(t,e),a=new Set;for(let c of s)c.id!==r.excludeProjectId&&c.trackerProvider==="internal"&&c.youtrackProjectKey&&a.add(c.youtrackProjectKey.toUpperCase());return a}catch(s){o=s,i<n-1&&await Vh(r.delayMs??1500)}throw o}async function cu(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new un(e)}if(!r.ok)throw new N(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function lu(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new N(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function uu(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function du(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new N(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function pu(t,e,r,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function fu(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function mu(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function gu(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function dn(t,e,r,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Ki(t,e,r,n){await Ge(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function hu(t,e,r,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function yu(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new N(o.status,s,a)}return s}async function V(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function Ge(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new N(o.status,s,a)}return s}var N,un,fe=S(()=>{"use strict";N=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};un=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{execFileSync as wy}from"node:child_process";import{mkdtempSync as by,mkdirSync as ky,readFileSync as Lu,rmSync as $y,writeFileSync as vy}from"node:fs";import{tmpdir as xy}from"node:os";import{dirname as Sy,join as Uu}from"node:path";function Bu(t="codepipe-context"){let e=by(Uu(xy(),"codepipe-ssh-")),r=Uu(e,"id_ed25519");try{return wy("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Lu(r,"utf-8"),publicKey:Lu(`${r}.pub`,"utf-8").trim()}}finally{$y(e,{recursive:!0,force:!0})}}async function Mu(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function Gu(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 Fu(t,e){ky(Sy(t),{recursive:!0});let r=e.endsWith(`
|
|
547
552
|
`)?e:e+`
|
|
548
|
-
`;return
|
|
549
|
-
`,{mode:384})}var Io=
|
|
550
|
-
`}async function
|
|
551
|
-
`))!==-1;){let
|
|
552
|
-
`)){let
|
|
553
|
+
`;return vy(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Ji=S(()=>{"use strict"});import{existsSync as Hu,mkdirSync as Ku}from"node:fs";import{dirname as Wu}from"node:path";import{simpleGit as ur}from"simple-git";function Ry(t,e,r="x-access-token"){let n=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,o=t.match(/^git@([^:]+):(.+)$/);if(o)return`https://${n}@${o[1]}/${o[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${n}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${n}@${s[1]}`:t}function Iy(t,e){return e?.contextWrite?.token?{user:Un(t),secret:e.contextWrite.token}:t===Wr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Wr.bitbucket?e?.bitbucket?.apiToken?{user:Dt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function qu(t,e){let r=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),n=e.initialDelayMs??5e3,o=e.maxDelayMs??6e4;for(;;)try{return await t()}catch(i){if(!(i instanceof xo))throw i;e.log.warn(`[ctx] ${i.message} \u2014 retrying in ${Math.round(n/1e3)}s (the HUB may be deploying)`),await r(n),n=Math.min(n*2,o)}}async function So(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await V(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new xo(c)}let s=i.contextRepo;if(!s)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=Iy(Xt(s.cloneUrl),r);if(a){let c=await Ty({ctx:s,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await Cy({ctx:s,contextDir:n,privateKey:r.contextSsh.privateKey,log:o});if(c)return c;o.warn("[ctx] SSH deploy-key clone failed")}return o.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function Ty(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Ry(e.cloneUrl,n.secret,n.user),s=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(Hu(`${r}/.git`)){let l=ur(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let d=mi(r);await l.reset(["--hard",`origin/${s}`]),gi(r,d),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Ku(Wu(r),{recursive:!0}),await ur().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Yu(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 Cy(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Fu(i,n),a=Gu(e.cloneUrl),c=e.branch;try{if(Hu(`${r}/.git`)){let l=ur(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let d=mi(r);await l.reset(["--hard",`origin/${c}`]),gi(r,d),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Ku(Wu(r),{recursive:!0}),await ur().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await ur(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Yu(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 Yu(t){let e=ur(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 xo,zi=S(()=>{"use strict";W();fe();at();Ji();xo=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as Py}from"node:child_process";function Ey(){try{return Py("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Ju(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Ey(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var zu=S(()=>{"use strict"});import{homedir as dr}from"node:os";import{mkdirSync as jy,readFileSync as Xu,writeFileSync as Ay,existsSync as Qi}from"node:fs";import{dirname as _y,join as Rt}from"node:path";function Ny(){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=M("SANDBOX_CONFIG");if(e)return e;let r=Rt(dr(),".codepipe","worker");return t?Rt(r,"profiles",t,"config.json"):Rt(r,"config.json")}function Qu(){return Rt(dr(),".devpipe-sandbox","config.json")}function Ro(){Lt(Rt(dr(),".devpipe"),Rt(dr(),".codepipe")),M("SANDBOX_CONFIG")||Lt(Rt(dr(),".devpipe-sandbox"),Rt(dr(),".codepipe-sandbox"))}function Zu(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function ge(t){let e=Fe(t),r=null;return Qi(e)?r=JSON.parse(Xu(e,"utf-8")):!t&&!M("SANDBOX_CONFIG")&&Qi(Qu())&&(r=JSON.parse(Xu(Qu(),"utf-8"))),r?(r.planningLane=Ny(),r):null}function ed(t,e){let r=Fe(e);jy(_y(r),{recursive:!0}),Ay(r,JSON.stringify(t,null,2)+`
|
|
554
|
+
`,{mode:384})}var Io=S(()=>{"use strict";Pe();Bn();Qi(".env")&&process.loadEnvFile(".env")});import Oy from"ws";var pr,Zi=S(()=>{"use strict";pr=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new Oy(e)}}});import{hostname as Dy}from"node:os";async function Ft(t){Ro();let e=ge(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Fe(t.profile)}.`),process.exit(1));let r=t.name??Dy(),n=Ju({projects:t.projects??[],llm:t.llm??null}),o=new pr(t.hub.replace(/\/$/,"")),i=so(),s=be(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});ed({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Fe(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}var td=S(()=>{"use strict";Ae();zu();Io();Zi()});import{spawn as Ly}from"node:child_process";function es(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function By(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 My(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Ht(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ts(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
|
|
555
|
+
`}async function id(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new ut;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let n=e.onActivity,o=c=>{if(n)try{n(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),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:es(p,rd)})}else if(m==="tool_use"){let p=String(u.name??""),h=u.input?.file_path??u.input?.path,y=By(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?es(My(u.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:m,...p?{text:p}:{}})}return}if(d==="result"){s=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=Ly(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"),nd)};e.signal?.addEventListener("abort",p,{once:!0});let h=null,y=()=>{h&&clearTimeout(h),h=setTimeout(()=>{u=!0,console.warn(`[claude:chat] idle for ${od}ms \u2014 ending session`),d.kill("SIGTERM"),m=setTimeout(()=>d.kill("SIGKILL"),nd)},od)},$=()=>{m&&clearTimeout(m),h&&clearTimeout(h),e.signal?.removeEventListener("abort",p)},w=!0,v=P=>{if(!(!w||d.stdin.destroyed))try{d.stdin.write(P)}catch{}};v(ts(e.prompt)),y(),(async()=>{try{for await(let P of e.interactive.inbox){if(f||!w)break;if(y(),P.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:es(P.text,rd)}),v(ts(P.text));else{v(ts(Uy)),w=!1;try{d.stdin.end()}catch{}break}}}catch{}})();let x="",U=P=>{let E;try{E=JSON.parse(P)}catch{return}a(E)};d.stdout.on("data",P=>{i.push(P),y(),x+=P;let E;for(;(E=x.indexOf(`
|
|
556
|
+
`))!==-1;){let B=x.slice(0,E).trim();x=x.slice(E+1),B&&U(B)}}),d.stderr.on("data",P=>{i.push(P);for(let E of P.split(`
|
|
557
|
+
`)){let B=E.trim();B&&console.warn(`[claude:chat:stderr] ${B}`)}}),d.on("error",P=>{$(),l(P)}),d.on("close",P=>{if($(),f){l(new ut);return}if(u){l(new Error("chat session ended: idle for too long without a reply"));return}x.trim()&&U(x.trim()),console.log(`[claude:chat] exit code=${P}`),c({artifactPaths:[],log:i.join(""),usage:Gy(s)})})})}function Gy(t){let e=_t();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Ht(r.input_tokens),e.outputTokens=Ht(r.output_tokens),e.cacheReadInputTokens=Ht(r.cache_read_input_tokens),e.cacheCreationInputTokens=Ht(r.cache_creation_input_tokens)),e.totalCostUsd=Ht(t.total_cost_usd),e.numTurns=Ht(t.num_turns),e.durationMs=Ht(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var rd,nd,od,Uy,sd=S(()=>{"use strict";W();fr();rd=16e3,nd=5e3,od=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Uy="\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 Fy}from"node:child_process";import{existsSync as Hy}from"node:fs";function Wy(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function ad(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${It(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=Vy(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let n=e.message;for(let o of n?.content??[])if(o.type==="tool_result")if(o.is_error===!0){let i=ld(o.content);console.log(`[claude] tool_result (error)${i?`: ${It(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${It(JSON.stringify(e),200)}`),e}function qy(t,e,r){let n=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let o=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;o?n.push(It(o,500)):typeof s=="string"&&s!=="success"&&n.push(s),typeof i=="number"&&n.push(`(api_status=${i})`)}return n.length===1&&r.trim()&&n.push(It(r.trim().split(`
|
|
553
558
|
`).slice(-5).join(`
|
|
554
|
-
`),500)),n.join(" \u2014 ")}function
|
|
555
|
-
`))!==-1;){let
|
|
556
|
-
`)){let
|
|
559
|
+
`),500)),n.join(" \u2014 ")}function Yy(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 ld(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Vy(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=${It(r,80)}`}return""}function It(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 Jy(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 zy(t,e,r,n){let o=_t(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=ke(i.input_tokens),o.outputTokens=ke(i.output_tokens),o.cacheReadInputTokens=ke(i.cache_read_input_tokens),o.cacheCreationInputTokens=ke(i.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 s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function Xy(t,e){let r=Date.now(),n=t.type;if(n==="system"){let o=String(t.subtype??"").trim();return o?[{ts:r,kind:"system",text:o}]:[]}if(n==="assistant"){let o=t.message,i=[];for(let s of o?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:It(c,cd)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,d=l?.file_path??l?.path??l?.notebook_path,f=Qy(d,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?It(ld(s.content),cd):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(n==="result"){let o=String(t.subtype??"").trim(),i=typeof t.num_turns=="number"?t.num_turns:void 0,s=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...o?{text:o}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function Qy(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}var mr,ut,Ky,mn,cd,fr=S(()=>{"use strict";W();sd();mr=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},ut=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Ky=5e3;mn=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return id(this.binary,e);if(e.signal?.aborted)throw new ut;let r=["-p",Wy(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=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,d=p=>{if(p){if(p.type==="result"){i=p;return}if(p.type==="rate_limit_event"){let h=Jy(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,s.input+=ke(y.input_tokens),s.output+=ke(y.output_tokens),s.cacheRead+=ke(y.cache_read_input_tokens),s.cacheCreate+=ke(y.cache_creation_input_tokens))}}},f=e.role,u=e.onActivity,m=p=>{if(u)for(let h of Xy(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=Fy(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});y.stdout.setEncoding("utf-8"),y.stderr.setEncoding("utf-8");let $=!1,w=null,v=()=>{$=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),y.kill("SIGTERM"),w=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),y.kill("SIGKILL")},Ky)};e.signal?.addEventListener("abort",v,{once:!0});let x=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",v)},U="";y.stdout.on("data",P=>{n.push(P),U+=P;let E;for(;(E=U.indexOf(`
|
|
560
|
+
`))!==-1;){let B=U.slice(0,E).trim();if(U=U.slice(E+1),B){let pe=ad(B);d(pe),pe&&m(pe)}}}),y.stderr.on("data",P=>{n.push(P),o.push(P);for(let E of P.split(`
|
|
561
|
+
`)){let B=E.trim();B&&console.warn(`[claude:stderr] ${B}`)}}),y.on("error",P=>{x(),h(P)}),y.on("close",P=>{if(x(),$){h(new ut);return}if(U.trim()){let B=ad(U.trim());d(B),B&&m(B)}let E=i?.is_error===!0;if(P!==0||E){let B=typeof i?.api_error_status=="number"?i.api_error_status:void 0,pe=typeof i?.subtype=="string"?i.subtype:void 0,we=typeof i?.result=="string"?i.result:void 0;h(new mr(qy(P,i,o.join("")),{code:P,apiErrorStatus:B,subtype:pe,resultText:we,retryAfterMs:Yy(i)}));return}console.log("[claude] exit code=0"),p({artifactPaths:[],log:n.join(""),usage:zy(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&Hy(n))}};cd=200});import{mkdirSync as Zy,writeFileSync as gr}from"node:fs";import{dirname as ew,join as hr}from"node:path";function ud(t,e,r){let n=hr(t,e);Zy(ew(n),{recursive:!0}),gr(n,r)}function tw(t,e,r){return`# ${t} \u2014 Estimate
|
|
557
562
|
|
|
558
563
|
**Title:** ${e}
|
|
559
564
|
|
|
@@ -574,7 +579,7 @@ production-grade estimates.)
|
|
|
574
579
|
${r.split(`
|
|
575
580
|
`).slice(0,8).join(`
|
|
576
581
|
`).trim()||"(empty)"}
|
|
577
|
-
`}function
|
|
582
|
+
`}function rw(t,e,r,n){let o=n?`
|
|
578
583
|
## Reviewer rework instruction
|
|
579
584
|
|
|
580
585
|
> ${n.split(`
|
|
@@ -603,10 +608,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
603
608
|
${r.split(`
|
|
604
609
|
`).slice(0,8).join(`
|
|
605
610
|
`).trim()||"(empty)"}
|
|
606
|
-
`}function
|
|
611
|
+
`}function nw(t){return`# ${t} \u2014 Open questions
|
|
607
612
|
|
|
608
613
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
609
|
-
`}function
|
|
614
|
+
`}function ow(t,e,r){let n=r?` (rework: ${r.split(`
|
|
610
615
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
611
616
|
index 0000000..1111111 100644
|
|
612
617
|
--- a/CHANGELOG.md
|
|
@@ -617,7 +622,7 @@ index 0000000..1111111 100644
|
|
|
617
622
|
+- mock-runner placeholder change for slice 5 testing.
|
|
618
623
|
+
|
|
619
624
|
# Changelog
|
|
620
|
-
`}function
|
|
625
|
+
`}function iw(t,e,r){return`# ${t} \u2014 Diff summary
|
|
621
626
|
|
|
622
627
|
**Title:** ${e}
|
|
623
628
|
${r?`
|
|
@@ -628,140 +633,140 @@ ${r?`
|
|
|
628
633
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
629
634
|
|
|
630
635
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
631
|
-
`}var gn,
|
|
632
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:
|
|
636
|
+
`}var gn,rs=S(()=>{"use strict";W();fr();gn=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=tw(n,o,i);gr(hr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;gr(hr(e.workspaceDir,"SOLUTION.md"),rw(n,o,i,a)),s.push("SOLUTION.md"),gr(hr(e.workspaceDir,"QUESTIONS.md"),nw(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;ud(e.workspaceDir,"changes/sample.patch",ow(n,o,a)),s.push("changes/sample.patch"),ud(e.workspaceDir,"diff-summary.md",iw(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(gr(hr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
637
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:_t()}}async runInteractive(e){let r=e.onActivity,n=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("\u041F\u0440\u0438\u0432\u0435\u0442! \u041E\u043F\u0438\u0448\u0438\u0442\u0435 \u0437\u0430\u0434\u0430\u0447\u0443, \u043A\u043E\u0442\u043E\u0440\u0443\u044E \u0445\u043E\u0442\u0438\u0442\u0435 \u0441\u0444\u043E\u0440\u043C\u0443\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C.");let o="\u0427\u0435\u0440\u043D\u043E\u0432\u0438\u043A \u0438\u0437 \u0447\u0430\u0442\u0430";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new ut;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`\u041F\u043E\u043D\u044F\u043B: **${i.text.trim()}**. \u0427\u0442\u043E-\u043D\u0438\u0431\u0443\u0434\u044C \u0435\u0449\u0451 \u0443\u0442\u043E\u0447\u043D\u0438\u0442\u044C?`);else break}return gr(hr(e.workspaceDir,"DRAFT.md"),`${o}
|
|
633
638
|
|
|
634
639
|
\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).
|
|
635
|
-
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:
|
|
640
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:_t()}}}});function dd(t){switch(t){case"mock":return new gn;case"claude-headless":return new mn;default:return null}}function pd(t,e){let r=e&&e.trim().length>0?e.trim():Ve;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var fd=S(()=>{"use strict";W();fr();rs();fr();rs()});function hd(t=process.env){return{maxAttempts:To(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:To(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:To(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:To(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function lw(t){if(t instanceof mr){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return aw.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&cw.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:sw.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:md.test(s)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:n??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return md.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function yd(t){if(t instanceof mr){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&gd.test(n)}let e=t instanceof Error?t.message:String(t);return gd.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 wd(t,e,r){let n=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),o=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=lw(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let d=uw(s,r.policy,c.retryAfterMs);if(Date.now()+d>o)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${d}ms`),await r.onBeforeRetry(),await n(d)}}function To(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var sw,md,aw,cw,gd,bd=S(()=>{"use strict";fr();sw=new Set([429,500,502,503,529]),md=/(\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,aw=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,cw=new Set(["error_max_turns"]);gd=/(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 dw,rmSync as pw,writeFileSync as kd}from"node:fs";import{tmpdir as fw}from"node:os";import{join as ns}from"node:path";function Co(t){return`[url "https://${t}/"]
|
|
636
641
|
insteadOf = git@${t}:
|
|
637
642
|
insteadOf = ssh://git@${t}/
|
|
638
|
-
`}function
|
|
643
|
+
`}function $d(t,e){if(t.length===0)return null;let r=dw(ns(fw(),"devpipe-gitcreds-")),n=ns(r,"credentials"),o=ns(r,"gitconfig");return kd(n,t.join(`
|
|
639
644
|
`)+`
|
|
640
|
-
`,{mode:384}),
|
|
645
|
+
`,{mode:384}),kd(o,`[credential]
|
|
641
646
|
helper = store --file=${n}
|
|
642
|
-
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{
|
|
643
|
-
`).map(p=>p.trim()).filter(p=>p.length>0);if(u&&m.length===0)throw await
|
|
644
|
-
`).map(l=>l.trim()).filter(l=>l.length>0),c=await
|
|
645
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function
|
|
646
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
647
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=
|
|
648
|
-
`+e.subarray(e.length-
|
|
649
|
-
\u2026 [${r.length-e} bytes elided]`}var
|
|
647
|
+
`+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{pw(r,{recursive:!0,force:!0})}catch{}}}}function os(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(mw)),t.bitbucket?.apiToken&&(e.push(`https://${Dt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(gw)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(hw)),$d(e,r)}function vd(t,e){if(t.contextWrite?.token){let r=Xt(e)??"github.com",n=Un(r);return $d([`https://${n}:${t.contextWrite.token}@${r}`],[Co(r)])}return os(t)}var mw,gw,hw,xd=S(()=>{"use strict";W();mw=Co("github.com"),gw=Co("bitbucket.org"),hw=Co("gitlab.com")});import{spawn as Rd}from"node:child_process";import{existsSync as Po,mkdirSync as hn,readFileSync as yw,rmSync as is,symlinkSync as ww}from"node:fs";import{homedir as bw}from"node:os";import{dirname as wr,join as Tt}from"node:path";function Id(t){let e=Tt(bw(),".codepipe-sandbox","repos");return t?Tt(e,t):e}function Td(t,e){let n=(yr.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{yr.get(t)===o&&yr.delete(t)},()=>{yr.get(t)===o&&yr.delete(t)});return yr.set(t,o),n}function Sd(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 kw(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 Cd(t,e,r,n,o){let i=async c=>{await z(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await z(t,["reset","--hard",`origin/${c}`],o),await z(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!Sd(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Po(t)&&is(t,{recursive:!0,force:!0}),hn(wr(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||!Sd(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Po(t)&&is(t,{recursive:!0,force:!0}),hn(wr(t),{recursive:!0}),await z(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Po(Tt(t,".git")))try{return await s()}catch(c){if(!kw(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 Pd(t){await z(t.workspacePath,["reset","--hard",t.baseSha]),await z(t.workspacePath,["clean","-fdx"])}async function Ed(t,e){let r=t.workspacePath;await z(r,["add","-A"]);let n=(await me(r,["write-tree"])).trim(),o=(await me(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:br,GIT_AUTHOR_EMAIL:kr,GIT_COMMITTER_NAME:br,GIT_COMMITTER_EMAIL:kr};return(await me(r,["commit-tree",n,"-m",e],i)).trim()}async function jd(t,e,r,n,o){try{await z(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Xt(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function Ad(t,e){return me(t.workspacePath,["diff","--binary",t.baseSha,e])}async function _d(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 Nd(t,e,r,n,o,i){let s=t.workspacePath;await z(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await me(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=p=>me(s,["rev-parse","-q","--verify",`${p}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await me(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await z(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(h=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(h)}`)}),await c(n)||await z(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:br,GIT_AUTHOR_EMAIL:kr,GIT_COMMITTER_NAME:br,GIT_COMMITTER_EMAIL:kr},d=(await me(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),f=(await me(s,["commit-tree",d,"-p",n,"-m","delivery"],l)).trim();await z(s,["cherry-pick","--quit"],l).catch(()=>{});let u=null;try{await z(s,["cherry-pick","--no-commit",f],l)}catch(p){u=p instanceof Error?p.message:String(p)}let m=(await me(s,["diff","--name-only","--diff-filter=U"])).split(`
|
|
648
|
+
`).map(p=>p.trim()).filter(p=>p.length>0);if(u&&m.length===0)throw await z(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${u}`);return m}async function ss(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:br,GIT_AUTHOR_EMAIL:kr,GIT_COMMITTER_NAME:br,GIT_COMMITTER_EMAIL:kr};(await me(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await z(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await z(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await z(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await me(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
649
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await me(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function z(t,e,r){return new Promise((n,o)=>{let i=Rd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
|
|
650
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function me(t,e,r){return new Promise((n,o)=>{let i=Rd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
|
|
651
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function Od(t,e){Po(t)&&is(t,{recursive:!0,force:!0}),hn(wr(t),{recursive:!0}),ww(e,t,"dir")}async function Dd(t,e,r){await z(t,["worktree","prune"]).catch(()=>{}),hn(wr(r),{recursive:!0}),await z(t,["worktree","add","--detach",r,`origin/${e}`])}async function $w(t,e,r){hn(wr(r),{recursive:!0}),await z(wr(r),["clone","--quiet","--no-checkout",t,r]),await z(r,["checkout","--force","--detach",e])}async function Ld(t,e,r,n="worktree",o,i){return r.length===0?[]:Td(e,async()=>{let s=[];for(let a of r){let c=Tt(Id(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await Cd(c,a.cloneUrl,a.ref,a.defaultBranch,o)}catch(u){throw new Error(`failed to materialize project repo "${a.name}" (${a.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let d=(await me(c,["rev-parse","HEAD"])).trim(),f=Tt(t,"code",a.name);n==="direct"?(Od(f,c),console.log(`[git] code: linked ${f} \u2192 ${c} @ ${d.slice(0,10)}`)):n==="clone"?(await $w(c,d,f),console.log(`[git] code: clone ${f} \u2190 ${c} @ ${d.slice(0,10)}`)):(await Dd(c,l,f),console.log(`[git] code: worktree ${f} \u2190 ${c} @ ${d.slice(0,10)}`)),s.push({name:a.name,workspacePath:f,cachePath:c,ref:l,baseSha:d})}return s})}async function Ud(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return Td(e,async()=>{let a=Tt(Id(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await Cd(a,s.cloneUrl,s.ref,void 0,o)}catch(d){throw new Error(`failed to materialize context repo (${s.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let c=Tt(t,"context");n==="direct"?(Od(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Dd(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await me(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function Bd(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await z(r,["add","-A",...n]).catch(()=>{});let o;try{o=await me(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
|
|
652
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=yw(Tt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var yr,br,kr,Md=S(()=>{"use strict";W();yr=new Map;br="CodePipe Agent",kr="codepipe@codepartner.ee"});import{readFileSync as vw}from"node:fs";import{join as xw}from"node:path";function Gd(t){let e=xw(t,yn),r;try{r=vw(e,"utf-8")}catch{throw new Ct(`BUILD produced no ${yn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(d){throw new Ct(`${yn} is not valid JSON: ${d instanceof Error?d.message:String(d)}`)}if(!n||typeof n!="object")throw new Ct(`${yn} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Ct(`${yn}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(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"?Sw(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let d=a.find(f=>f.exitCode!==0);d&&(l.failedStep=d.name)}return l}function Sw(t){let e=Buffer.from(t,"utf-8");return e.length<=as?t:`\u2026 [${e.length-as} bytes elided] \u2026
|
|
653
|
+
`+e.subarray(e.length-as).toString("utf-8")}var as,Ct,yn,Fd=S(()=>{"use strict";as=8*1024,Ct=class extends Error{},yn="meta/build-result.json"});import{readFileSync as Rw}from"node:fs";import{join as Iw}from"node:path";function Kd(t){let e=Iw(t,$r),r;try{r=Rw(e,"utf-8")}catch{throw new dt(`code review produced no ${$r} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new dt(`${$r} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new dt(`${$r} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new dt(`${$r}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?Hd(o.remarks,Tw):"";if(!i&&s.trim().length===0)throw new dt(`${$r}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?Hd(o.summary,Cw):"";return{approved:i,remarks:s,summary:a}}function Hd(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
|
|
654
|
+
\u2026 [${r.length-e} bytes elided]`}var Tw,Cw,dt,$r,Wd=S(()=>{"use strict";Tw=16*1024,Cw=4*1024,dt=class extends Error{},$r="meta/review-result.json"});import{readFileSync as Pw,statSync as Ew}from"node:fs";import{join as qd}from"node:path";function Lw(t){return t.startsWith("meta/")||Dw.has(t)}function Uw(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 Bw(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Yd(t,e,r){let n=r?.maxBytes??jw,o=r?.totalBytes??Aw,i=r?.maxCount??_w,s=e.map((p,h)=>{let y=null;try{y=Ew(qd(t,p)).size}catch{}return{path:p,index:h,size:y}}),a=[...s].sort((p,h)=>{let y=$=>Lw($.path)?0:1;return y(p)!==y(h)?y(p)-y(h):(p.size??0)-(h.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((p,h)=>p.index-h.index).map(p=>p.path),d=new Array(s.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=Pw(qd(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?Bw(p.path):Uw(p.path,p.size,n,o),$=Buffer.from(y,"utf-8");u+=$.length,d[p.index]={path:p.path,contentBase64:$.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,Ow),h=`# Artifacts omitted from upload
|
|
650
655
|
|
|
651
656
|
${l.length} file(s) exceeded the SANDBOX artifact count budget (${i}) and were dropped from the listing. The delivered code (git) and the build/review verdicts are unaffected. Usually this means a job left a stray tree in the workspace \u2014 throwaway copies belong in the workspace's \`scratch/\` directory, which is never uploaded.
|
|
652
657
|
|
|
653
658
|
`+p.map(y=>`- ${y}
|
|
654
659
|
`).join("")+(l.length>p.length?`
|
|
655
660
|
\u2026and ${l.length-p.length} more.
|
|
656
|
-
`:"");m.push({path:
|
|
661
|
+
`:"");m.push({path:Nw,contentBase64:Buffer.from(h,"utf-8").toString("base64")})}return{artifacts:m,omitted:f,dropped:l}}var jw,Aw,_w,Nw,Ow,Dw,Vd=S(()=>{"use strict";jw=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),Aw=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),_w=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),Nw="artifacts-omitted.md",Ow=500,Dw=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 Mw,mkdtempSync as Gw,readFileSync as Fw,readdirSync as zd,rmSync as Jd}from"node:fs";import{tmpdir as Hw}from"node:os";import{join as Eo,relative as Kw}from"node:path";function Xd(t){let e=Gw(Eo(Hw(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Jd(e,{recursive:!0,force:!0}),listFiles:()=>Qd(e,e),readFile:r=>Fw(Eo(e,r),"utf-8"),clean:()=>{for(let r of zd(e))qw.has(r)||Jd(Eo(e,r),{recursive:!0,force:!0})}}}function Qd(t,e){let r=[];for(let n of zd(e)){let o=Eo(e,n),i=Mw(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Ww.has(n))continue;r.push(...Qd(t,o))}else r.push(Kw(t,o))}return r}var Ww,qw,Zd=S(()=>{"use strict";Ww=new Set(["code","context","scratch"]),qw=new Set(["code","context"])});import{mkdirSync as Yw,readFileSync as ep,readdirSync as Vw,writeFileSync as Jw}from"node:fs";import{homedir as zw}from"node:os";import{dirname as Xw,join as vr}from"node:path";function Zw(t){let e=Buffer.from(t,"utf-8");if(e.length<=jo)return t;let r=Math.floor(jo/4),n=jo-r,o=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-n).toString("utf-8"),s=e.length-r-n;return`${o}
|
|
657
662
|
|
|
658
663
|
\u2026 [${s} bytes elided \u2014 log capped at ${jo} bytes for upload] \u2026
|
|
659
664
|
|
|
660
|
-
${i}`}function
|
|
665
|
+
${i}`}function eb(){let t=[],e=!1,r=null,n=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},o=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||n(i)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function wn(t={}){Ro();let e=ge(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=e.sandboxId,o=e.llm,i=Zu(t.profile,e.sandboxId,!!M("SANDBOX_CONFIG")),s=vr(zw(),".codepipe","logs"),a=qn("SANDBOX_LOG",i,s);if(a.enabled){let j=new tr(a);Yn(j),console.log(`[log] file logging \u2192 ${j.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Te} (protocol ${qe})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=dd(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=hd();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let d=new pr(e.hubUrl,e.token),f=!1,u=new AbortController,m=new Map,p=null,h=null,y=!1,$=()=>{let j=d.openControlSocket();return p=j,j.on("open",()=>{console.log("[ws] connected");let g={type:"sandbox_hello",platformVersion:Te,protocolVersion:qe};j.send(JSON.stringify(g))}),j.on("message",g=>{let C=g.toString("utf-8"),b=null;try{let R=JSON.parse(C);R&&typeof R=="object"&&(b=R)}catch{}if(b&&b.type==="hello"){let R=b;h=_n(R.protocolVersion);let A=h?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${R.platformVersion} (protocol ${R.protocolVersion}) \u2014 ${A}`),h&&(y=!1);return}if(b&&b.type==="pause_job"){let R=typeof b.jobId=="string"?b.jobId:"",A=R?m.get(R):void 0;A?(console.warn(`[ws] pause_job ${R} \u2014 aborting agent`),A.paused=!0,A.abort.abort()):console.log(`[ws] pause_job ${R} \u2014 not a running job, ignoring`),R&&j.send(JSON.stringify({type:"job_paused",jobId:R}));return}if(b&&(b.type==="chat_user_message"||b.type==="chat_finalize")){let R=typeof b.jobId=="string"?b.jobId:"",A=R?m.get(R):void 0;if(A?.chatInbox)if(b.type==="chat_user_message"){let k=typeof b.text=="string"?b.text:"";k.trim()&&A.chatInbox.push({kind:"user",text:k})}else A.chatInbox.finalize();else console.log(`[ws] ${String(b.type)} ${R} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${C}`)}),j.on("close",(g,C)=>{console.log(`[ws] closed code=${g} reason=${C?.toString()||""}`),p===j&&(p=null),!f&&setTimeout($,2e3)}),j.on("error",g=>console.warn(`[ws] error: ${g.message}`)),j},w=$(),v=async j=>{for(;!f;){if(h===!1){y||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Te}, protocol ${qe}) \u2014 not claiming jobs until versions align.`),y=!0),await new Promise(g=>setTimeout(g,5e3));continue}try{let g=await d.claim(u.signal,j);if(g.status===204)continue;if(g.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,f=!0;break}if(!g.ok){console.warn(`[claim:${j}] ${g.status} \u2014 backoff 5s`),await new Promise(b=>setTimeout(b,5e3));continue}let C=await g.json();await x(d,C)}catch(g){if(u.signal.aborted)break;let C=g instanceof Error?g.message:String(g);console.warn(`[claim:${j}] error: ${C} \u2014 backoff 5s`),await new Promise(b=>setTimeout(b,5e3))}}};async function x(j,g){let C={abort:new AbortController,paused:!1};g.role==="chat"&&(C.chatInbox=eb()),m.set(g.jobId,C);let b=!1,R=null,A=null,k=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),I=async()=>{try{await j.heartbeat(g.jobId)==="claim_lost"&&(b=!0,console.warn(`[job] ${g.jobId} claim lost \u2014 HUB sweeper took it`))}catch(H){let J=H instanceof Error?H.message:String(H);console.warn(`[job] ${g.jobId} heartbeat error: ${J}`)}};I();let K=setInterval(()=>{I()},k),G=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(P(g.prompt," \u2502 "));let Re=[],Ke=null,Ho=400,En=25,Ko=500,_=()=>{if(Ke&&(clearTimeout(Ke),Ke=null),Re.length===0)return;let H=Re.splice(0,Re.length),J=p;if(!J||J.readyState!==J.OPEN)return;let tt={type:"agent_activity",jobId:g.jobId,taskId:g.taskId,projectId:g.projectId,role:g.role,phase:g.phase,events:H};try{J.send(JSON.stringify(tt))}catch{}},re=H=>{Re.push(H),Re.length>Ko&&Re.shift(),Re.length>=En?_():Ke||(Ke=setTimeout(_,Ho))},Ie=g.role==="analysis"&&g.taskId.startsWith("draft::")?g.taskId.slice(7):null,Oe=new Set,pt=null;try{if(!c){b||await j.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:G,finishedAt:new Date().toISOString()});return}if(!pd(o,g.provider??null)){b||await j.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${g.provider??"claude"}"`},startedAt:G,finishedAt:new Date().toISOString()});return}let H=Xd(g.jobId);console.log(`[job] ${g.jobId} workspace=${H.dir}`);let J=U(g,r);R=J.gitCreds,A=J.contextGitCreds;let tt=R?.env,js=J.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:J.claudeOauthToken}:void 0,rt=[],Lr=null,Wo=null;try{let O=g.role==="build"?"clone":"worktree";rt=await Ld(H.dir,g.projectId,g.projectRepos,O,tt,n);let D=await Ud(H.dir,g.projectId,g.contextRepo,"worktree",tt,n);Wo=D,Lr=D?.workspacePath??null}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} materialize failed: ${D}`),b||await j.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${D}`},startedAt:G,finishedAt:new Date().toISOString()}),H.dispose();return}let As=async()=>{if(!g.deliveries||g.deliveries.length===0)return[];let O=g.contextRepo?.cloneUrl;if(!O||!tt)throw new Error(O?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let D=[];for(let Y of g.deliveries){let q=rt.find(ce=>ce.name===Y.name);if(q){if(g.role==="implement"&&Y.baseSha&&Y.baseSha!==q.baseSha){let ce=await Nd(q,Y.deliveryRef,Y.deliverySha,Y.baseSha,O,tt);console.log(`[job] ${g.jobId} ${q.name}: base moved ${Y.baseSha.slice(0,10)} \u2192 ${q.baseSha.slice(0,10)} \u2014 re-applied delivery ${Y.deliverySha.slice(0,10)} (${ce.length} conflicted file(s))`),ce.length>0&&D.push(`- **${q.name}**:`,...ce.map(Ur=>` - \`${Ur}\``));continue}await _d(q,Y.deliveryRef,Y.deliverySha,O,tt),console.log(`[job] ${g.jobId} ${q.name}: checked out delivery ${Y.deliverySha.slice(0,10)} for ${g.role}`)}}return D},qo=[];if(g.role==="build"||g.role==="implement"||g.role==="code-review")try{qo=await As()}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} delivery checkout failed: ${D}`),b||await j.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${D}`},startedAt:G,finishedAt:new Date().toISOString()}),H.dispose();return}let Yo=g.role==="resolve-conflict"?g.metadata?.taskBranchByRepo??{}:{},_s="";if(g.role==="resolve-conflict"){if(!rt.some(O=>Yo[O.name])){let O="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${g.jobId} ${O}`),b||await j.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:G,finishedAt:new Date().toISOString()}),H.dispose();return}try{let O=[];for(let D of rt){let Y=Yo[D.name];if(!Y)continue;let q=await ss(D,Y,tt);console.log(`[job] ${g.jobId} ${D.name}: merged ${Y} into ${D.ref} \u2014 ${q.length} conflicted file(s)`),q.length>0?O.push(`- **${D.name}**:`,...q.map(ce=>` - \`${ce}\``)):O.push(`- **${D.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}_s=`
|
|
661
666
|
|
|
662
667
|
## Conflicts to resolve
|
|
663
668
|
|
|
664
669
|
`+(O.length>0?O.join(`
|
|
665
670
|
`):"(no task branches to merge)")+`
|
|
666
|
-
`}catch(O){let
|
|
671
|
+
`}catch(O){let D=O instanceof Error?O.message:String(O);console.warn(`[job] ${g.jobId} conflict merge failed: ${D}`),b||await j.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${D}`},startedAt:G,finishedAt:new Date().toISOString()}),H.dispose();return}}let Af=qo.length>0?`
|
|
667
672
|
|
|
668
673
|
## Base branch moved \u2014 conflicts to resolve
|
|
669
674
|
|
|
670
675
|
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:
|
|
671
676
|
|
|
672
|
-
`+
|
|
677
|
+
`+qo.join(`
|
|
673
678
|
`)+`
|
|
674
|
-
`:"",
|
|
679
|
+
`:"",_f=B(E(g.prompt,rt,Lr),Lr,g.taskId)+_s+Af,Vo=[...rt.map(O=>O.workspacePath),...Lr?[Lr]:[]];Vo.length>0&&console.log(`[job] ${g.jobId} --add-dir: ${Vo.join(", ")}`),Ie&&(pt=setInterval(()=>{let D=p;if(!D||D.readyState!==D.OPEN)return;let Y;try{Y=Vw(vr(H.dir,"drafts")).filter(q=>q.endsWith(".json")).sort()}catch{return}for(let q of Y){if(Oe.has(q))continue;if(Oe.size>=ja)break;let ce;try{let De=JSON.parse(ep(vr(H.dir,"drafts",q),"utf-8")),Vt=typeof De.localRef=="string"?De.localRef:"",jn=typeof De.title=="string"?De.title:"",Jo=typeof De.body=="string"?De.body:"";if(!Vt||!jn)continue;ce={localRef:Vt,title:jn,body:Jo,...De.isEpic===!0?{isEpic:!0}:{},...Array.isArray(De.links)?{links:De.links}:{}}}catch{continue}Oe.add(q);let Ur={type:"child_draft",jobId:g.jobId,projectId:g.projectId,draftId:Ie,child:ce};try{D.send(JSON.stringify(Ur))}catch{}}},1500));try{let O={workspaceDir:H.dir,role:g.role,prompt:_f,addDirs:Vo,metadata:g.metadata??{},...g.model?{model:g.model}:{},...js?{env:js}:{},signal:C.abort.signal,onActivity:re},D=C.chatInbox?await c.run({...O,interactive:{inbox:C.chatInbox.iterable}}):await wd(c,O,{jobId:g.jobId,policy:l,onBeforeRetry:async()=>{H.clean();for(let Z of rt)try{await Pd(Z);let le=Yo[Z.name];g.role==="resolve-conflict"&&le&&await ss(Z,le,tt)}catch(le){let Br=le instanceof Error?le.message:String(le);console.warn(`[job] ${g.jobId} worktree reset failed (${Z.name}): ${Br}`)}try{await As()}catch(Z){let le=Z instanceof Error?Z.message:String(Z);console.warn(`[job] ${g.jobId} delivery re-checkout failed: ${le}`)}},aborted:()=>b||C.paused}),Y=[];if(Qw.has(g.role)&&rt.length>0){let Z=g.metadata??{},le=typeof Z.commitMessage=="string"?Z.commitMessage:`${g.taskId}: changes`,Br=g.contextRepo?.cloneUrl,Os=A?.env;if(!Br||!Os)throw new Error("delivery requested but "+(Br?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Nf=g.taskId.includes(":")?g.taskId.slice(g.taskId.indexOf(":")+1):g.taskId;for(let nt of rt){let Mr=await Ed(nt,le);if(!Mr){console.log(`[job] ${g.jobId} ${nt.name}: no changes \u2014 no delivery`);continue}let zo=`codepipe/deliveries/${Nf}/${g.jobId}/${nt.name}`;await jd(nt,Mr,zo,Br,Os),Y.push({name:nt.name,deliveryRef:zo,deliverySha:Mr,baseSha:nt.baseSha}),console.log(`[job] ${g.jobId} ${nt.name}: delivered ${Mr.slice(0,10)} \u2192 ${zo}`);let Ds=await Ad(nt,Mr);if(Ds.trim().length>0){let Of=vr("display",`${nt.name}.diff`),Ls=vr(H.dir,Of);Yw(Xw(Ls),{recursive:!0}),Jw(Ls,Ds)}}}if(g.role==="resolve-conflict"&&Y.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let q;g.role==="build"&&(q=Gd(H.dir),console.log(`[job] ${g.jobId} build verdict: ok=${q.ok}`+(q.failedStep?` failedStep=${q.failedStep}`:"")));let ce;g.role==="code-review"&&(ce=Kd(H.dir),console.log(`[job] ${g.jobId} review verdict: approved=${ce.approved}`));let Ur=D.artifactPaths.length>0?D.artifactPaths:H.listFiles(),De=Array.from(new Set(Ur)),Vt;if(Wo)try{let Z=g.role==="index"?["adr/SOURCES.md"]:g.role==="backfill"?["adr"]:[],le=await Bd(Wo,Z);le.length>0&&(Vt=le,console.log(`[job] ${g.jobId} captured ${le.length} knowledge file(s) for Context Repo`))}catch(Z){let le=Z instanceof Error?Z.message:String(Z);console.warn(`[job] ${g.jobId} knowledge capture failed (non-fatal): ${le}`)}let{artifacts:jn,omitted:Jo,dropped:Ns}=Yd(H.dir,De);for(let Z of Jo)console.warn(`[job] ${g.jobId} artifact ${Z.path} (${Z.bytes} bytes) exceeded upload budget \u2014 content omitted`);Ns.length>0&&console.warn(`[job] ${g.jobId} artifact listing truncated: ${Ns.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let An={jobId:g.jobId,status:"succeeded",artifacts:jn,...Vt?{contextWrites:Vt}:{},...Y.length>0?{deliveries:Y}:{},log:Zw(D.log),startedAt:G,finishedAt:new Date().toISOString(),usage:D.usage,...D.rateLimit?{rateLimit:D.rateLimit}:{},...q?{build:q}:{},...ce?{review:ce}:{}};if(b||C.paused)console.warn(`[job] ${g.jobId} skipping result upload \u2014 ${C.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await j.submitResult(An),console.log(`[job] ${g.jobId} done \u2014 uploaded ${An.artifacts.length} artifact(s):`);for(let Z of An.artifacts){let le=Buffer.from(Z.contentBase64,"base64").length;console.log(` \xB7 ${Z.path} (${le} bytes)`)}An.artifacts.length===0&&console.warn(`[job] ${g.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(O){let D=O instanceof Error?O.message:String(O);if(C.paused)console.log(`[job] ${g.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(b)console.warn(`[job] ${g.jobId} failed after claim lost (${D}) \u2014 skipping result upload`);else{let Y=yd(O),q=O instanceof Ct,ce=O instanceof dt;console.warn(Y?`[job] ${g.jobId} failed: ${D} (Claude auth \u2014 token invalid/expired)`:q?`[job] ${g.jobId} failed: ${D} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:ce?`[job] ${g.jobId} failed: ${D} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${g.jobId} failed: ${D}`),await j.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:D},startedAt:G,finishedAt:new Date().toISOString(),...Y?{authError:!0}:{},...q?{buildInconclusive:!0}:{},...ce?{reviewInconclusive:!0}:{}})}}finally{H.dispose()}}finally{clearInterval(K),pt&&clearInterval(pt),_(),C.chatInbox?.close(),m.delete(g.jobId),R?.cleanup(),A?.cleanup()}}function U(j,g){if(!j.credBundle)return{gitCreds:null,contextGitCreds:null};if(!g)return console.warn(`[job] ${j.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let C;try{C=JSON.parse(cr(g,j.credBundle).toString("utf-8"))}catch(k){return console.warn(`[job] ${j.jobId} failed to open credBundle: ${k instanceof Error?k.message:String(k)}`),{gitCreds:null,contextGitCreds:null}}let b=os(C);b&&console.log(`[job] ${j.jobId} cred bundle opened \u2014 git creds configured`);let R=vd(C,j.contextRepo.cloneUrl),A={gitCreds:b,contextGitCreds:R};return C.claudeOauthToken&&(A.claudeOauthToken=C.claudeOauthToken),A}function P(j,g){return j.split(`
|
|
675
680
|
`).map(C=>g+C).join(`
|
|
676
|
-
`)}function j
|
|
677
|
-
[${A}] shutting down`),u.abort();let g=[...m.keys()];for(let I of m.values())I.abort.abort();let C=new AbortController,b=setTimeout(()=>C.abort(),3e3);(async()=>(await Promise.all(g.map(async I=>{try{await d.releaseJob(I,`sandbox ${A}`,C.signal),console.log(`[${A}] released job ${I}`)}catch(E){let k=E instanceof Error?E.message:String(E);console.warn(`[${A}] release failed: ${k} (sweeper will reclaim)`)}})),clearTimeout(b),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>de("SIGINT")),process.on("SIGTERM",()=>de("SIGTERM"));let ye=[v("implementation")];e.planningLane!==!1?ye.push(v("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(ye)}var jo,qw,zd=R(()=>{"use strict";K();Ee();ai();cd();md();Te();Io();wd();Xi();Od();Ld();Md();Hd();Vd();jo=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),qw=new Set(["implement","resolve-conflict"])});var Sr=R(()=>{"use strict";zu();zd();Io()});async function Ir(t,e,r){return e.host==="github"?zw(t,e,r):e.host==="gitlab"?nk(t,e,r):ik(t,e,r)}async function Qd(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 Et(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Zd(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 Pt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await ep(e.gitlabToken,t):o}}return e.bitbucket?(await Rr(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await tp(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 Zd(t,e){let r=!1;try{r=(await Et(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 ep(t,e){let r=!1;try{r=(await Pt(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 tp(t,e){let r=!1;try{r=(await Rr(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function Et(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(Jw+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function zw(t,e,r){let n=r.githubToken;if(!n)throw new Error("GitHub PAT required to provision a github-hosted Context Repo \u2014 set GH_TOKEN / GITHUB_TOKEN or provide it during `codepipe init`");let o=await Xw(n,e,r),i=await Zw(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=ar(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await ek(n,o.owner,o.name,a.path,i)||await tk(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:i}}async function Xw(t,e,r){let n=await Et(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 Zd(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Qw(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await Et(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Qw(t,e){let{status:r,data:n}=await Et(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Zw(t,e,r){let{data:n}=await Et(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function ek(t,e,r,n,o){let{status:i,data:s}=await Et(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function tk(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 Et(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Pt(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(rk+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 nk(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 Pt(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 ep(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Pt(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 Pt(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 Pt(n,"POST","/projects",u);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ar(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let m=(await Pt(n,"GET",`/projects/${i.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 Pt(n,"POST",`/projects/${i.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:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function Rr(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let i=await fetch(ok+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 ik(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await Rr(n,"GET",o);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await tp(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let f=await Rr(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=f.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ar(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await Rr(n,"GET",`${o}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let m of l)f.set(m.path,m.content);if((await Rr(n,"POST",`${o}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let d=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:d??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Jw,rk,ok,Ao=R(()=>{"use strict";Gt();Jw="https://api.github.com";rk="https://gitlab.com/api/v4";ok="https://api.bitbucket.org/2.0"});function Ae(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=sk[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 sk,_o=R(()=>{"use strict";sk={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as ak}from"node:crypto";import{existsSync as rp,mkdirSync as ck,readFileSync as np,readdirSync as lk,rmSync as No,writeFileSync as uk}from"node:fs";import{homedir as dk}from"node:os";import{dirname as pk,join as ss}from"node:path";function op(){return ss(dk(),".codepipe","init-drafts")}function as(t){let e=ak("sha256").update(t).digest("hex").slice(0,16);return ss(op(),`${e}.json`)}function ip(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=fk)}function sp(t){let e=as(t);if(!rp(e))return null;try{let r=JSON.parse(np(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:ip(r.savedAt)?(No(e,{force:!0}),null):r}catch{return null}}function cs(t){No(as(t),{force:!0})}function ap(){let t=op();if(rp(t))for(let e of lk(t)){let r=ss(t,e);try{let n=JSON.parse(np(r,"utf-8"));ip(n.savedAt)&&No(r,{force:!0})}catch{No(r,{force:!0})}}}var fk,Tr,cp=R(()=>{"use strict";fk=24*60*60*1e3;Tr=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){cs(this.cwd)}persist(){let e=as(this.cwd);ck(pk(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};uk(e,JSON.stringify(r,null,2)+`
|
|
678
|
-
`,{mode:384})}}});function
|
|
679
|
-
`).map(n=>n.trim()).filter(Boolean);return
|
|
680
|
-
Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${n.sandboxId} \u2014 replacing the registration`),
|
|
681
|
+
`)}function E(j,g,C){let b=g[0]?.workspacePath??"";return j.replace(/\{\{codeDir\}\}/g,b).replace(/\{\{codeRoot\}\}/g,b?b.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,C??"")}function B(j,g,C){let b=j,R=C.includes("::")?"":C.split(":",2)[1]??"",A=k=>{if(!g||!R)return"";try{return ep(vr(g,"tasks",R,k),"utf-8").trim()}catch{return""}};if(b.includes("{{solutionMd}}")){let k=A("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";b=b.replace(/\{\{solutionMd\}\}/g,()=>k)}if(b.includes("{{taskDescription}}")){let k=A("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";b=b.replace(/\{\{taskDescription\}\}/g,()=>k)}return b}let pe=j=>{if(f)return;f=!0,console.log(`
|
|
682
|
+
[${j}] shutting down`),u.abort();let g=[...m.keys()];for(let R of m.values())R.abort.abort();let C=new AbortController,b=setTimeout(()=>C.abort(),3e3);(async()=>(await Promise.all(g.map(async R=>{try{await d.releaseJob(R,`sandbox ${j}`,C.signal),console.log(`[${j}] released job ${R}`)}catch(A){let k=A instanceof Error?A.message:String(A);console.warn(`[${j}] release failed: ${k} (sweeper will reclaim)`)}})),clearTimeout(b),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>pe("SIGINT")),process.on("SIGTERM",()=>pe("SIGTERM"));let we=[v("implementation")];e.planningLane!==!1?we.push(v("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(we)}var jo,Qw,tp=S(()=>{"use strict";W();Ae();li();fd();bd();Pe();Io();xd();Zi();Md();Fd();Wd();Vd();Zd();jo=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Qw=new Set(["implement","resolve-conflict"])});var xr=S(()=>{"use strict";td();tp();Io()});async function Rr(t,e,r){return e.host==="github"?rb(t,e,r):e.host==="gitlab"?lb(t,e,r):db(t,e,r)}async function np(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 Et(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await op(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 Pt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await ip(e.gitlabToken,t):o}}return e.bitbucket?(await Sr(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await sp(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 op(t,e){let r=!1;try{r=(await Et(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 ip(t,e){let r=!1;try{r=(await Pt(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 sp(t,e){let r=!1;try{r=(await Sr(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 Et(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(tb+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 rb(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 nb(n,e,r),i=await ib(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=sr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await sb(n,o.owner,o.name,a.path,i)||await ab(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 nb(t,e,r){let n=await Et(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 op(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await ob(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 Et(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 ob(t,e){let{status:r,data:n}=await Et(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function ib(t,e,r){let{data:n}=await Et(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function sb(t,e,r,n,o){let{status:i,data:s}=await Et(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function ab(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 Et(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Pt(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(cb+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 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}`),i,s=await Pt(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 ip(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Pt(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 Pt(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 Pt(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=sr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let m=(await Pt(n,"GET",`/projects/${i.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 Pt(n,"POST",`/projects/${i.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:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}async function Sr(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(ub+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 db(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 Sr(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 sp(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 Sr(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=sr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await Sr(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 Sr(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=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:d??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var tb,cb,ub,Ao=S(()=>{"use strict";Mt();tb="https://api.github.com";cb="https://gitlab.com/api/v4";ub="https://api.bitbucket.org/2.0"});function Ne(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=pb[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 pb,_o=S(()=>{"use strict";pb={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as fb}from"node:crypto";import{existsSync as ap,mkdirSync as mb,readFileSync as cp,readdirSync as gb,rmSync as No,writeFileSync as hb}from"node:fs";import{homedir as yb}from"node:os";import{dirname as wb,join as cs}from"node:path";function lp(){return cs(yb(),".codepipe","init-drafts")}function ls(t){let e=fb("sha256").update(t).digest("hex").slice(0,16);return cs(lp(),`${e}.json`)}function up(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=bb)}function dp(t){let e=ls(t);if(!ap(e))return null;try{let r=JSON.parse(cp(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:up(r.savedAt)?(No(e,{force:!0}),null):r}catch{return null}}function us(t){No(ls(t),{force:!0})}function pp(){let t=lp();if(ap(t))for(let e of gb(t)){let r=cs(t,e);try{let n=JSON.parse(cp(r,"utf-8"));up(n.savedAt)&&No(r,{force:!0})}catch{No(r,{force:!0})}}}var bb,Ir,fp=S(()=>{"use strict";bb=24*60*60*1e3;Ir=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){us(this.cwd)}persist(){let e=ls(this.cwd);mb(wb(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};hb(e,JSON.stringify(r,null,2)+`
|
|
683
|
+
`,{mode:384})}}});function mp(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 gp(){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 hp(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 yp=S(()=>{"use strict"});import{existsSync as kb}from"node:fs";import{join as $b}from"node:path";import{simpleGit as vb}from"simple-git";function Ib(t){let e=t.split("/");return e[e.length-1]??t}function wp(t){if(t.filter(r=>!Sb.test(Ib(r))).length>xb)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(Rb.has(n))return!0}return!1}async function Tb(t){try{let r=(await vb(t).raw(["ls-files"])).split(`
|
|
684
|
+
`).map(n=>n.trim()).filter(Boolean);return wp(r)}catch{return!1}}async function Cb(t,e){if(t.host!=="github")return!1;let r=e.github?.token;if(!r)return!1;let n=t.defaultBranch??"main";try{let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.repoName}/contents/?ref=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status!==200)return!1;let i=await o.json();return Array.isArray(i)?wp(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function bp(t,e){for(let r of t)try{let n=e.localRoot!=null?$b(e.localRoot,r.mountAs??r.name):null;if(n&&kb(n)?await Tb(n):await Cb(r,e.tokens))return!0}catch{}return!1}var xb,Sb,Rb,kp=S(()=>{"use strict";xb=3,Sb=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,Rb=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as $p}from"node:fs";import{join as vp}from"node:path";import{simpleGit as xp}from"simple-git";async function kn(t,e,r={}){let n=r.log??Pb,o=[];for(let i of e){let s=vp(t,i.mountAs),a=Oa(i);if(!$p(s)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${i.mountAs}/`),await xp().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(d){let f=bn(d instanceof Error?d.message:String(d));n.warn(`clone failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!$p(vp(s,".git"))){n.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=xp(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Eb(l,a)){n.warn(`${i.mountAs}/ origin (${bn(l)||"none"}) != expected (${bn(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:bn(l)});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(d){let f=bn(d instanceof Error?d.message:String(d));n.warn(`fetch failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}}return o}function Eb(t,e){return Sp(t)===Sp(e)}function Sp(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function bn(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Rp(t={}){let e=Ee();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await kn(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let n of r)console.log(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}var Pb,Oo=S(()=>{"use strict";it();Pb={info:t=>console.log(t),warn:t=>console.warn(t)}});var Tp={};Lf(Tp,{upCommand:()=>ds});import{spawn as jb}from"node:child_process";import{existsSync as Ip}from"node:fs";import{homedir as Ab,hostname as _b}from"node:os";import{join as Do}from"node:path";async function Nb(t,e,r){let n=ge(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 su(t.hubUrl.replace(/\/$/,""),n.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(o==="unsupported")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(o==="ok")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${n.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${Fe(e)} still holds its token.
|
|
685
|
+
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`),Za(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function Ob(t,e,r){let n=ge(e)!==null;if(!await Nb(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 bo(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof N&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof N&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof N?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await Ft({hub:t.hubUrl,token:o,name:r.name??`${_b()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function Db(t,e){let r=ge(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=be(r.sealPublicKey);if(!L(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Kn(t,r.sandboxId,n);if(o==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${n}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${o==="pinned"?"auto-pinned":"already pinned"} for ${t} (${n})`)}async function Lb(t,e){let r=process.cwd(),n=Do(r,Je);if(Gn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Ip(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await V(t.hubUrl,t.cliToken,t.projectId)}catch(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 i=await fs(r);if(!Na(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=L(t.projectId),a={info:d=>console.log(d),warn:d=>console.warn(d)},c=await So({cfg:t,secrets:s,contextDir:n,log:a}).catch(()=>null);if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=Do(Ab(),".codepipe",e?Do("profiles",e,"context-config"):"context-config");if(zn(c.contextDir,l,a),!Ip(Do(c.contextDir,"project.yaml"))){or(c.contextDir);let d={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Vr(c.contextDir,Qe(d,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function ds(t){let{cfg:e,profile:r}=Hn(t.profile);await Lb(e,r),await Ob(e,r,t),Db(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=>$=>{for(let w of $.toString("utf-8").split(`
|
|
681
686
|
`))w.length>0&&y.write(`${p} ${w}
|
|
682
|
-
`)};m.stdout?.on("data",h(process.stdout)),m.stderr?.on("data",h(process.stderr))},i=(m,p)=>{let h=
|
|
683
|
-
[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,$)=>h({name:m,code:y??($?1:0)}))})),u=await Promise.race(f);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),d("SIGTERM")),await Promise.all(f),process.exit(u.code)}var
|
|
687
|
+
`)};m.stdout?.on("data",h(process.stdout)),m.stderr?.on("data",h(process.stderr))},i=(m,p)=>{let h=jb(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 s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,d=m=>{if(!l){l=!0,console.log(`
|
|
688
|
+
[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,$)=>h({name:m,code:y??($?1:0)}))})),u=await Promise.race(f);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),d("SIGTERM")),await Promise.all(f),process.exit(u.code)}var ps=S(()=>{"use strict";Ae();xr();$e();at();zi();Mt();fe();ne();it();$n()});import{spawn as Ub}from"node:child_process";import{existsSync as Tr,mkdirSync as Pp,readFileSync as Ep,readdirSync as Bb,writeFileSync as jp}from"node:fs";import{join as Kt,resolve as Ap}from"node:path";import{setTimeout as ms}from"node:timers/promises";import{cancel as Mb,confirm as Cr,intro as _p,isCancel as Lo,log as T,outro as gs,password as Pr,select as He,spinner as ys,text as ie}from"@clack/prompts";import{simpleGit as Bo}from"simple-git";function ee(t){Mb(t),process.exit(1)}function he(t){return Lo(t)&&ee("aborted"),t}function X(t){return Lo(t)&&ee("aborted"),typeof t=="string"?t:""}async function Np(t={}){_p("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();pp();let r=dp(e),n,o=!1;r&&Object.keys(r.answers).length>0?he(await Cr({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(T.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Ir(e,r),o=!0):(us(e),n=new Ir(e)):n=new Ir(e);let i=t.force===!0?null:await fs(e),s=await n.ask("target",async()=>he(await He({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?T.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||Dp(e,t.force===!0));let c=await n.ask("hubUrl",async()=>X(await ie({message:"HUB URL",placeholder:We,initialValue:M("HUB_URL")??We,validate:_=>_.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Er()),{cliToken:d,accountEmail:f}=await n.ask("bootstrap",()=>jr(c,l)),u=null;s==="farm"&&(u=await Gb(c,d));let m=a?Hb(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()=>he(await He({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),$=s==="farm"?"auto":await n.ask("applyMode",async()=>he(await He({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),w=await n.ask("trackerProvider",async()=>he(await He({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),v=w==="internal",x=null,U,P=!0;if(v){let _,re=ys();re.start("checking task-key prefixes on your account\u2026");try{_=await au(c,d,{excludeProjectId:p}),re.stop("prefixes checked")}catch{re.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 Ie=Ra(Sa(h),_);U=await n.ask("trackerPrefix",async()=>X(await ie({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Ie,initialValue:Ie,validate:Oe=>{let pt=Oe.trim();if(!zt.test(pt))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(_.has(pt.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else x=await n.ask("youtrack",()=>Kp()),U=await n.ask("youtrackProjectKey",async()=>X(await ie({message:"YouTrack project key",placeholder:"DEV",validate:_=>_.trim().length>0?void 0:"required"})).trim()),P=await n.ask("youtrackWrites",async()=>he(await Cr({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let E=n.get("tokens")??{},B=()=>n.set("tokens",E),pe=await n.ask("repos",()=>qb(E,l,a,{onCred:B,initial:n.get("reposPartial")??[],onProgress:_=>n.set("reposPartial",_)}));n.delete("reposPartial");let we=await Yb(await n.ask("contextRepo",()=>Gp(p,pe,E,l)),p,pe,E,l,B,_=>n.set("contextRepo",_)),{spec:j,mode:g}=we,C;v||(T.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),C=await n.ask("assigneeLogin",async()=>X(await ie({message:"your YouTrack login (the assignee value)",...x?.login?{initialValue:x.login}:{},validate:_=>_.trim().length>0?void 0:"required"})).trim()));let b=await n.ask("llmProvider",async()=>{for(;;){if(he(await He({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";T.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),R=b==="claude"?await n.ask("claudeToken",()=>ek(s==="farm")):"",A;if(R){let _=await _l(R);if(_){let re=Xs(_);re&&(A=re,T.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${re} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let k={projectId:p,name:h,automationLevel:y,repos:pe,trackerProvider:w,youtrackProjectKey:U};T.step(`${g==="attach"?"attaching to":"provisioning"} Context Repo ${j.owner}/${j.name} (${j.host})\u2026`);let I;try{I=await Rr(k,j,{...Fp(E),youtrackWrites:P,...x?{trackerUrl:x.url}:{},mode:g,log:{info:_=>T.message(_),warn:_=>T.warn(_)}})}catch(_){ee(`Context Repo provisioning failed: ${_ instanceof Error?_.message:String(_)}`)}k.contextRepo=I,T.success(`Context Repo ready: ${I.owner}/${I.name}@${I.branch}`),T.step(`registering project on ${c}\u2026`);let K;try{K=await St(c,d,k)}catch(_){if(_ instanceof N&&_.status===409){T.warn(`project ${p} already exists on HUB \u2014 reusing it`);try{K=await V(c,d,p)}catch(re){throw re instanceof N&&ee(`HUB \u2192 ${re.status} ${re.message}`),re}}else if(_ instanceof N&&_.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 N)ee(`HUB \u2192 ${_.status} ${_.message}`);else throw _}let G=K.contextRepo??I;T.success(`project ${K.projectId} ready (${K.provisioningStatus})`);let Re=await Qb(G),Ke=x?{url:x.url,token:x.token}:void 0;if(s==="farm"){let _=u,re={...E,...Re?{contextWrite:Re}:{},...R?{claude:{oauthToken:R}}:{},...Ke?{youtrack:Ke}:{}},Ie=E.github?.token;if(G.host==="github"&&Ie)try{let J=Bu(`devpipe-${p}`);await Mu(G,Ie,J.publicKey,`devpipe-${p}`),re.contextSsh={privateKey:J.privateKey},T.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(J){T.warn(`could not set up Context Repo SSH deploy key (${J instanceof Error?J.message:String(J)}); the farm will fall back to the token path.`)}let Oe={projectId:p,config:{hubUrl:c,cliToken:d,projectId:p},secrets:re,contextRepo:G,projectConfig:Qe(k,P,x?.url,C||void 0,"auto",b,A)},pt=lt(_.farm.publicKey,JSON.stringify(Oe));T.step(`handing project ${p} to farm ${_.farm.name}\u2026`);let H;try{H=await wo(c,d,_.farm.farmId,{projectId:p,sealedBundle:pt})}catch(J){throw J instanceof N&&ee(J.status===409?`farm ${_.farm.name} is offline \u2014 start it and re-run.`:J.status===504?`farm ${_.farm.name} did not respond in time.`:`HUB \u2192 ${J.status} ${J.message}`),J}H.ok||ee(`farm rejected provisioning: ${H.error??"unknown error"}`),await hs(c,d,p,G,Ie,K.repos,null,E),n.clear(),gs(`done. project ${p} is now hosted on farm ${_.farm.name} (daemon ${H.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Hp(E),await Up(e,G.cloneUrl,G.branch),Mp(e),a&&await Wb(e);{let _=Kt(e,Je);or(_);let re=Qe(k,P,x?.url,C||void 0,$,b,A),Ie=Vr(_,re);Ie.length>0&&T.success(`local project config \u2192 .codepipe/{${Ie.join(", ")}}`),Ut(p,re,{info:Oe=>T.message(Oe),warn:Oe=>T.warn(Oe)})}await Bp(e,K.repos);let Ho={hubUrl:c,cliToken:d,projectId:p,...E,...Re?{contextWrite:Re}:{},...R?{claude:{oauthToken:R}}:{},...Ke?{youtrack:Ke}:{}};Q(Ho),st({hubUrl:c,cliToken:d,projectId:p,accountEmail:f},p),T.success(`secrets \u2192 ${ze(p)}`),await hs(c,d,p,G,E.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,K.repos,e,E),n.clear();let En=`${c}/?project=${encodeURIComponent(p)}`;Lp(En),gs(`done. your project on the dashboard (sign in there to work with it):
|
|
684
689
|
${En}
|
|
685
|
-
starting \`codepipe up\` \u2014 the CLI daemon + an agent worker. Ctrl+C stops both; start again anytime with \`codepipe up\` from this folder.`);let{upCommand:
|
|
690
|
+
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:Ko}=await Promise.resolve().then(()=>(ps(),Tp));await Ko({profile:void 0})}async function hs(t,e,r,n,o,i=[],s=null,a={}){let c=await hp(n,o);if(!c){let f=!1;try{f=await bp(i,{localRoot:s,tokens:a})}catch{f=!1}if(f){let u=gp(),m=await He({message:u.message,options:u.options,initialValue:u.initialValue});if(!Lo(m)&&m===u.proceedValue)try{let{jobId:p}=await dn(t,e,r,{reindex:!1,backfill:!0});T.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){T.warn(`could not start the retrospective analysis: ${p instanceof Error?p.message:String(p)}. Registration is not affected.`)}}}let l=mp(c),d=await He({message:l.message,options:l.options,initialValue:l.initialValue});if(!(Lo(d)||d!==l.proceedValue))try{let{jobId:f}=await dn(t,e,r,{reindex:l.reindex});T.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){T.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function Gb(t,e){let r;try{r=await nu(t,e)}catch(c){throw c instanceof N&&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=he(await He({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=ho(i.farmId,i.publicKey)}catch(c){ee(c instanceof Error?c.message:String(c))}return he(await Cr({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
686
691
|
${s}
|
|
687
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||
|
|
692
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||ee("farm fingerprint not confirmed \u2014 aborting."),go(i.farmId,s),{farm:i,fingerprint:s}}async function Op(t){_p(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Dp(e,t.force===!0);let r=X(await ie({message:"HUB URL",initialValue:M("HUB_URL")??We,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Er(),{cliToken:o,accountEmail:i}=await jr(r,n);T.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await V(r,o,t.projectId)}catch(u){throw u instanceof N&&ee(`HUB \u2192 ${u.status} ${u.message}`),u}s.contextRepo||ee(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Kp(),l={},d=new Set(s.repos.map(u=>u.host));d.add(s.contextRepo.host);for(let u of d){let m=s.repos.find(p=>p.host===u);await Uo(u,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}Hp(l),await Up(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Mp(e);{let u=Kt(e,Je);or(u);let m={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},p=Qe(m,!0,c?.url,void 0,"auto",s.llmProvider??Ve),h=Vr(u,p);h.length>0&&T.success(`local project config \u2192 .codepipe/{${h.join(", ")}} (defaults \u2014 review and adjust)`),Ut(t.projectId,p,{info:y=>T.message(y),warn:y=>T.warn(y)})}await Bp(e,s.repos);let f={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};Q(f),st({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),T.success(`secrets \u2192 ${ze(t.projectId)}`),await hs(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),gs("done.")}function Dp(t,e){if(!Tr(t)){Pp(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=Bb(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 fs(t){if(!Tr(Kt(t,".git")))return null;try{let r=(await Bo(t).remote(["get-url","origin"])||"").toString().trim(),n=r?Ne(r):null;return n?{parsed:n,defaultBranch:await Fb(t)}:null}catch{return null}}async function Fb(t){let e=Bo(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 Hb(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Ot.test(e)?e:""}function Kb(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Wb(t){let e=Kt(t,".gitignore"),r=Tr(e)?Ep(e,"utf-8"):"";if(Kb(r))return;if(!he(await Cr({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){T.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
|
|
688
693
|
`)?"":`
|
|
689
|
-
`;
|
|
694
|
+
`;jp(e,r+o+`
|
|
690
695
|
# codepipe workspace (added by \`codepipe init\`)
|
|
691
696
|
.codepipe/
|
|
692
|
-
`),T.success(`.codepipe/ added to ${
|
|
697
|
+
`),T.success(`.codepipe/ added to ${Ap(e)}`)}function Lp(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Ub(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function Er(){let t="";try{t=(await Bo().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 jr(t,e){T.step(`connecting account ${e}`);let r;try{r=await cu(t,e)}catch(s){throw s instanceof un&&ee(`${e} is not authorized on this HUB yet.
|
|
693
698
|
Sign up at ${t} (registration form on the login screen),
|
|
694
699
|
wait for the operator to approve it by email, then re-run
|
|
695
|
-
\`codepipe init\` with the same email.`),s}r.accountCreated&&T.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&T.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(
|
|
700
|
+
\`codepipe init\` with the same email.`),s}r.accountCreated&&T.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&T.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Lp(r.authorizeUrl),T.message(`a browser tab was opened to confirm this CLI:
|
|
696
701
|
${r.authorizeUrl}
|
|
697
702
|
`+(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
|
|
698
|
-
otherwise use the emailed link the page offers.`))),r.approvalRequired&&T.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),T.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await
|
|
699
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
703
|
+
otherwise use the emailed link the page offers.`))),r.approvalRequired&&T.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),T.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await lu(t,r.requestId)}catch(a){T.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await ms(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&T.message(`connected as ${a} (the account confirmed in the browser).`),T.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&ee("the HUB rejected this account"),s.status==="expired"&&ee("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,T.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
704
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await ms(5e3);continue}await ms(2e3)}ee("bootstrap timed out")}async function Up(t,e,r){let n=Kt(t,Je);if(Tr(Kt(n,".git"))){T.message(`${n} already cloned \u2014 skipping`);return}Tr(n)&&ee(`${n} exists but is not a git repo \u2014 remove it and re-run`),Pp(n,{recursive:!0}),T.step(`cloning Context Repo \u2192 ${n}`);try{await Bo().clone(e,n,["--branch",r]),T.success(`cloned ${e}`)}catch(o){ee(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function Bp(t,e){if(e.length===0)return;T.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await kn(t,r,{log:{info:o=>T.message(o),warn:o=>T.warn(o)}});for(let o of n)T.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Mp(t){let e=Kt(t,Je,".gitignore"),r="";if(Tr(e)&&(r=Ep(e,"utf-8")),Cp.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
|
|
700
705
|
`)||r.length===0?"":`
|
|
701
|
-
`,i=
|
|
706
|
+
`,i=Cp.join(`
|
|
702
707
|
`)+`
|
|
703
|
-
`;
|
|
704
|
-
`:"")+i),T.message(`appended runtime entries to ${
|
|
708
|
+
`;jp(e,r+o+(r?`
|
|
709
|
+
`:"")+i),T.message(`appended runtime entries to ${Ap(e)}`)}async function qb(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;T.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Uo(s.host,t,s.owner,e,s.repoName),i?.();let c=X(await ie({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.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:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;he(await Cr({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()||Ne(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=Ne(a);T.message(`${c.host}: ${c.owner}/${c.repoName}`),await Uo(c.host,t,c.owner,e,c.repoName),i?.();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 Gp(t,e,r,n){T.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=he(await He({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&T.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=X(await ie({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:ot(t),validate:d=>{let f=(d??"").trim();if(!f)return"required";if(!Ne(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=Ne(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Vb(),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:ot(t),initialValue:ot(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:d}}return{spec:a,mode:o}}function Fp(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??er()}}async function Yb(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Uo(c.host,n,c.owner,o),i?.();let d=ys();d.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await np(c,Fp(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=he(await He({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(u==="abort"&&ee("aborted"),u==="create")return a={spec:c,mode:"create"},s(a),a;a=await Gp(e,r,n,o),s(a)}}async function Vb(){return he(await He({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function vn(t,e){let r=ys();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 Hp(t){nn(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),on(t.gitlab?.token??process.env.GITLAB_TOKEN),sn(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Uo(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await Jb(r);i?e.github=i:T.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await zb(r,n,o);i?e.bitbucket=i:T.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await Xb();i?e.gitlab=i:T.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Jb(t){for(;;){let e=X(await Pr({message:`GitHub PAT \u2014 blank to skip
|
|
705
710
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
706
711
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
707
712
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
708
713
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
709
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await vn("GitHub",()=>yt(e,t?{owner:t}:void 0)))return{token:e};T.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function
|
|
714
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await vn("GitHub",()=>yt(e,t?{owner:t}:void 0)))return{token:e};T.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function zb(t,e,r){for(T.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
710
715
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
711
716
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
|
|
712
717
|
read:repository:bitbucket + write:repository:bitbucket +
|
|
713
718
|
read:pullrequest:bitbucket + write:pullrequest:bitbucket
|
|
714
719
|
\u2014 write scopes do NOT include read: pick BOTH scopes of each pair
|
|
715
720
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
716
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let n=
|
|
717
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await vn("GitLab",()=>
|
|
721
|
+
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:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=X(await Pr({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){T.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await vn("Bitbucket",async()=>{let i=await wt(n,o,t);if(t&&r){let s=await ro(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};T.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Xb(){for(;;){let t=X(await Pr({message:`GitLab PAT \u2014 blank to skip
|
|
722
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await vn("GitLab",()=>bt(t))){let e=await Ic(t);return e&&T.warn(e),{token:t}}T.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Qb(t){if(he(await Cr({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
718
723
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
719
724
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
720
725
|
your trusted network.`,initialValue:!1})))for(t.host==="github"?T.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
721
726
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
722
727
|
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):T.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
723
|
-
(${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=
|
|
724
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=
|
|
725
|
-
`),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function
|
|
726
|
-
`),a=s.findIndex($=>$.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),d=[],f="",u=null,m=a>=0?a+1:0;for(let $=m;$<s.length;$++){let w=(s[$]??"").trim();if(w===""){m=$+1;continue}let v=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!v)break;let x=(v[1]??"").trim().toLowerCase(),
|
|
728
|
+
(${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 Pr({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await vn("contextWrite",()=>Zb(r,t)))return{token:r};T.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Zb(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function ek(t){if(ci()?.claude?.oauthToken&&!t)return T.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";T.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t?`
|
|
729
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=X(await Pr({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||T.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),r):(T.warn(t?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}async function Kp(){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 Pr({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await vn("YouTrack",()=>xt({baseUrl:t,token:e}))){let r=await gl({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}T.warn("re-enter the YouTrack URL / token.")}}var Cp,$n=S(()=>{"use strict";Pe();W();Ae();$e();at();Mt();ao();Ao();Ji();_o();kt();Gt();fp();fe();yp();kp();Fi();co();ne();Oo();it();Cp=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});W();Pe();$e();import{Command as u$}from"commander";Bn();import{homedir as Ma}from"node:os";import{join as Ga}from"node:path";function Fa(){Lt(Ga(Ma(),".devpipe"),Ga(Ma(),".codepipe"))}$e();ne();async function tc(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=Ue(e);r&&!t.force&&(console.error(`already configured at ${Qt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");st({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...L(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};Q(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Qt(e)}`)}li();$e();import{homedir as Xi}from"node:os";import{join as fn}from"node:path";Pe();W();import{existsSync as Du,rmSync as dy}from"node:fs";import{join as pn}from"node:path";import{simpleGit as py}from"simple-git";import"ws";Pe();ne();import{createHash as wm}from"node:crypto";import{existsSync as bm,readFileSync as km}from"node:fs";import{homedir as $m,hostname as ui}from"node:os";import{join as vm}from"node:path";function ic(t){return wm("sha256").update(t).digest("hex").slice(0,12)}function xm(){let t=M("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=vm($m(),".claude","credentials.json");if(!bm(e))return;let r=JSON.parse(km(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 sc(t){let e=xm(),r=M("ACCOUNT_ID")?.trim(),n=M("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Zt(t);return o?{accountId:`acct-${ic(o)}`,label:n||ui(),...e?{email:e}:{}}:{accountId:`acct-${ic(`host:${ui()}`)}`,label:n||ui(),...e?{email:e}:{}}}import{existsSync as Sm}from"node:fs";import{join as Rm}from"node:path";import{simpleGit as Im}from"simple-git";async function ac(t,e){if(!Sm(Rm(t,".git")))return{status:"skipped"};let r=Im(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Tm(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 Tm(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as pi,readFileSync as pc,readdirSync as Em,watch as jm}from"node:fs";import{join as Yr}from"node:path";W();import{existsSync as cc,readFileSync as lc,readdirSync as Cm,statSync as Pm}from"node:fs";import{join as di}from"node:path";import{parse as uc}from"yaml";function Vn(t){let e=di(t,"actions"),r=[],n=[];if(!cc(e))return{defs:r,errors:n};let o;try{o=Cm(e).sort()}catch{return{defs:r,errors:n}}let i=new Set;for(let s of o){if(!/\.(yml|yaml)$/i.test(s))continue;let a=di(e,s);try{if(!Pm(a).isFile())continue;let c=ra(s,uc(lc(a,"utf-8")));if(i.has(c.id))throw new Error(`duplicate action id "${c.id}"`);i.add(c.id),r.push(c)}catch(c){n.push({file:`actions/${s}`,error:c instanceof Error?c.message:String(c)})}}return{defs:r,errors:n}}function dc(t){let e={},r=di(t,"project.yaml");if(!cc(r))return e;let n;try{n=uc(lc(r,"utf-8"))}catch{return e}if(!n||typeof n!="object")return e;let o=n.variables;if(!o||typeof o!="object"||Array.isArray(o))return e;for(let[i,s]of Object.entries(o))!Ce.test(i)||ft(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var Jn=class{constructor(e,r,n,o,i=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;this.intervalMs=i}timer=null;watchers=[];debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[]}installWatcher(){let e=()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()},r=[this.contextDir,Yr(this.contextDir,"prompts"),Yr(this.contextDir,"actions")];for(let n of r)if(pi(n))try{let o=jm(n,e);o.on("error",i=>{this.log.warn(`[config] fs.watch failed on ${n} \u2014 falling back to periodic reporting: ${i instanceof Error?i.message:String(i)}`);try{o.close()}catch{}}),this.watchers.push(o)}catch{}}reportNow(){this.report()}report(){try{this.send(this.read())}catch(e){this.log.warn(`[config] report failed: ${e instanceof Error?e.message:String(e)}`)}}read(){let e=Vn(this.contextDir);return{type:"config_observation",projectId:this.projectId,projectYaml:this.readFile("project.yaml"),regimenYaml:this.readFile("regimen.yaml"),prompts:this.readPrompts(),actions:e.defs,actionErrors:e.errors}}readFile(e){let r=Yr(this.contextDir,e);if(!pi(r))return null;try{return pc(r,"utf-8")}catch{return null}}readPrompts(){let e=Yr(this.contextDir,"prompts"),r={};if(!pi(e))return r;let n;try{n=Em(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=pc(Yr(e,o),"utf-8")}catch{}}return r}};ht();import{existsSync as ki,readFileSync as bc,readdirSync as Hm}from"node:fs";import{join as kc}from"node:path";import{simpleGit as Km}from"simple-git";var Wm=/^(\d{4})-(.+)\.md$/,qm="0000-template.md";function Ym(t){let e=t.split(`
|
|
730
|
+
`),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function Vm(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
731
|
+
`),a=s.findIndex($=>$.startsWith("# ")),c=a>=0&&(s[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 $=m;$<s.length;$++){let w=(s[$]??"").trim();if(w===""){m=$+1;continue}let v=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!v)break;let x=(v[1]??"").trim().toLowerCase(),U=(v[2]??"").trim(),P=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(w);P&&(u=parseInt(P[1]??"",10)),x==="tasks"&&(f=U),l.has(x)||d.push(w),m=$+1}let p=f?f.includes(n)?f:`${f}, ${n}`:n,h=s.slice(m).join(`
|
|
727
732
|
`).replace(/^\n+/,""),y=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${p}`,...d,"",h].join(`
|
|
728
733
|
`);return{content:y.endsWith(`
|
|
729
734
|
`)?y:y+`
|
|
730
|
-
`,supersedes:u}}function
|
|
735
|
+
`,supersedes:u}}function Jm(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
|
|
731
736
|
|
|
732
|
-
- **Status:** superseded by ADR-${r}`):n}function
|
|
737
|
+
- **Status:** superseded by ADR-${r}`):n}function zm(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(`
|
|
733
738
|
`)+`
|
|
734
|
-
`}async function
|
|
735
|
-
`)}async function
|
|
736
|
-
${l.trim()}`)}}let i=
|
|
737
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function en(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var
|
|
738
|
-
${w.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),y=r.push!==!1;if(y){let $=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push($)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:h,pushed:y}}async function
|
|
739
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function
|
|
740
|
-
`,o.length>
|
|
741
|
-
`))!==-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");s.stdout?.on("data",f.data),s.stderr?.on("data",u.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,p)=>{clearTimeout(l),f.flush(),u.flush(),i(a?
|
|
742
|
-
`)}function
|
|
743
|
-
`)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=
|
|
739
|
+
`}async function $c(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Km(t).pull(void 0,void 0,["--rebase"])}catch{}let i=y=>o==="staging"?`adr/DRAFT-${y}.md`:`tasks/${e}/adr/DRAFT-${y}.md`,s=[],a=[];for(let y of r){let $=ue(t,i(y));if(!ki($)){a.push(y);continue}s.push({slug:y,content:bc($,"utf-8")})}let c=kc(t,"adr"),l=new Map;if(ki(c))for(let y of Hm(c)){let $=Wm.exec(y);!$||y===qm||l.set(y,{num:parseInt($[1]??"",10),slug:$[2]??"",content:bc(kc(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 s){if([...l.entries()].find(([,P])=>P.slug===y.slug&&P.content.includes(e))){m.push(y.slug);continue}let w=d++,v=`${String(w).padStart(4,"0")}-${y.slug}.md`,{content:x,supersedes:U}=Vm(y.content,w,y.slug,e,n);if(f.set(v,x),l.set(v,{num:w,slug:y.slug,content:x}),u.push(`adr/${v}`),U!==null){let P=[...l.keys()].find(E=>E.startsWith(`${String(U).padStart(4,"0")}-`));if(P&&P!==v){let E=Jm(f.get(P)??l.get(P).content,w);f.set(P,E),l.set(P,{...l.get(P),content:E})}}}let p=[];if(o==="staging")for(let y of s)ki(ue(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(([$,w])=>({num:w.num,file:$,header:Ym(w.content)}));f.set("INDEX.md",zm(y))}for(let[y,$]of f.entries())p.push({path:`adr/${y}`,content:$});let h=u.length>0?`adr(${e}): promote ${s.map(y=>y.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await ct(t,p,h),{promoted:u,skipped:m,missing:a}}ht();at();W();import{existsSync as vc,readFileSync as Qm}from"node:fs";import{join as xc}from"node:path";function Zm(t){for(let e of[Ye,Gr]){let r=xc(t,e);if(vc(r))try{return Gs(Qm(r,"utf-8"))}catch{return 0}}return 0}function eg(t,e,r,n=3){let o=e<n,i=o?Fs(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function eo(t,e){return eg(e,Zm(t),r=>vc(xc(t,r)))}W();kt();import{existsSync as Dc,mkdirSync as Tg,mkdtempSync as Cg,rmSync as Lc,writeFileSync as Uc}from"node:fs";import{tmpdir as Pg}from"node:os";import{dirname as Eg,join as oo}from"node:path";import{simpleGit as Pi}from"simple-git";Mt();function jg(t){return`codepipe/context-migration-v${t}`}function Ag(t){let e=Hs(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 \`${Ye}\` stamp (renamed from \`${Gr}\``,"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(`
|
|
740
|
+
`)}async function Bc(t,e,r,n){let o=Pi(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=eo(t,e);if(!i.outdated)return i;let s=jg(i.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await _g(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Be(c),d=await l.findOpenPrByBranch?.(c,s)??null;if(d)return n.info(`[ctx] migration PR already open: ${d.url}`),{...i,migrationPrUrl:d.url};let f=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Ag(i)});return n.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function _g(t,e,r,n,o,i,s){let a=Pi(t),c=Cg(oo(Pg(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);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(sr(l,d).map(h=>[h.path,h.content])),u=0;for(let h of n.missingPaths){if(h===Ye)continue;let y=f.get(h);if(y==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let $=oo(c,h);Dc($)||(Tg(Eg($),{recursive:!0}),Uc($,y),u++)}Uc(oo(c,Ye),Nn(n.currentVersion)),u++;let m=oo(c,Gr);Dc(m)&&(Lc(m,{force:!0}),u++);let p=Pi(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]),s.info(`[ctx] migration branch ${o} pushed (${u} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Lc(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as Ng,readFileSync as Og,writeFileSync as Dg}from"node:fs";import{homedir as Lg}from"node:os";import{join as Mc}from"node:path";import{parseDocument as Ug}from"yaml";function Bg(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 Mg(t,e){let r=Ug(t);return r.set("repos",e.map(Bg)),r.toString()}function Gg(t,e){let r=[Mc(Lg(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Mc(e,"project.yaml")),r}function Qr(t,e,r){let n=[],o=[];for(let i of Gg(t,r))if(Ng(i))try{let s=Og(i,"utf-8"),a=Mg(s,e);a!==s&&(Dg(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}import{homedir as Fg}from"node:os";import{existsSync as Hg,mkdirSync as Kg}from"node:fs";import{join as Ei}from"node:path";import{simpleGit as ji}from"simple-git";var Gc=t=>console.log(t);function Fc(t){Gc=t}function Zr(t,e="info"){Gc(t,e)}function ve(t,e,r){let n=r??Ei(Fg(),".codepipe","repos");return Ei(n,t,e)}async function ar(t,e,r={}){let n=ve(t,e.name,r.baseDir),o=r.cloneUrlOverride??tn(e);if(!Hg(Ei(n,".git"))){Kg(n,{recursive:!0});let a=ji();Zr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
|
|
741
|
+
${l.trim()}`)}}let i=ji(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
|
|
742
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function en(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var Hc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function io(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&Zr(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await en(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await en(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...Hc,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Kc(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await en(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await en(t,o)){let s=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}async function Wc(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:d,force:f}=r,u=await Kc(t,i,()=>io(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;if(await en(t,m)||(m=`origin/${d??c}`),(await t.revparse([m])).trim()===s)await t.raw(["branch","-f",a,u]),await t.checkout(a);else{await t.checkout(["-B",a,m]);try{await t.raw([...Hc,"cherry-pick",u])}catch($){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let w=$ instanceof Error?$.message:String($);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
743
|
+
${w.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),y=r.push!==!1;if(y){let $=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push($)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:h,pushed:y}}async function qc(t,e,r){let n=r.force?["--force-with-lease","-u","origin",r.branchName]:["-u","origin",r.branchName];return await t.push(n),{pushed:!0}}async function Yc(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,d=await Kc(t,i,()=>io(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,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 Vc(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:i,deleteBranch:s}=r,a=`origin/${n}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):i==="rebase"?(await t.checkout(["-B",n,a]),await t.rebase([o]),await t.checkout(o),await t.merge(["--ff-only",n])):await t.merge(["--no-ff",a,"-m",`Merge branch '${n}'`]),await t.push(["origin",o]),s&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function tn(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}async function Jc(t){return(await ji().listRemote(["--heads",t])).split(`
|
|
744
|
+
`).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 zc(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}Ae();ne();function zg(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 tl(t,e,r,n){let o=zg(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(o),s=[];for(let a of t.sandboxes){let c=Kn(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=lt(a.publicKey,i)}catch(d){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${d instanceof Error?d.message:String(d)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}Ae();ne();kt();Gt();ao();co();function Ll(t){let e=L(t);if(!e)return null;if(!e.sealKey){let r=so();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 Ul(t,e,r,n){let o;try{o=JSON.parse(cr(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=L(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await yt(o.token);return i.github={token:o.token},lr(i,()=>{process.env.GH_TOKEN=o.token,Nl(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await bt(o.token);return i.gitlab={token:o.token},lr(i,()=>{process.env.GITLAB_TOKEN=o.token,Ol(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await wt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},lr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Dl(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await xt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},lr(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Oi(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},lr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},lr(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function lr(t,e){Q(t),e()}W();W();import{spawn as dh}from"node:child_process";var ph=124,Bl=16*1024,Ml=4e3;function fh(t,e,r,n,o,i){let s={...t},a=(c,l)=>{ft(c)||(s[c]=l)};for(let[c,l]of Object.entries(e))a(c,l);for(let[c,l]of Object.entries(r))a(c,l);for(let[c,l]of Object.entries(n??{}))a(c,l);for(let[c,l]of Object.entries(o))s[c]=l;for(let[c,l]of Object.entries(i))s[`INPUT_${c}`]=String(l);return s}async function Gl(t){let{def:e,onEvent:r}=t,n=fh(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
745
|
+
`,o.length>Bl&&(o=o.slice(o.length-Bl))},s=(a,c)=>{let l=c.length>Ml?c.slice(0,Ml)+"\u2026":c;i(l),r({ts:Date.now(),kind:"log",stream:a,text:l})};r({ts:Date.now(),kind:"start",status:"running"});for(let[a,c]of e.steps.entries()){let l=c.name??`step ${a+1}`;r({ts:Date.now(),kind:"step",stepName:l});let d=await mh(c.run,c.timeout_sec,t.cwd,n,s);if(d!==0)return i(`[${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 mh(t,e,r,n,o){return new Promise(i=>{let s=dh("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??ta)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let d=m=>{let p="";return{data:h=>{p+=h.toString("utf-8");let y;for(;(y=p.indexOf(`
|
|
746
|
+
`))!==-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");s.stdout?.on("data",f.data),s.stderr?.on("data",u.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,p)=>{clearTimeout(l),f.flush(),u.flush(),i(a?ph:m??(p?1:0))})})}ht();import{existsSync as gh,readFileSync as hh,statSync as Fl}from"node:fs";var Hl=2*1024*1024;function yh(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Kl(t,e){let r=ue(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!gh(r)||!Fl(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Fl(r);if(n>Hl)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Hl})`);let o=hh(r);return yh(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}ne();W();import{existsSync as wh,readFileSync as bh,writeFileSync as kh}from"node:fs";import{join as $h}from"node:path";import{parseDocument as vh}from"yaml";async function Wl(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=ca(o);if(!i.ok)throw new Error(i.error);let s=r.get(o.file)??[];s.push({path:i.field.path,value:i.value}),r.set(o.file,s)}let n=[];for(let[o,i]of r){let s=$h(t,o);if(!wh(s))throw new Error(`${o} not found in context repo (${t})`);let a=vh(bh(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);kh(s,a.toString()),n.push(o)}return{files:n}}W();import{existsSync as xh,readFileSync as Sh,writeFileSync as Rh}from"node:fs";import{join as Ih}from"node:path";import{isMap as ql,parseDocument as Th}from"yaml";async function Yl(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||!ma(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=Ih(t,"project.yaml");if(!xh(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Th(Sh(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>ql(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!ql(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),Rh(o,i.toString()),{repoName:r,defaultBranch:n}}import{existsSync as Li,readFileSync as Ui,writeFileSync as Ch}from"node:fs";import{join as lo}from"node:path";import{parseDocument as Bi}from"yaml";async function Vl(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.doneColumns!==void 0||e.reviewColumns!==void 0||e.statusColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let i=lo(t,"project.yaml");if(!Li(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Bi(Ui(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.doneColumns!==void 0){let a=e.doneColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","done_columns"],a):s.deleteIn(["youtrack","done_columns"])}if(e.reviewColumns!==void 0){let a=e.reviewColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","review_columns"],a):s.deleteIn(["youtrack","review_columns"])}if(e.statusColumns!==void 0){let a=e.statusColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","status_columns"],a):s.deleteIn(["youtrack","status_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?s.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?s.setIn(["youtrack","backlog_scope"],"shared"):s.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=lo(t,"regimen.yaml");if(!Li(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Bi(Ui(i,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&s.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;s.setIn(["youtrack","writes","enabled"],a.enabled===!0),s.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),s.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),s.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:s.toString()})}if(r.length===0)return{files:[]};for(let i of r)Ch(lo(t,i.path),i.content);return{files:r.map(i=>i.path)}}function uo(t){if(!t)return"Stage";try{let e=lo(t,"project.yaml");if(!Li(e))return"Stage";let n=Bi(Ui(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}kt();Gt();import{existsSync as Xl,readFileSync as Ql}from"node:fs";import{join as Zl}from"node:path";import{parseDocument as eu}from"yaml";Gt();var an=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Il(this.cfg,e)}getIssue(e,r){return Tl(this.cfg,e,r??uo(this.contextDir))}listComments(e,r){return Cl(this.cfg,e,r)}downloadAttachment(e){return Rl(this.cfg,e)}updateStatus(e,r){return hl(this.cfg,e,r,uo(this.contextDir))}addComment(e,r,n){return yl(this.cfg,e,r)}createIssue(e){return kl(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,uo(this.contextDir))}editIssue(e,r){return wl(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return $l(this.cfg,e,r,n)}fetchStateFields(e){return El(this.cfg,e)}};W();ht();import{existsSync as Oh,readFileSync as Dh}from"node:fs";import{randomBytes as Lh}from"node:crypto";import{existsSync as Jl,readFileSync as Ph,readdirSync as Eh}from"node:fs";W();ht();function po(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Nh(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:jh(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:_h(Ah(t,i,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function fo(t,e,r){if(r.length===0)return;let n=po(t,e,r),o=r.map(i=>i.issue.key);await ct(t,n,`sync(${o.join(", ")}): task data`)}function jh(t,e,r){let n=new Date(t.updatedAt).toISOString(),o=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${n}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){o.push("## Attachments","");for(let i of r)o.push(`- [${i}](attachments/${encodeURI(i)})`);o.push("")}return o.join(`
|
|
747
|
+
`)}function Ah(t,e,r){let n=new Map,o=ue(t,`tasks/${e}/comments.jsonl`);if(Jl(o))for(let i of Ph(o,"utf-8").split(`
|
|
748
|
+
`)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Jt(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function _h(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
744
749
|
`)+(t.length>0?`
|
|
745
|
-
`:"")}function
|
|
750
|
+
`:"")}function Nh(t,e,r){let n=[],o=ue(t,`tasks/${e}/attachments`);if(Jl(o))for(let i of Eh(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}no();var cn=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Jr(this.contextDir);let r=e.columns??[];return _c(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Xr(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=zr(this.contextDir,e);return r?Xr(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return zl(this.contextDir,e).map(n=>({id:n.id,issueId:e,author:n.author,body:n.body,createdAt:n.createdAt}))}async downloadAttachment(e){throw new Error(`internal tracker: no remote attachments (${e})`)}async updateStatus(e,r){await this.mutateRecord(e,n=>({...n,status:r}))}async addComment(e,r,n){if(await Jr(this.contextDir),!zr(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${Lh(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Jt(r);s&&(i.parsedCommand=s);let c=[...zl(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
|
|
746
751
|
`)+`
|
|
747
|
-
`;return await
|
|
748
|
-
`)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}oo();function Ui(t){if(!t)return"youtrack";try{let e=Vl(t,"project.yaml");return ql(e)&&Jl(Yl(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Qe(t){let e=Ui(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=Tc(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Ah(n);return i?{ok:!0,kind:e,provider:new cn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=ul();return r?{ok:!0,kind:e,provider:new an(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Ah(t){try{let e=Vl(t,"project.yaml");if(!ql(e))return null;let r=Jl(Yl(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var mo=new Map;async function ln(t,e){let n=(mo.get(t)??Promise.resolve()).catch(()=>{}).then(e);mo.set(t,n);try{return await n}finally{mo.get(t)===n&&mo.delete(t)}}async function zl(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;Zr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{commit:c,pushed:l}=await Gc(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});return ee({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir);return await Fc(s,a,{branchName:e.branchName,force:e.force}),ee({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{commit:c,pushed:l}=await Hc(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ee({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return F("no repo spec");let i=Le(r),s=await i.createPullRequest(r,e);return ee({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return F("no repo spec");let i=Le(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ee({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return F("no repo spec");let i=Le(r);return await i.closePR(r,e.prNumber,e.comment),ee({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{mergedSha:c}=await Kc(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ee({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return F("no repo spec");let i=t.cloneUrlOverride??tn(r),a=(await Wc(i)).filter(d=>qc(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 ee({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return F("no repo spec");let i=Le(r);return await i.addPRComment(r,e.prNumber,e.body),ee({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=Qe({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ee({issueId:t.trackerIssueId,newStatus:e.newStatus})):F("no tracker_issue_id provided"):F(i.error)}case"tracker_comment":{let i=Qe({contextDir:t.contextDir});if(!i.ok)return F(i.error);if(!t.trackerIssueId)return F("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ee({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Qe({contextDir:t.contextDir});if(!i.ok)return F(i.error);if(!e.projectKey)return F("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ee({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Qe({contextDir:t.contextDir});if(!i.ok)return F(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 F(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ee({applied:s})}case"set_project_setting":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await Ml(t.contextDir,e.edits);return ee({files:i.files})}case"tracker_edit":{let i=Qe({contextDir:t.contextDir});if(!i.ok)return F(i.error);if(!t.contextDir)return F("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 fo(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ee({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await Hl(t.contextDir,e);return ee({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await Fl(t.contextDir,e);return ee({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ee({reported:!0})):F("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return F("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ee({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return F("no project workspace on this CLI");if(!r)return F("no repo spec");if(!t.onRunActivity)return F("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Jn(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(p=>p.file===`actions/${e.actionId}.yml`);return F(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Zs(c,e.input);if(!l.ok)return F(l.error);let d=ac(t.contextDir),f=U(e.projectId),u={};return f?.github?.token&&(u.GH_TOKEN=f.github.token),f?.gitlab?.token&&(u.GITLAB_TOKEN=f.gitlab.token),f?.bitbucket&&(u.BITBUCKET_EMAIL=f.bitbucket.email,u.BITBUCKET_API_TOKEN=f.bitbucket.apiToken),f?.youtrack&&(u.YOUTRACK_URL=f.youtrack.url,u.YOUTRACK_TOKEN=f.youtrack.token),ln(`${e.projectId}/${r.name}`,async()=>{await cr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=$e(e.projectId,r.name,t.baseDir),p=await Dl({cwd:m,def:c,input:l.values,variables:d,secrets:f?.secrets??{},credEnv:u,onEvent:h=>i(e.runId,h)});return ee({runId:e.runId,status:p.status,exitCode:p.exitCode,...p.failedStep?{failedStep:p.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=Bl(t.contextDir,e.path);return ee({path:e.path,...i})}default:return F(`unsupported action type: ${e.type}`)}}catch(i){return F(i instanceof Error?i.message:String(i))}}function ee(t){return{status:"done",result:t}}function F(t){return{status:"failed",error:t}}Ee();Mi();pe();te();import{existsSync as fu,readFileSync as mu}from"node:fs";import{join as gu}from"node:path";async function hu(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=we(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");ho(e.farmId,e.farmPublicKey);let s=U(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await V(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=gu(r,"project.yaml"),m=gu(r,"regimen.yaml");fu(u)&&fu(m)?c={projectYaml:mu(u,"utf-8"),regimenYaml:mu(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},d=ct(e.farmPublicKey,JSON.stringify(l));go(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await wo(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(i){return o(i instanceof Error?i.message:String(i))}}Ee();Te();Ee();import{homedir as Kh}from"node:os";import{existsSync as Wh,mkdirSync as qh,readFileSync as Yh,writeFileSync as Vh}from"node:fs";import{dirname as Jh,join as zh}from"node:path";function Hi(){return G("RUNNER_PINS")??zh(Kh(),".codepipe","runner-pins.json")}function yu(){let t=Hi();if(!Wh(t))return{};try{return JSON.parse(Yh(t,"utf-8"))}catch{return{}}}function Xh(t){let e=Hi();qh(Jh(e),{recursive:!0}),Vh(e,JSON.stringify(t,null,2)+`
|
|
749
|
-
`,{mode:384})}function Qh(t){return yu()[t]}function Ki(t,e){let r=yu();r[t]=e,Xh(r)}function wu(t,e){let r=we(e),n=Qh(t);if(n&&n!==r)throw new Error(`runner host ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the runner host was re-registered intentionally, remove its entry from ${Hi()}.`);return r}pe();te();var bu=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function ku(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:bu(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var Zh={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:bu(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)=>ku(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>ku(t,e,r,"remove-token")},$u={api:Zh,fetchProject:V,provisionOnRunner:Zl,teardownOnRunner:eu};async function vu(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(we(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");wu(e.runnerId,e.runnerPublicKey);let i=U(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).filter(c=>c.host==="github");if(a.length===0)throw new Error("the project has no GitHub repositories \u2014 nothing to connect a runner to");return{githubToken:i,repos:a}}async function xu(t,e,r,n=$u){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await vu(t,e,n),a=[];for(let u of s)await n.api.repoHasAdmin(i,u.owner,u.repoName)||a.push(`${u.owner}/${u.repoName}`);if(a.length>0)return o(`the GitHub token lacks admin access on ${a.join(", ")} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on every repository`);let c=[];for(let u of s)c.push({owner:u.owner,repo:u.repoName,regToken:await n.api.mintRegistrationToken(i,u.owner,u.repoName)});let l={projectId:t.projectId,runners:c},d=ct(e.runnerPublicKey,JSON.stringify(l));Ki(e.runnerId,e.fingerprint),r.info(`[ghr] ${c.length} registration token(s) sealed for runner host ${e.runnerName} \u2014 handing off`);let f=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle: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(i){return o(i instanceof Error?i.message:String(i))}}async function Su(t,e,r,n=$u){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await vu(t,e,n),a=[];for(let f of s)try{a.push({owner:f.owner,repo:f.repoName,removeToken:await n.api.mintRemoveToken(i,f.owner,f.repoName)})}catch(u){r.warn(`[ghr] remove-token for ${f.owner}/${f.repoName} failed (${u instanceof Error?u.message:u}) \u2014 the runner host will force-remove`),a.push({owner:f.owner,repo:f.repoName})}let c={projectId:t.projectId,runners:a},l=ct(e.runnerPublicKey,JSON.stringify(c));Ki(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle sealed for runner host ${e.runnerName} \u2014 handing off`);let 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(i){return o(i instanceof Error?i.message:String(i))}}pe();K();Ee();te();var Ru=16*1024;function ey(t){return Ie.test(t)?ft(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ie}`}function Iu(t,e,r,n){let o=ey(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(lr(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>Ru)return{ok:!1,detail:`secret value too large (max ${Ru} chars)`};try{return qa(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Tu(t,e){try{return Ya(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}te();bt();var bo=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=Le(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof Mt){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Le(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=ty(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function ty(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}K();var $o=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??(()=>Qe({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let v=e.stageField?{stageField:e.stageField}:{},x=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},P=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(P){let j=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[M,de]=await Promise.all([j.length>0?r.listIssues({projectKey:e.projectKey,columns:j,...v,...x}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...v})]),ye=new Map;for(let A of[...M,...de])ye.set(A.id,A);o=[...ye.values()]}else{let j=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:j,...v,...x})}}catch(v){this.log.warn(`[yt-sync] listIssues failed: ${v instanceof Error?v.message:String(v)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let v of o){if(s.add(v.id),a.has(v.status))continue;let x=await Pu(r,v.id,e.sinceMs,this.log);x&&i.set(v.id,x)}let c=[];for(let v of e.offBoardIssueIds){if(s.has(v))continue;let x=await Pu(r,v,e.sinceMs,this.log);if(x&&x.length>0&&i.set(v,x),e.requireAssignee||x&&x.length>0){let B=await oy(r,v,e.stageField,this.log);if(B)c.push(B);else if(x&&x.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(v=>!a.has(v.status)),{attachmentsByIssue:d,attachmentKeys:f}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let u=[...l,...c].map(v=>({issue:v,comments:i.get(v.id)??[],attachments:d.get(v.id)??[]}));try{await fo(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let v of f)this.shippedAttachments.add(v)}catch(v){let x=v instanceof Error?v.message:String(v);this.abandonTick(`context task sync failed: ${x}`);return}let m=this.options.isSelfComment??(()=>!1),p=[],h=[];for(let[v,x]of i){let B=x.filter(j=>!m(j.id));if(B.length===0)continue;p.push({issueId:v,comments:B.map(ry)});let P=B.flatMap(j=>{let M=zt(j.body);return M?[{commentId:j.id,author:j.author,name:M.name,args:M.args,createdAt:j.createdAt}]:[]});P.length>0&&h.push({issueId:v,commands:P})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Cu),commentsBatch:p,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Cu)}:{},observedAtMs:n};this.send(y);let $=p.reduce((v,x)=>v+x.comments.length,0),w=h.reduce((v,x)=>v+x.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${$} commands=${w} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let d of r.get(s.id)??[])a.push(...d.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let d of a){let f=`${s.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} (${s.id}) download failed: ${p instanceof Error?p.message:String(p)}`);continue}let m=ny(d.name);l.has(m)&&(m=`${d.id}-${m}`),l.add(m),c.push({name:m,contentBase64:u.toString("base64")}),i.push(f)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Cu(t){let{description:e,...r}=t;return r}function ry(t){let{body:e,...r}=t;return r}function ny(t){let r=(t.split(/[\\/]/).pop()??t).replace(/[^A-Za-z0-9._-]/g,"_").replace(/^\.+/,"");return r.length>0?r.slice(0,120):"attachment"}async function oy(t,e,r,n){try{return await t.getIssue(e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Pu(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Wi="npm i -g @code-partner/codepipe@latest";function vo(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&&uc(o.contextDir,r);let i=Eu("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Eu("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=yo(t.hubUrl,t.cliToken),h=null,y=new bo(i,g=>{p.readyState===p.OPEN&&p.send(JSON.stringify(g))},r),$=new $o(s,g=>{p.readyState===p.OPEN&&p.send(JSON.stringify(g))},r,{contextDir:o?.contextDir??null,isSelfComment:g=>f.has(g)}),w=null,v=async()=>{try{let g={trackerProvider:Ui(o?.contextDir??null)};try{let I=await V(t.hubUrl,t.cliToken,t.projectId);g={...g,repos:I.repos,contextRepo:I.contextRepo}}catch(I){r.warn(`[readiness] could not fetch project summary for push checks: ${I instanceof Error?I.message:String(I)}`)}let C=await Cl(t.projectId,g);if(p.readyState!==p.OPEN)return;let b={type:"cli_readiness",projectId:t.projectId,ready:C.ready,checks:C.checks,creds:C.creds,secretNames:Va(t.projectId),checkedAt:C.checkedAt};if(p.send(JSON.stringify(b)),C.ready)r.info("[readiness] ready");else{let I=C.checks.filter(E=>!E.ok).map(E=>`${E.name}(${E.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${I.join(", ")}`)}}catch(g){r.warn(`[readiness] check failed: ${g instanceof Error?g.message:String(g)}`)}},x=()=>{v(),w=setInterval(()=>void v(),a),typeof w.unref=="function"&&w.unref()},B=()=>{w&&(clearInterval(w),w=null)},P=150,j=new Map,M=g=>{let C=j.get(g);if(!C||(C.timer&&clearTimeout(C.timer),j.delete(g),C.events.length===0||p.readyState!==p.OPEN))return;let b={type:"run_activity",projectId:t.projectId,runId:g,events:C.events};p.send(JSON.stringify(b))},de=(g,C)=>{let b=j.get(g);if(b||(b={events:[],timer:null},j.set(g,b)),b.events.push(C),C.kind==="result"){M(g);return}b.timer||(b.timer=setTimeout(()=>M(g),P),b.timer.unref?.())},ye=o?.contextDir?new zn(o.contextDir,t.projectId,g=>{p.readyState===p.OPEN&&p.send(JSON.stringify(g))},r):null,A=async()=>{let g=o?.contextDir;if(!g)throw new Error("no context repo clone on this CLI");let C;try{C=(await V(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let b=await Oc(g,t.projectId,C,r);return p.readyState===p.OPEN&&p.send(JSON.stringify(b)),b};return p.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let g=rc(t.projectId),C=G("ORIGIN")==="farm"?"farm":"local",b=G("FARM_ID"),I=t.accountEmail??g.email,E;try{let S=Al(t.projectId);S&&(E=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 k={type:"register",projectId:t.projectId,platformVersion:Re,protocolVersion:Ke,accountId:g.accountId,accountLabel:g.label,origin:C,inFlightActionIds:[...d],...I?{accountEmail:I}:{},...C==="farm"&&b?{farmId:b}:{},...E?{sealPublicKey:E}:{}};p.send(JSON.stringify(k))}),p.on("message",async g=>{let C=g.toString("utf-8");if(C==="pong"||C==="ping")return;let b;try{b=JSON.parse(C)}catch{return}if(!b||typeof b!="object")return;let I=b.type;if(I==="registered"){let k=b;if(k.ok){if(r.info(`[ws] registered for project ${k.projectId}`),n({kind:"registered",projectId:k.projectId??t.projectId}),y.start(),ye?.start(),x(),qi(t,o,r),o?.contextDir)try{let S=to(o.contextDir,t.projectId);p.readyState===p.OPEN&&p.send(JSON.stringify(S)),S.outdated&&(r.warn(`[ctx] context format outdated: v${S.templateVersion} \u2192 v${S.currentVersion}`+(S.missingPaths.length>0?` (missing: ${S.missingPaths.join(", ")})`:"")),l||(l=!0,A().catch(()=>{})))}catch(S){r.warn(`[ctx] context-format detect failed (non-fatal): ${S instanceof Error?S.message:String(S)}`)}}else r.warn(`[ws] register rejected: ${k.reason??"unknown"}`),n({kind:"register_rejected",reason:k.reason??"unknown"}),c=!0,p.close();return}if(I==="hello"){let k=b;h=_n(k.protocolVersion);let S=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${k.platformVersion} (protocol ${k.protocolVersion}) \u2014 ${S}`),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: ${Wi}`),n({kind:"incompatible",hubVersion:typeof k.platformVersion=="string"?k.platformVersion:null,hubProtocol:typeof k.protocolVersion=="number"?k.protocolVersion:null,updateCommand:Wi}));return}if(I==="tracking_targets"){y.setTargets(b.targets);return}if(I==="youtrack_sync_request"){$.setRequest(b);return}if(I==="youtrack_force_sync"){$.forceSync();return}if(I==="sync_local"){await ly(b,o,p,r);return}if(I==="provision_repo"){let k=b;r.info(`[repo] provision_repo: ${k.repo.name} (${k.repo.host}:${k.repo.owner}/${k.repo.repoName})`),await ay(t,o,k.repo,r),await qi(t,o,r);return}if(I==="remove_repo"){let k=b;r.info(`[repo] remove_repo: ${k.repoName}${k.purge?" (purge)":""}`),await qi(t,o,r),k.purge&&cy(t,o,k.repoName,r);return}if(I==="context_write"){await uy(b,o,p,r);return}if(I==="adr_promote"){await dy(b,o,p,r);return}if(I==="cred_update"){let k=b,S=U(t.projectId),H=S?.sealKey?await _l(t.projectId,k.kind,k.sealed,S.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},W={type:"cred_update_result",updateId:k.updateId,projectId:t.projectId,ok:H.ok,...H.detail?{detail:H.detail}:{}};p.readyState===p.OPEN&&p.send(JSON.stringify(W)),H.ok?(r.info(`[cred] ${k.kind} replaced${H.detail?` \u2014 ${H.detail}`:""}`),v()):r.warn(`[cred] ${k.kind} replacement rejected: ${H.detail??"unknown"}`);return}if(I==="move_to_farm"){let k=b;r.info(`[farm-move] request to move ${t.projectId} onto farm ${k.farmName} (${k.farmId})`);let S=await hu(t,k,o?.contextDir,r);p.readyState===p.OPEN&&p.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(I==="gh_runner_setup"){let k=b;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${k.runnerName} (${k.runnerId})`);let S=await xu(t,k,r);p.readyState===p.OPEN&&p.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners connected on ${k.runnerName}`):r.warn(`[ghr] setup failed: ${S.error??"see per-repo statuses"}`);return}if(I==="gh_runner_teardown"){let k=b;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${k.runnerName} (${k.runnerId})`);let S=await Su(t,k,r);p.readyState===p.OPEN&&p.send(JSON.stringify(S)),S.ok?r.info(`[ghr] runners disconnected from ${k.runnerName}`):r.warn(`[ghr] teardown failed: ${S.error??"unknown error"}`);return}if(I==="tracker_fields_request"){let k=b,S={type:"tracker_fields_result",requestId:k.requestId,projectId:t.projectId,ok:!1},H=Qe({contextDir:o?.contextDir??null});if(!H.ok)S.error=H.error;else try{S.fields=await H.provider.fetchStateFields(k.projectKey),S.ok=!0}catch(W){S.error=W instanceof Error?W.message:String(W)}p.readyState===p.OPEN&&p.send(JSON.stringify(S)),S.ok||r.warn(`[yt-fields] listing failed: ${S.error??"unknown"}`);return}if(I==="project_secret_update"||I==="project_secret_delete"){let k=b,S;if(k.type==="project_secret_update"){let W=U(t.projectId);S=W?.sealKey?Iu(t.projectId,k.name,k.sealed,W.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else S=Tu(t.projectId,k.name);let H={type:"project_secret_update_result",updateId:k.updateId,projectId:t.projectId,ok:S.ok,...S.detail?{detail:S.detail}:{}};p.readyState===p.OPEN&&p.send(JSON.stringify(H)),S.ok?(r.info(`[secret] ${k.name} ${k.type==="project_secret_update"?"saved":"deleted"}`+(S.detail?` \u2014 ${S.detail}`:"")),v()):r.warn(`[secret] ${k.name} rejected: ${S.detail??"unknown"}`);return}if(I==="sandbox_keys"){let k=U(t.projectId);if(!k){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let S=er(t.projectId),H=Xc(b,k,S,r);for(let W of H)p.readyState===p.OPEN&&p.send(JSON.stringify(W));return}if(I!=="dispatch_action")return;let E=b;if(h===!1){let k=`refused: HUB protocol incompatible with CLI v${Re} (protocol ${Ke})`;p.send(JSON.stringify({type:"action_result",actionId:E.actionId,status:"failed",error:k})),r.warn(`[exec] ${E.actionId} (${E.action.type}) \u2192 REFUSED: ${k}`),r.warn(`[exec] update the CLI to clear this: ${Wi}`),n({kind:"action",actionId:E.actionId,actionType:E.action.type,ok:!1,error:k});return}d.add(E.actionId);try{let k=await zl({action:E.action,repo:E.repo,trackerIssueId:E.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:ye?()=>ye.reportNow():void 0,refreshContextStatus:o?.contextDir?A:void 0,onRunActivity:de}).catch(W=>({status:"failed",error:W instanceof Error?W.message:String(W)}));E.action.type==="tracker_comment"&&k.status==="done"&&"result"in k&&typeof k.result?.commentId=="string"&&f.add(k.result.commentId),p.send(JSON.stringify({type:"action_result",actionId:E.actionId,...k}));let S=k.status!=="failed",H=!S&&"error"in k?k.error:void 0;S?r.info(`[exec] ${E.actionId} (${E.action.type}) \u2192 done`):r.warn(`[exec] ${E.actionId} (${E.action.type}) \u2192 FAILED: ${H??"?"}`),n({kind:"action",actionId:E.actionId,actionType:E.action.type,ok:S,...H?{error:H}:{}})}finally{d.delete(E.actionId)}}),p.on("close",(g,C)=>{let b=C?.toString("utf-8")??"";if(r.info(`[ws] closed code=${g}${b?` reason=${b}`:""}`),y.stop(),$.stop(),ye?.stop(),B(),b==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:g}),!c&&setTimeout(()=>{u=m()},2e3)}),p.on("error",g=>r.warn(`[ws] error: ${g.message}`)),p}return{stop(){c=!0,u.close()}}}async function qi(t,e,r){try{let n=await V(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Qr(t.projectId,n.repos,e?.contextDir);for(let s of o)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function ay(t,e,r,n){let o=r.mountAs??r.name;if(o==="."){n.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?pn(e.root,o):$e(t.projectId,r.name);if(ju(pn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await sy().clone(tn(r),i),n.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function cy(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?pn(e.root,o):$e(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!ju(pn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{iy(i,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${i}`)}catch(s){n.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function ly(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let i=e.repos.find(l=>l.name===o.repoName),s=pn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await nc(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function uy(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await at(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function dy(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=t.source??"task",s=await yc(e.contextDir,t.taskKey,t.slugs,void 0,i);if(n.info(`[adr] adr_promote ${t.id}: promoted ${s.promoted.length}, skipped ${s.skipped.length}`+(s.promoted.length>0?` (${s.promoted.join(", ")})`:"")),s.missing.length>0){let a=l=>i==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${s.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function Eu(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}pe();te();st();Vi();ot();co();async function Hu(t={profile:void 0}){let{cfg:e,profile:r}=Kn(t.profile),n=U(e.projectId);n&&qr(n),nn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),on(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),sn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=fn(Ji(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Yn("CLI_LOG",i,o);if(s.enabled){let u=new rr(s);Vn(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=Fn(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let u=fn(Ji(),".codepipe",r?fn("profiles",r,"context"):"context");if(await Fi(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Gu(()=>So({cfg:e,secrets:n,contextDir:u,log:{info:m=>console.log(m),warn:m=>console.warn(m)}}),{log:{warn:m=>console.warn(m)}}),a||await Fi(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let m=fn(Ji(),".codepipe",r?fn("profiles",r,"context-config"):"context-config");Xn(a.contextDir,m,{info:p=>console.log(p),warn:p=>console.warn(p)})}}let l=vo(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(`
|
|
750
|
-
[${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}Sr();be();pe();async function Xd(t={profile:void 0}){let e=Pe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=yo(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 d=l.toString("utf-8");if(s.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=>s.push(`error:${l.message}`)),r.on("close",(l,d)=>{s.push(`close:${l}:${d?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await V(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=me(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}$n();import{readFileSync as Jk}from"node:fs";K();be();st();Ao();Gt();bt();Ft();pe();te();function re(t){throw new Error(t)}function ue(t,e){return(typeof t!="string"||t.trim().length===0)&&re(`config: '${e}' must be a non-empty string`),t.trim()}function xn(t,e){if(t==null)return;typeof t!="string"&&re(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function zk(t){(!t||typeof t!="object")&&re("config: expected a JSON object");let e=t,r=ue(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||re("config: 'hubUrl' must start with http(s)://");let n=ue(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&re("config: 'project' is required");let i=o,s=ue(i.id,"project.id");Dt.test(s)||re("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=ue(i.name,"project.name"),c=ue(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&re("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||re("config: 'project.repos' must be an array");let d=l.map((w,v)=>{(!w||typeof w!="object")&&re(`config: project.repos[${v}] must be an object`);let x=w,B=ue(x.host,`project.repos[${v}].host`);B!=="github"&&B!=="bitbucket"&&B!=="gitlab"&&re(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let P={name:ue(x.name,`project.repos[${v}].name`),host:B,owner:ue(x.owner,`project.repos[${v}].owner`),repoName:ue(x.repoName,`project.repos[${v}].repoName`)},j=xn(x.defaultBranch,`project.repos[${v}].defaultBranch`);j&&(P.defaultBranch=j);let M=xn(x.mountAs,`project.repos[${v}].mountAs`);return M&&(P.mountAs=M),P}),f=i.contextRepo;(!f||typeof f!="object")&&re("config: 'project.contextRepo' is required");let u=f,m=xn(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&re("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let p={host:m,owner:ue(u.owner,"project.contextRepo.owner"),name:xn(u.name,"project.contextRepo.name")??nt(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:d,contextRepo:p}},y=xn(i.youtrackProjectKey,"project.youtrackProjectKey");if(y&&(h.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&re("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&re("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let w=ue(i.llmProvider,"project.llmProvider");w==="codex"&&re(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),w!=="claude"&&re("config: 'project.llmProvider' must be 'claude'"),h.project.llmProvider=w}let $=e.secrets;if($!==void 0){(typeof $!="object"||$===null)&&re("config: 'secrets' must be an object");let w=$,v={};if(w.github){let x=w.github;v.github={token:ue(x.token,"secrets.github.token")}}if(w.bitbucket){let x=w.bitbucket;v.bitbucket={email:ue(x.email,"secrets.bitbucket.email"),apiToken:ue(x.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let x=w.gitlab;v.gitlab={token:ue(x.token,"secrets.gitlab.token")}}if(w.youtrack){let x=w.youtrack;v.youtrack={url:ue(x.url,"secrets.youtrack.url").replace(/\/$/,""),token:ue(x.token,"secrets.youtrack.token")}}if(w.contextWrite){let x=w.contextWrite;v.contextWrite={token:ue(x.token,"secrets.contextWrite.token")}}h.secrets=v}return h}async function Xk(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Qk(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await yt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await wt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await no(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 kt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await xt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Mp(t){let e=!t.configPath||t.configPath==="-"?await Xk():Jk(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){re(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=zk(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 Qk(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 Ir(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??tr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){re(`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 St(o,i,a)}catch(u){if(u instanceof N&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),d=await V(o,i,s.id);else if(u instanceof N)re(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${d.projectId} ready (${d.provisioningStatus})`);let f={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(X(f),it({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Je(s.id)}`),Bt(s.id,Xe(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??Ye),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await dn(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`)}be();te();import{cancel as Gp,intro as Fp,isCancel as Hp,log as hs,outro as Zk,password as Kp}from"@clack/prompts";async function eb(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Wp(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await eb(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Fp("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),hs.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Kp({message:"Claude OAuth token"});Hp(i)&&(Gp("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),za({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${qn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Pe(t.profile);if(!e){Fp(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),hs.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Kp({message:"Claude OAuth token"});Hp(i)&&(Gp("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=U(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},X(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(hs.success("Claude OAuth token saved."),Zk("It will be sealed into job bundles when a SANDBOX (re)connects."))}K();be();st();Ao();Gt();_o();pe();te();import{cancel as tb,confirm as rb,intro as nb,isCancel as qp,log as he,outro as ob,select as Yp,text as jt}from"@clack/prompts";function Vp(t){tb(t),process.exit(1)}function _r(t){return qp(t)&&Vp("aborted"),t}function Sn(t){return qp(t)&&Vp("aborted"),typeof t=="string"?t:""}async function ib(t,e){let r=_r(await Yp({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=Sn(await jt({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Sn(await jt({message:"Context Repo name",placeholder:nt(t),initialValue:nt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Jp(t={profile:void 0}){let e=Pe(t.profile);nb(`codepipe project add \u2192 ${e.hubUrl}`);let r=_r(await jt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>Dt.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=_r(await jt({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=_r(await Yp({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=_r(await jt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=_r(await rb({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=Sn(await jt({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:$=>!$||!$.trim()||Ae($)?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=Ae(u);he.message(`${m.host}: ${m.owner}/${m.repoName}`);let p=Sn(await jt({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:$=>$.trim().length>0?void 0:"required"})).trim(),h=Sn(await jt({message:"default branch (optional)",placeholder:"main"})).trim(),y={name: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};i&&(c.youtrackProjectKey=i);let l=await ib(r,a),d=U(e.projectId);he.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Ir(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??tr(),youtrackWrites:s,trackerUrl:d?.youtrack?.url,log:{info:u=>he.message(u),warn:u=>he.warn(u)}})}catch(u){he.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=f,he.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await St(e.hubUrl,e.cliToken,c);he.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Bt(r,Xe(c,s,d?.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}`),ob("done")}catch(u){u instanceof N?(he.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&he.message(JSON.stringify(u.payload,null,2))):he.error(u instanceof Error?u.message:String(u)),process.exit(1)}}Sr();be();pe();te();ot();$n();import{existsSync as sb,rmSync as ab}from"node:fs";import{confirm as cb,intro as lb,isCancel as ub,log as At,outro as db,spinner as pb}from"@clack/prompts";function Ze(t){At.error(t),process.exit(1)}var zp=t=>t.trim().replace(/\/+$/,"");async function Xp(t){lb("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Ce()?.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=zp(r.hubUrl),o=r.projectId,i=zp(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 $=pb();$.start(`reading project ${o} from ${n}\u2026`);try{l=await V(n,r.cliToken,o),$.stop(`read project ${o} (${l.name})`)}catch(w){throw $.stop("could not read the source project",1),w instanceof N&&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=U(o),f=(t.account??r.accountEmail??await jr()).trim().toLowerCase();if(At.message(`move project '${o}'
|
|
752
|
+
`;return await ct(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:i.id}}async createIssue(e){let r=new Date().toISOString(),n=await Nc(this.contextDir,this.config.prefix,o=>this.renderNewIssueFiles(o,e,r),o=>`tracker(${o}): create issue`);return{id:n,key:n}}async editIssue(e,r){await this.mutateRecord(e,n=>({...n,...r.title!==void 0?{title:r.title}:{}}),r.body)}async applyLink(e,r,n){let o=r==="subtask_of"?"subtask":"depends_on";await this.mutateRecord(e,i=>{let s=i.links.filter(a=>!(a.type===o&&a.targetKey===n));return s.push({type:o,targetKey:n}),{...i,links:s}})}async fetchStateFields(e){return[{name:"Status",values:ii.statusColumns}]}async mutateRecord(e,r,n){let o=zr(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Xr(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Kr(e),content:Ci(i)},...po(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await ct(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Dn,status:r.targetStatus,links:[],created:n,updated:n},i=Xr(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Kr(e),content:Ci(o)},...po(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function zl(t,e){let r=ue(t,`tasks/${e}/comments.jsonl`);if(!Oh(r))return[];let n=[];for(let o of Dh(r,"utf-8").split(`
|
|
753
|
+
`)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}no();function Mi(t){if(!t)return"youtrack";try{let e=Zl(t,"project.yaml");return Xl(e)&&eu(Ql(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Ze(t){let e=Mi(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=jc(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Uh(n);return i?{ok:!0,kind:e,provider:new cn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=ml();return r?{ok:!0,kind:e,provider:new an(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Uh(t){try{let e=Zl(t,"project.yaml");if(!Xl(e))return null;let r=eu(Ql(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var mo=new Map;async function ln(t,e){let n=(mo.get(t)??Promise.resolve()).catch(()=>{}).then(e);mo.set(t,n);try{return await n}finally{mo.get(t)===n&&mo.delete(t)}}async function tu(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;Zr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await ar(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await Wc(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});return te({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await ar(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir);return await qc(s,a,{branchName:e.branchName,force:e.force}),te({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await ar(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await Yc(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return te({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return F("no repo spec");let i=Be(r),s=await i.createPullRequest(r,e);return te({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return F("no repo spec");let i=Be(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return te({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return F("no repo spec");let i=Be(r);return await i.closePR(r,e.prNumber,e.comment),te({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return ln(`${i}/${r.name}`,async()=>{let s=await ar(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{mergedSha:c}=await Vc(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return te({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return F("no repo spec");let i=t.cloneUrlOverride??tn(r),a=(await Jc(i)).filter(d=>zc(d,e.issueKey)),c=Be(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 te({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return F("no repo spec");let i=Be(r);return await i.addPRComment(r,e.prNumber,e.body),te({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=Ze({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),te({issueId:t.trackerIssueId,newStatus:e.newStatus})):F("no tracker_issue_id provided"):F(i.error)}case"tracker_comment":{let i=Ze({contextDir:t.contextDir});if(!i.ok)return F(i.error);if(!t.trackerIssueId)return F("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return te({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ze({contextDir:t.contextDir});if(!i.ok)return F(i.error);if(!e.projectKey)return F("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return te({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ze({contextDir:t.contextDir});if(!i.ok)return F(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 F(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return te({applied:s})}case"set_project_setting":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await Wl(t.contextDir,e.edits);return te({files:i.files})}case"tracker_edit":{let i=Ze({contextDir:t.contextDir});if(!i.ok)return F(i.error);if(!t.contextDir)return F("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 fo(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),te({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await Vl(t.contextDir,e);return te({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await Yl(t.contextDir,e);return te({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),te({reported:!0})):F("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return F("no context repo clone on this CLI");let i=await t.refreshContextStatus();return te({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return F("no project workspace on this CLI");if(!r)return F("no repo spec");if(!t.onRunActivity)return F("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Vn(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(p=>p.file===`actions/${e.actionId}.yml`);return F(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=na(c,e.input);if(!l.ok)return F(l.error);let d=dc(t.contextDir),f=L(e.projectId),u={};return f?.github?.token&&(u.GH_TOKEN=f.github.token),f?.gitlab?.token&&(u.GITLAB_TOKEN=f.gitlab.token),f?.bitbucket&&(u.BITBUCKET_EMAIL=f.bitbucket.email,u.BITBUCKET_API_TOKEN=f.bitbucket.apiToken),f?.youtrack&&(u.YOUTRACK_URL=f.youtrack.url,u.YOUTRACK_TOKEN=f.youtrack.token),ln(`${e.projectId}/${r.name}`,async()=>{await ar(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=ve(e.projectId,r.name,t.baseDir),p=await Gl({cwd:m,def:c,input:l.values,variables:d,secrets:f?.secrets??{},credEnv:u,onEvent:h=>i(e.runId,h)});return te({runId:e.runId,status:p.status,exitCode:p.exitCode,...p.failedStep?{failedStep:p.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=Kl(t.contextDir,e.path);return te({path:e.path,...i})}default:return F(`unsupported action type: ${e.type}`)}}catch(i){return F(i instanceof Error?i.message:String(i))}}function te(t){return{status:"done",result:t}}function F(t){return{status:"failed",error:t}}Ae();Fi();fe();ne();import{existsSync as wu,readFileSync as bu}from"node:fs";import{join as ku}from"node:path";async function $u(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=be(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");ho(e.farmId,e.farmPublicKey);let s=L(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await V(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=ku(r,"project.yaml"),m=ku(r,"regimen.yaml");wu(u)&&wu(m)?c={projectYaml:bu(u,"utf-8"),regimenYaml:bu(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}:{}},d=lt(e.farmPublicKey,JSON.stringify(l));go(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await wo(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(i){return o(i instanceof Error?i.message:String(i))}}Ae();Pe();Ae();import{homedir as zh}from"node:os";import{existsSync as Xh,mkdirSync as Qh,readFileSync as Zh,writeFileSync as ey}from"node:fs";import{dirname as ty,join as ry}from"node:path";function Wi(){return M("RUNNER_PINS")??ry(zh(),".codepipe","runner-pins.json")}function vu(){let t=Wi();if(!Xh(t))return{};try{return JSON.parse(Zh(t,"utf-8"))}catch{return{}}}function ny(t){let e=Wi();Qh(ty(e),{recursive:!0}),ey(e,JSON.stringify(t,null,2)+`
|
|
754
|
+
`,{mode:384})}function oy(t){return vu()[t]}function qi(t,e){let r=vu();r[t]=e,ny(r)}function xu(t,e){let r=be(e),n=oy(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 ${Wi()}.`);return r}fe();ne();var Ru=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Su(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Ru(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 iy={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Ru(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)=>Su(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Su(t,e,r,"remove-token")},Iu={api:iy,fetchProject:V,provisionOnRunner:ou,teardownOnRunner:iu};async function Tu(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)");xu(e.runnerId,e.runnerPublicKey);let i=L(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 Cu(t,e,r,n=Iu){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 Tu(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},d=lt(e.runnerPublicKey,JSON.stringify(l));qi(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(i){return o(i instanceof Error?i.message:String(i))}}async function Pu(t,e,r,n=Iu){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 Tu(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=lt(e.runnerPublicKey,JSON.stringify(c));qi(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(i){return o(i instanceof Error?i.message:String(i))}}fe();W();Ae();ne();var Eu=16*1024;function sy(t){return Ce.test(t)?ft(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ce}`}function ju(t,e,r,n){let o=sy(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(cr(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>Eu)return{ok:!1,detail:`secret value too large (max ${Eu} chars)`};try{return za(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Au(t,e){try{return Xa(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)}}}ao();ne();kt();var ko=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=Be(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 Bt){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=Be(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=ay(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function ay(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}W();var $o=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??(()=>Ze({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let v=e.stageField?{stageField:e.stageField}:{},x=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},P=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(P){let E=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[B,pe]=await Promise.all([E.length>0?r.listIssues({projectKey:e.projectKey,columns:E,...v,...x}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...v})]),we=new Map;for(let j of[...B,...pe])we.set(j.id,j);o=[...we.values()]}else{let E=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:E,...v,...x})}}catch(v){this.log.warn(`[yt-sync] listIssues failed: ${v instanceof Error?v.message:String(v)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let v of o){if(s.add(v.id),a.has(v.status))continue;let x=await Nu(r,v.id,e.sinceMs,this.log);x&&i.set(v.id,x)}let c=[];for(let v of e.offBoardIssueIds){if(s.has(v))continue;let x=await Nu(r,v,e.sinceMs,this.log);if(x&&x.length>0&&i.set(v,x),e.requireAssignee||x&&x.length>0){let U=await uy(r,v,e.stageField,this.log);if(U)c.push(U);else if(x&&x.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(v=>!a.has(v.status)),{attachmentsByIssue:d,attachmentKeys:f}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let u=[...l,...c].map(v=>({issue:v,comments:i.get(v.id)??[],attachments:d.get(v.id)??[]}));try{await fo(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let v of f)this.shippedAttachments.add(v)}catch(v){let x=v instanceof Error?v.message:String(v);this.abandonTick(`context task sync failed: ${x}`);return}let m=this.options.isSelfComment??(()=>!1),p=[],h=[];for(let[v,x]of i){let U=x.filter(E=>!m(E.id));if(U.length===0)continue;p.push({issueId:v,comments:U.map(cy)});let P=U.flatMap(E=>{let B=Jt(E.body);return B?[{commentId:E.id,author:E.author,name:B.name,args:B.args,createdAt:E.createdAt}]:[]});P.length>0&&h.push({issueId:v,commands:P})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(_u),commentsBatch:p,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(_u)}:{},observedAtMs:n};this.send(y);let $=p.reduce((v,x)=>v+x.comments.length,0),w=h.reduce((v,x)=>v+x.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${$} commands=${w} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let d of r.get(s.id)??[])a.push(...d.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let d of a){let f=`${s.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} (${s.id}) download failed: ${p instanceof Error?p.message:String(p)}`);continue}let m=ly(d.name);l.has(m)&&(m=`${d.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 _u(t){let{description:e,...r}=t;return r}function cy(t){let{body:e,...r}=t;return r}function ly(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 uy(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 Nu(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 Yi="npm i -g @code-partner/codepipe@latest";function vo(t,e={}){let r=e.log??{info:p=>console.log(p),warn:p=>console.warn(p)};r.info(`codepipe-cli v${Te} (protocol ${qe})`);let n=p=>e.onEvent?.(p),o=e.workspace;o?.contextDir&&mc(o.contextDir,r);let i=Ou("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Ou("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=yo(t.hubUrl,t.cliToken),h=null,y=new ko(i,g=>{p.readyState===p.OPEN&&p.send(JSON.stringify(g))},r),$=new $o(s,g=>{p.readyState===p.OPEN&&p.send(JSON.stringify(g))},r,{contextDir:o?.contextDir??null,isSelfComment:g=>f.has(g)}),w=null,v=async()=>{try{let g={trackerProvider:Mi(o?.contextDir??null)};try{let R=await V(t.hubUrl,t.cliToken,t.projectId);g={...g,repos:R.repos,contextRepo:R.contextRepo}}catch(R){r.warn(`[readiness] could not fetch project summary for push checks: ${R instanceof Error?R.message:String(R)}`)}let C=await Al(t.projectId,g);if(p.readyState!==p.OPEN)return;let b={type:"cli_readiness",projectId:t.projectId,ready:C.ready,checks:C.checks,creds:C.creds,secretNames:Qa(t.projectId),checkedAt:C.checkedAt};if(p.send(JSON.stringify(b)),C.ready)r.info("[readiness] ready");else{let R=C.checks.filter(A=>!A.ok).map(A=>`${A.name}(${A.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${R.join(", ")}`)}}catch(g){r.warn(`[readiness] check failed: ${g instanceof Error?g.message:String(g)}`)}},x=()=>{v(),w=setInterval(()=>void v(),a),typeof w.unref=="function"&&w.unref()},U=()=>{w&&(clearInterval(w),w=null)},P=150,E=new Map,B=g=>{let C=E.get(g);if(!C||(C.timer&&clearTimeout(C.timer),E.delete(g),C.events.length===0||p.readyState!==p.OPEN))return;let b={type:"run_activity",projectId:t.projectId,runId:g,events:C.events};p.send(JSON.stringify(b))},pe=(g,C)=>{let b=E.get(g);if(b||(b={events:[],timer:null},E.set(g,b)),b.events.push(C),C.kind==="result"){B(g);return}b.timer||(b.timer=setTimeout(()=>B(g),P),b.timer.unref?.())},we=o?.contextDir?new Jn(o.contextDir,t.projectId,g=>{p.readyState===p.OPEN&&p.send(JSON.stringify(g))},r):null,j=async()=>{let g=o?.contextDir;if(!g)throw new Error("no context repo clone on this CLI");let C;try{C=(await V(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let b=await Bc(g,t.projectId,C,r);return p.readyState===p.OPEN&&p.send(JSON.stringify(b)),b};return p.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let g=sc(t.projectId),C=M("ORIGIN")==="farm"?"farm":"local",b=M("FARM_ID"),R=t.accountEmail??g.email,A;try{let I=Ll(t.projectId);I&&(A=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let k={type:"register",projectId:t.projectId,platformVersion:Te,protocolVersion:qe,accountId:g.accountId,accountLabel:g.label,origin:C,inFlightActionIds:[...d],...R?{accountEmail:R}:{},...C==="farm"&&b?{farmId:b}:{},...A?{sealPublicKey:A}:{}};p.send(JSON.stringify(k))}),p.on("message",async g=>{let C=g.toString("utf-8");if(C==="pong"||C==="ping")return;let b;try{b=JSON.parse(C)}catch{return}if(!b||typeof b!="object")return;let R=b.type;if(R==="registered"){let k=b;if(k.ok){if(r.info(`[ws] registered for project ${k.projectId}`),n({kind:"registered",projectId:k.projectId??t.projectId}),y.start(),we?.start(),x(),Vi(t,o,r),o?.contextDir)try{let I=eo(o.contextDir,t.projectId);p.readyState===p.OPEN&&p.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),l||(l=!0,j().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}}else r.warn(`[ws] register rejected: ${k.reason??"unknown"}`),n({kind:"register_rejected",reason:k.reason??"unknown"}),c=!0,p.close();return}if(R==="hello"){let k=b;h=_n(k.protocolVersion);let I=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${k.platformVersion} (protocol ${k.protocolVersion}) \u2014 ${I}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Te}, protocol ${qe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Yi}`),n({kind:"incompatible",hubVersion:typeof k.platformVersion=="string"?k.platformVersion:null,hubProtocol:typeof k.protocolVersion=="number"?k.protocolVersion:null,updateCommand:Yi}));return}if(R==="tracking_targets"){y.setTargets(b.targets);return}if(R==="youtrack_sync_request"){$.setRequest(b);return}if(R==="youtrack_force_sync"){$.forceSync();return}if(R==="sync_local"){await gy(b,o,p,r);return}if(R==="provision_repo"){let k=b;r.info(`[repo] provision_repo: ${k.repo.name} (${k.repo.host}:${k.repo.owner}/${k.repo.repoName})`),await fy(t,o,k.repo,r),await Vi(t,o,r);return}if(R==="remove_repo"){let k=b;r.info(`[repo] remove_repo: ${k.repoName}${k.purge?" (purge)":""}`),await Vi(t,o,r),k.purge&&my(t,o,k.repoName,r);return}if(R==="context_write"){await hy(b,o,p,r);return}if(R==="adr_promote"){await yy(b,o,p,r);return}if(R==="cred_update"){let k=b,I=L(t.projectId),K=I?.sealKey?await Ul(t.projectId,k.kind,k.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},G={type:"cred_update_result",updateId:k.updateId,projectId:t.projectId,ok:K.ok,...K.detail?{detail:K.detail}:{}};p.readyState===p.OPEN&&p.send(JSON.stringify(G)),K.ok?(r.info(`[cred] ${k.kind} replaced${K.detail?` \u2014 ${K.detail}`:""}`),v()):r.warn(`[cred] ${k.kind} replacement rejected: ${K.detail??"unknown"}`);return}if(R==="move_to_farm"){let k=b;r.info(`[farm-move] request to move ${t.projectId} onto farm ${k.farmName} (${k.farmId})`);let I=await $u(t,k,o?.contextDir,r);p.readyState===p.OPEN&&p.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if(R==="gh_runner_setup"){let k=b;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${k.runnerName} (${k.runnerId})`);let I=await Cu(t,k,r);p.readyState===p.OPEN&&p.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${k.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if(R==="gh_runner_teardown"){let k=b;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${k.runnerName} (${k.runnerId})`);let I=await Pu(t,k,r);p.readyState===p.OPEN&&p.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${k.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if(R==="tracker_fields_request"){let k=b,I={type:"tracker_fields_result",requestId:k.requestId,projectId:t.projectId,ok:!1},K=Ze({contextDir:o?.contextDir??null});if(!K.ok)I.error=K.error;else try{I.fields=await K.provider.fetchStateFields(k.projectKey),I.ok=!0}catch(G){I.error=G instanceof Error?G.message:String(G)}p.readyState===p.OPEN&&p.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(R==="project_secret_update"||R==="project_secret_delete"){let k=b,I;if(k.type==="project_secret_update"){let G=L(t.projectId);I=G?.sealKey?ju(t.projectId,k.name,k.sealed,G.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else I=Au(t.projectId,k.name);let K={type:"project_secret_update_result",updateId:k.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};p.readyState===p.OPEN&&p.send(JSON.stringify(K)),I.ok?(r.info(`[secret] ${k.name} ${k.type==="project_secret_update"?"saved":"deleted"}`+(I.detail?` \u2014 ${I.detail}`:"")),v()):r.warn(`[secret] ${k.name} rejected: ${I.detail??"unknown"}`);return}if(R==="sandbox_keys"){let k=L(t.projectId);if(!k){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=Zt(t.projectId),K=tl(b,k,I,r);for(let G of K)p.readyState===p.OPEN&&p.send(JSON.stringify(G));return}if(R!=="dispatch_action")return;let A=b;if(h===!1){let k=`refused: HUB protocol incompatible with CLI v${Te} (protocol ${qe})`;p.send(JSON.stringify({type:"action_result",actionId:A.actionId,status:"failed",error:k})),r.warn(`[exec] ${A.actionId} (${A.action.type}) \u2192 REFUSED: ${k}`),r.warn(`[exec] update the CLI to clear this: ${Yi}`),n({kind:"action",actionId:A.actionId,actionType:A.action.type,ok:!1,error:k});return}d.add(A.actionId);try{let k=await tu({action:A.action,repo:A.repo,trackerIssueId:A.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:we?()=>we.reportNow():void 0,refreshContextStatus:o?.contextDir?j:void 0,onRunActivity:pe}).catch(G=>({status:"failed",error:G instanceof Error?G.message:String(G)}));A.action.type==="tracker_comment"&&k.status==="done"&&"result"in k&&typeof k.result?.commentId=="string"&&f.add(k.result.commentId),p.send(JSON.stringify({type:"action_result",actionId:A.actionId,...k}));let I=k.status!=="failed",K=!I&&"error"in k?k.error:void 0;I?r.info(`[exec] ${A.actionId} (${A.action.type}) \u2192 done`):r.warn(`[exec] ${A.actionId} (${A.action.type}) \u2192 FAILED: ${K??"?"}`),n({kind:"action",actionId:A.actionId,actionType:A.action.type,ok:I,...K?{error:K}:{}})}finally{d.delete(A.actionId)}}),p.on("close",(g,C)=>{let b=C?.toString("utf-8")??"";if(r.info(`[ws] closed code=${g}${b?` reason=${b}`:""}`),y.stop(),$.stop(),we?.stop(),U(),b==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:g}),!c&&setTimeout(()=>{u=m()},2e3)}),p.on("error",g=>r.warn(`[ws] error: ${g.message}`)),p}return{stop(){c=!0,u.close()}}}async function Vi(t,e,r){try{let n=await V(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Qr(t.projectId,n.repos,e?.contextDir);for(let s of o)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function fy(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?pn(e.root,o):ve(t.projectId,r.name);if(Du(pn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await py().clone(tn(r),i),n.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function my(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?pn(e.root,o):ve(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Du(pn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{dy(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 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 i=e.repos.find(l=>l.name===o.repoName),s=pn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await ac(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 hy(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 ct(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 yy(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 $c(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 Ou(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}fe();ne();at();zi();it();co();async function Vu(t={profile:void 0}){let{cfg:e,profile:r}=Hn(t.profile),n=L(e.projectId);n&&qr(n),nn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),on(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),sn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=fn(Xi(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=qn("CLI_LOG",i,o);if(s.enabled){let u=new tr(s);Yn(u),console.log(`[log] file logging \u2192 ${u.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=Gn(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let u=fn(Xi(),".codepipe",r?fn("profiles",r,"context"):"context");if(await Ki(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await qu(()=>So({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 Ki(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let m=fn(Xi(),".codepipe",r?fn("profiles",r,"context-config"):"context-config");zn(a.contextDir,m,{info:p=>console.log(p),warn:p=>console.warn(p)})}}let l=vo(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(`
|
|
755
|
+
[${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}xr();$e();fe();async function rp(t={profile:void 0}){let e=je(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=yo(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 d=l.toString("utf-8");if(s.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=>s.push(`error:${l.message}`)),r.on("close",(l,d)=>{s.push(`close:${l}:${d?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await V(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ge(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}$n();import{readFileSync as tk}from"node:fs";W();$e();at();Ao();Mt();kt();Gt();fe();ne();function oe(t){throw new Error(t)}function de(t,e){return(typeof t!="string"||t.trim().length===0)&&oe(`config: '${e}' must be a non-empty string`),t.trim()}function xn(t,e){if(t==null)return;typeof t!="string"&&oe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function rk(t){(!t||typeof t!="object")&&oe("config: expected a JSON object");let e=t,r=de(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||oe("config: 'hubUrl' must start with http(s)://");let n=de(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&oe("config: 'project' is required");let i=o,s=de(i.id,"project.id");Ot.test(s)||oe("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"&&oe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||oe("config: 'project.repos' must be an array");let d=l.map((w,v)=>{(!w||typeof w!="object")&&oe(`config: project.repos[${v}] must be an object`);let x=w,U=de(x.host,`project.repos[${v}].host`);U!=="github"&&U!=="bitbucket"&&U!=="gitlab"&&oe(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let P={name:de(x.name,`project.repos[${v}].name`),host:U,owner:de(x.owner,`project.repos[${v}].owner`),repoName:de(x.repoName,`project.repos[${v}].repoName`)},E=xn(x.defaultBranch,`project.repos[${v}].defaultBranch`);E&&(P.defaultBranch=E);let B=xn(x.mountAs,`project.repos[${v}].mountAs`);return B&&(P.mountAs=B),P}),f=i.contextRepo;(!f||typeof f!="object")&&oe("config: 'project.contextRepo' is required");let u=f,m=xn(u.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&oe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let p={host:m,owner:de(u.owner,"project.contextRepo.owner"),name:xn(u.name,"project.contextRepo.name")??ot(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:d,contextRepo:p}},y=xn(i.youtrackProjectKey,"project.youtrackProjectKey");if(y&&(h.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&oe("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&oe("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let w=de(i.llmProvider,"project.llmProvider");w==="codex"&&oe(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),w!=="claude"&&oe("config: 'project.llmProvider' must be 'claude'"),h.project.llmProvider=w}let $=e.secrets;if($!==void 0){(typeof $!="object"||$===null)&&oe("config: 'secrets' must be an object");let w=$,v={};if(w.github){let x=w.github;v.github={token:de(x.token,"secrets.github.token")}}if(w.bitbucket){let x=w.bitbucket;v.bitbucket={email:de(x.email,"secrets.bitbucket.email"),apiToken:de(x.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let x=w.gitlab;v.gitlab={token:de(x.token,"secrets.gitlab.token")}}if(w.youtrack){let x=w.youtrack;v.youtrack={url:de(x.url,"secrets.youtrack.url").replace(/\/$/,""),token:de(x.token,"secrets.youtrack.token")}}if(w.contextWrite){let x=w.contextWrite;v.contextWrite={token:de(x.token,"secrets.contextWrite.token")}}h.secrets=v}return h}async function nk(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function ok(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await yt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await wt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await ro(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(i)throw new Error(`Bitbucket: ${i}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await bt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await xt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Wp(t){let e=!t.configPath||t.configPath==="-"?await nk():tk(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){oe(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=rk(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 ok(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 Rr(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??er(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){oe(`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 St(o,i,a)}catch(u){if(u instanceof N&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),d=await V(o,i,s.id);else if(u instanceof N)oe(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${d.projectId} ready (${d.provisioningStatus})`);let f={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(Q(f),st({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${ze(s.id)}`),Ut(s.id,Qe(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??Ve),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await dn(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`)}$e();ne();import{cancel as qp,intro as Yp,isCancel as Vp,log as ws,outro as ik,password as Jp}from"@clack/prompts";async function sk(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function zp(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await sk(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Yp("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),ws.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Jp({message:"Claude OAuth token"});Vp(i)&&(qp("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),ec({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Wn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=je(t.profile);if(!e){Yp(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),ws.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Jp({message:"Claude OAuth token"});Vp(i)&&(qp("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=L(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}.`):(ws.success("Claude OAuth token saved."),ik("It will be sealed into job bundles when a SANDBOX (re)connects."))}W();$e();at();Ao();Mt();_o();fe();ne();import{cancel as ak,confirm as ck,intro as lk,isCancel as Xp,log as ye,outro as uk,select as Qp,text as jt}from"@clack/prompts";function Zp(t){ak(t),process.exit(1)}function Ar(t){return Xp(t)&&Zp("aborted"),t}function Sn(t){return Xp(t)&&Zp("aborted"),typeof t=="string"?t:""}async function dk(t,e){let r=Ar(await Qp({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=Sn(await jt({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Sn(await jt({message:"Context Repo name",placeholder:ot(t),initialValue:ot(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function ef(t={profile:void 0}){let e=je(t.profile);lk(`codepipe project add \u2192 ${e.hubUrl}`);let r=Ar(await jt({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=Ar(await jt({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=Ar(await Qp({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=Ar(await jt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Ar(await ck({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=Sn(await jt({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:$=>!$||!$.trim()||Ne($)?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=Ne(u);ye.message(`${m.host}: ${m.owner}/${m.repoName}`);let p=Sn(await jt({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:$=>$.trim().length>0?void 0:"required"})).trim(),h=Sn(await jt({message:"default branch (optional)",placeholder:"main"})).trim(),y={name: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};i&&(c.youtrackProjectKey=i);let l=await dk(r,a),d=L(e.projectId);ye.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Rr(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??er(),youtrackWrites:s,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 St(e.hubUrl,e.cliToken,c);ye.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Ut(r,Qe(c,s,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 N?(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)}}xr();$e();fe();ne();it();$n();import{existsSync as pk,rmSync as fk}from"node:fs";import{confirm as mk,intro as gk,isCancel as hk,log as At,outro as yk,spinner as wk}from"@clack/prompts";function et(t){At.error(t),process.exit(1)}var tf=t=>t.trim().replace(/\/+$/,"");async function rf(t){gk("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Ee()?.spec.projectId??void 0;e||et("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Ue(e);r||et(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=tf(r.hubUrl),o=r.projectId,i=tf(t.hub);i.startsWith("http")||et("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&et(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let $=wk();$.start(`reading project ${o} from ${n}\u2026`);try{l=await V(n,r.cliToken,o),$.stop(`read project ${o} (${l.name})`)}catch(w){throw $.stop("could not read the source project",1),w instanceof N&&et(`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||et(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let d=L(o),f=(t.account??r.accountEmail??await Er()).trim().toLowerCase();if(At.message(`move project '${o}'
|
|
751
756
|
from : ${n} (profile ${e})
|
|
752
757
|
to : ${i} (profile ${s}, project ${a}, account ${f})
|
|
753
758
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
754
759
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
755
|
-
`+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let $=await
|
|
756
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await
|
|
757
|
-
`)}async function
|
|
760
|
+
`+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let $=await mk({message:"Continue?",initialValue:!0});(hk($)||!$)&&et("aborted")}!c&&a===o&&At.warn(`source and destination share the same project id, so they share one secrets file (${ze(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 jr(i,f),p={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};At.step(`registering project on ${i}\u2026`);let h;try{h=await St(i,u,p)}catch($){if($ instanceof N&&$.status===409){At.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await V(i,u,a)}catch(w){throw w instanceof N&&et(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if($ instanceof N&&$.status===403)et(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if($ instanceof N)et(`target HUB \u2192 ${$.status} ${$.message}`);else throw $}At.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),st({hubUrl:i,cliToken:u,projectId:a,accountEmail:m},s);let y={...d??{},hubUrl:i,cliToken:u,projectId:a};if(delete y.sandboxPins,Q(y),At.success(`profile '${s}' \u2192 ${ze(a)}`),c){let $=Fe(s);pk($)&&(fk($),At.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}yk(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}$e();import{existsSync as bs,rmSync as bk,statSync as kk}from"node:fs";import{join as Mo,relative as $k,resolve as vk}from"node:path";import{cancel as xk,intro as of,isCancel as Sk,log as se,outro as sf,text as Wt}from"@clack/prompts";import{simpleGit as af}from"simple-git";_o();fe();ne();it();function xe(t){xk(t),process.exit(1)}function qt(t){return Sk(t)&&xe("aborted"),typeof t=="string"?t:""}async function nf(t){try{let e=await af(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function Rk(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function Ik(t,e){let r=L(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(Rk(r,e)){se.message(`reusing existing ${e} credentials`);return}if(se.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=qt(await Wt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=qt(await Wt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=qt(await Wt({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),se.success(`saved ${e} credentials`)}async function cf(t){let e=je(t.profile);of(`codepipe repo add \u2192 project ${e.projectId}`);let r=Ee()??void 0,n;try{n=(await V(e.hubUrl,e.cliToken,e.projectId)).repos}catch(w){xe(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await nf(process.cwd());w?(o=process.cwd(),se.message(`using the current directory (${w})`)):o=qt(await Wt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:v=>v.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(bs(o)&&kk(o).isDirectory()){i=vk(o);let w=await nf(i);w||xe(`${i} is not a git repository (no origin remote)`);let v=Ne(w);v||xe(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=v,s=w,se.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let w=Ne(o);w||xe(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,s=o,se.message(`${a}: ${c}/${l}`)}let d=qt(await Wt({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=qt(await Wt({message:"default branch (optional)",placeholder:"main"})).trim(),u=d;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let w=$k(r.root,i);u=w===""?".":w}let m=qt(await Wt({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 Ik(e,a);let p={name:d,host:a,owner:c,repoName:l,mountAs:m,...f?{defaultBranch:f}:{}};if(!i){let w=r?Mo(r.root,m):ve(e.projectId,d);if(bs(Mo(w,".git")))se.message(`already cloned at ${w}`);else{se.info(`cloning ${s} \u2192 ${w} \u2026`);try{await af().clone(s,w),se.success(`cloned into ${w}`)}catch(v){xe(`clone failed: ${v instanceof Error?v.message.trim():String(v)}
|
|
761
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await hu(e.hubUrl,e.cliToken,e.projectId,p)}catch(w){w instanceof N&&xe(`HUB \u2192 ${w.status} ${w.message}`),xe(w instanceof Error?w.message:String(w))}let{updated:y,errors:$}=Qr(e.projectId,h.repos,r?.contextDir);for(let w of y)se.message(`updated ${w}`);for(let w of $)se.warn(`could not update ${w.path}: ${w.error}`);se.success(`added "${d}" \u2014 project now has ${h.repos.length} repo(s)`),sf("done")}async function lf(t){let e=je(t.profile);of(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Ee()??void 0,n;try{let c=(await V(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await yu(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof N&&(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:i,errors:s}=Qr(e.projectId,o.repos,r?.contextDir);for(let a of i)se.message(`updated ${a}`);for(let a of s)se.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")se.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Mo(r.root,n):ve(e.projectId,t.name);if(bs(Mo(a,".git")))try{bk(a,{recursive:!0,force:!0}),se.message(`deleted local clone ${a}`)}catch(c){se.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else se.message(`no local clone found to purge (${a})`)}se.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),sf("done")}async function uf(t){let e=je(t.profile),r;try{r=(await V(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}Oo();ps();import{existsSync as vf,mkdirSync as jk,readFileSync as Ak,writeFileSync as _k}from"node:fs";import{homedir as Nk}from"node:os";import{dirname as Ok,join as xf}from"node:path";import*as Nr from"node:readline";fe();ne();it();Oo();fe();import{existsSync as vs,readFileSync as Tk,writeFileSync as Ck}from"node:fs";import{join as In}from"node:path";import{simpleGit as $s}from"simple-git";var df=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Pk="apply-queue.json";function pf(t){return In(t,Pk)}function _r(t){let e=pf(t);if(!vs(e))return{};try{return JSON.parse(Tk(e,"utf-8"))}catch{return{}}}function ff(t,e){Ck(pf(t),JSON.stringify(e,null,2)+`
|
|
762
|
+
`)}async function mf(t,e,r,n,o){let i;try{i=await pu(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(u){return{ok:!1,message:`claim failed: ${u instanceof Error?u.message:String(u)}`}}let s=[];for(let u of i.repos){let m=t.spec.repos.find($=>$.name===u.repoName);if(!m)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let p=In(t.root,m.mountAs);if(!vs(In(p,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await $s(p).status()).isClean())return{ok:!1,message:`${m.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:u,spec:m,dir:p})}let a=[];for(let u of s){let m=$s(u.dir),p=await Ek(m),h=u.claimRepo;try{await m.fetch()}catch(w){return await ks(a,o),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${Rn(w)}`}}let y=`origin/${h.baseRef}`,$;try{$=await io(m,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(w){return await ks(a,o),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${Rn(w)}`}}a.push({git:m,dir:u.dir,mountAs:u.spec.mountAs,originalRef:p,branch:h.branchName,baseSha:y,deliveryCommit:$,startPoint:y})}let c=[];for(let u of a)try{if(n==="apply"){await u.git.checkout(["-B",u.branch,u.startPoint]),await u.git.raw([...df,"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([...df,"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 ks(a,o),{ok:!1,message:`apply failed in ${u.mountAs}: ${Rn(m)} (rolled back all repos)`}}let l=_r(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},ff(t.contextDir,l);let d=c.map(u=>u.mountAs).join(", "),f=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${d}
|
|
758
763
|
${f}
|
|
759
|
-
or: /abort ${r} --reason "..."`}}function
|
|
764
|
+
or: /abort ${r} --reason "..."`}}function xs(t,e){let r=_r(t);r[e]&&(delete r[e],ff(t,r))}async function ks(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${Rn(n)} \u2014 check manually`)}}async function gf(t,e,r){let o=_r(t.contextDir)[e];if(o){for(let i of o.repos){let s=In(t.root,i.mountAs);if(!vs(In(s,".git")))continue;let a=$s(s),c=t.spec.repos.find(d=>d.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(d){r.warn(`rollback failed in ${i.mountAs}: ${Rn(d)} \u2014 check manually`)}}xs(t.contextDir,e)}}async function Ek(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Rn(t){return t instanceof Error?t.message.trim():String(t)}var Go=xf(Nk(),".codepipe","history"),hf=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Sf=500,yf=40;async function Rf(){let t=Ee();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=L(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),qr(e),console.log(`connected to ${e.hubUrl} as project ${t.spec.projectId}`),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let r=_r(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
|
|
760
765
|
\u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
|
|
761
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=
|
|
762
|
-
`))}async function
|
|
763
|
-
`)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}
|
|
764
|
-
`),t.unread+=1,
|
|
765
|
-
bye.`),setTimeout(()=>process.exit(0),150))}function
|
|
766
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=Nr.createInterface({input:process.stdin,output:process.stdout,completer:Dk,history:r$(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};Fc(s=>Yt(i,s)),i.daemon=vo({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>Yt(i,s),warn:s=>Yt(i,s)},onEvent:s=>zk(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Rs(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await Lk(i,a)){$f(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Rs(i),o.prompt()}),o.on("close",()=>{$f(i)})}function Dk(t){let e=hf.filter(r=>r.startsWith(t));return[e.length?e:hf,t]}async function Lk(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return Uk(),!1;case"/status":return await Bk(t),!1;case"/tasks":return await Mk(t,n),!1;case"/task":return await Gk(t,n),!1;case"/sync":return await Fk(t),!1;case"/logs":return Xk(t,n),!1;case"/monitor":return Qk(t),!1;case"/apply":return await wf(t,n,"apply"),!1;case"/unstash":return await wf(t,n,"unstash"),!1;case"/applied":return await Hk(t,n),!1;case"/abort":return await Kk(t,n),!1;case"/approve":return await bf(t,n,"approve"),!1;case"/merge":return await bf(t,n,"merge"),!1;case"/login":return qk(t,n),!1;case"/secret":return Yk(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Uk(){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(`
|
|
767
|
+
`))}async function Bk(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=vf(xf(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function Mk(t,e){let r=Zk(e,"--phase");try{let n=await uu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){Cn(n)}}async function Gk(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await du(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${n.task.phase} \u2014 ${n.task.title}`),n.artifacts.length>0){console.log(" artifacts:");for(let o of n.artifacts)console.log(` ${o.path}`)}}catch(n){Cn(n)}}async function Fk(t){let e=await kn(t.ws.root,t.ws.spec.repos);for(let r of e)console.log(` ${r.mountAs}: ${r.status}${r.detail?` \u2014 ${r.detail}`:""}`)}async function wf(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await mf(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function Hk(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=_r(t.ws.contextDir)[r],i=e$(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),d,f;if(l>0?(d=c.slice(0,l),f=c.slice(l+1)):(f=c,d=o?.repos.length===1?Wk(t,o.repos[0].mountAs):s.length===1?s[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 fu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);xs(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Cn(c)}}async function bf(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await gu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Cn(o)}}async function Kk(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=t$(e,"--reason")||"local apply aborted";await gf(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await mu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Cn(o)}}function Wk(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function qk(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 Yk(t,e){let[r,n,...o]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
|
|
768
|
+
`)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}Vk(t.secrets,n,i),Q(t.secrets),qr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}Jk(t.secrets,n),Q(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function Vk(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 Jk(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 zk(t,e){switch(e.kind){case"connected":t.connection="connecting",Yt(t,"[hub] connected");break;case"registered":t.connection="registered",Yt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Tn(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Yt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Tn(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Tn(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?Yt(t,`[hub] action ${e.actionType} done`):Tn(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Yt(t,e){t.logBuffer.push(e),t.logBuffer.length>Sf&&t.logBuffer.shift(),t.follow&&Tn(t,e)}function Xk(t,e){let r=e[0];if(r==="follow"||r==="on"){Ss(t,!0);return}if(r==="off"){Ss(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Sf,Number(r)||yf)):yf,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of o)console.log(` ${i}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function Qk(t){Ss(t,!t.follow)}function Ss(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Tn(t,e){Nr.cursorTo(process.stdout,0),Nr.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
769
|
+
`),t.unread+=1,Rs(t),t.rl.prompt(!0)}function Rs(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var kf=!1;function $f(t){kf||(kf=!0,n$(t.rl),t.daemon.stop(),console.log(`
|
|
770
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function Zk(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function e$(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 t$(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Cn(t){t instanceof N?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function r$(){if(!vf(Go))return[];try{return Ak(Go,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function n$(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{jk(Ok(Go),{recursive:!0}),_k(Go,r.slice().reverse().join(`
|
|
766
771
|
`)+`
|
|
767
|
-
`)}catch{}}Sr();K();Te();Sr();be();pe();$n();import{hostname as Qb}from"node:os";import{cancel as Zb,confirm as $f,intro as e$,isCancel as Sf,log as Dr,multiselect as t$,outro as vf,password as r$,select as Ss,text as Rs}from"@clack/prompts";function Pn(t){Zb(t),process.exit(1)}function Lr(t){return Sf(t)&&Pn("aborted"),t}function Fo(t){return Sf(t)&&Pn("aborted"),typeof t=="string"?t:""}function Is(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function xf(t,e){try{let{secret:r}=await ko(t,e);return r}catch(r){throw r instanceof N&&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 n$(t,e){if(Lr(await Ss({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let o=await Gi(t,e);if(o.length>0)return Lr(await t$({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));Dr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Dr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Fo(await Rs({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:o=>o.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function Ts(t){e$("codepipe worker \u2014 set up this machine as a runner");let e=me(t.profile);e&&(Dr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Lr(await $f({message:"re-register this worker?",initialValue:!1}))||Pn("keeping the existing registration"));let r=De(t.profile)??De(),n=Fo(await Rs({message:"HUB URL",placeholder:He,initialValue:G("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,i=Lr(await Ss({message:"how to authorize the registration?",options:[...o?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await xf(n,a),Dr.success("account-issued registration token minted");else if(i==="login"){let u=await jr();a=(await Ar(n,u)).cliToken,s=await xf(n,a),Dr.success("account-issued registration token minted")}else s=Fo(await r$({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Pn("a registration token is required");let c=await n$(n,a),l=Fo(await Rs({message:"worker name",initialValue:Qb(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),d=Lr(await Ss({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await Ht({hub:n,token:s,name:l,projects:c,...d?{llm:d}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Dr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Lr(await $f({message:"start the claim-loop now?",initialValue:!0}))){vf("registered. start later with `codepipe worker`.");return}vf("starting the claim-loop\u2026"),await wn(t.profile?{profile:t.profile}:{})}function i$(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return G("PROFILE")}var ie=i$();Oa(ie);Ua();var xe=new o$;xe.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 bf()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});xe.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Mp({configPath:t.config,skipVerify:t.skipVerify===!0}):await Pp({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});xe.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Xa({...t,profile:ie})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});xe.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await Ep({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});xe.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Hu({profile:ie})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});xe.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await bp({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});xe.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Wp({profile:ie,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});xe.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Xd({profile:ie})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});xe.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await ls({profile:ie,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Rf=xe.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Rf.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??G("HUB_URL")??De(ie)?.hubUrl??He,r=t.token??G("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Is()){await Ts({profile:ie});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=G("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??G("WORKER_NAME"),i=t.llm??G("WORKER_LLM");await Ht({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ie?{profile:ie}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Rf.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!me(ie)&&Is()){await Ts({profile:ie});return}await wn(ie?{profile:ie}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var If=xe.command("project").description("Manage CodePipe projects");If.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Jp({profile:ie})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});If.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 Xp({...t,cliProfile:ie})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Cs=xe.command("repo").description("Manage the project's git repositories");Cs.command("add").description("Add a repo to this project (a path to an existing clone, or a clone URL)").argument("[target]","Path to an already-cloned repo, or a repo clone URL").action(async t=>{try{await rf({profile:ie,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Cs.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await nf({profile:ie,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Cs.command("list").description("List the project's repos").action(async()=>{try{await of({profile:ie})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});xe.parseAsync();
|
|
772
|
+
`)}catch{}}xr();W();Pe();xr();$e();fe();$n();import{hostname as o$}from"node:os";import{cancel as i$,confirm as If,intro as s$,isCancel as Pf,log as Or,multiselect as a$,outro as Tf,password as c$,select as Is,text as Ts}from"@clack/prompts";function Pn(t){i$(t),process.exit(1)}function Dr(t){return Pf(t)&&Pn("aborted"),t}function Fo(t){return Pf(t)&&Pn("aborted"),typeof t=="string"?t:""}function Cs(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Cf(t,e){try{let{secret:r}=await bo(t,e);return r}catch(r){throw r instanceof N&&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(Dr(await Is({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 Hi(t,e);if(o.length>0)return Dr(await a$({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}));Or.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Or.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Fo(await Ts({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 Ps(t){s$("codepipe worker \u2014 set up this machine as a runner");let e=ge(t.profile);e&&(Or.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Dr(await If({message:"re-register this worker?",initialValue:!1}))||Pn("keeping the existing registration"));let r=Ue(t.profile)??Ue(),n=Fo(await Ts({message:"HUB URL",placeholder:We,initialValue:M("HUB_URL")??r?.hubUrl??We,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Dr(await Is({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 Cf(n,a),Or.success("account-issued registration token minted");else if(i==="login"){let u=await Er();a=(await jr(n,u)).cliToken,s=await Cf(n,a),Or.success("account-issued registration token minted")}else s=Fo(await c$({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Pn("a registration token is required");let c=await l$(n,a),l=Fo(await Ts({message:"worker name",initialValue:o$(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),d=Dr(await Is({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 Ft({hub:n,token:s,name:l,projects:c,...d?{llm:d}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Or.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Dr(await If({message:"start the claim-loop now?",initialValue:!0}))){Tf("registered. start later with `codepipe worker`.");return}Tf("starting the claim-loop\u2026"),await wn(t.profile?{profile:t.profile}:{})}function d$(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return M("PROFILE")}var ae=d$();Ba(ae);Fa();var Se=new u$;Se.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Te).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await Rf()}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 Wp({configPath:t.config,skipVerify:t.skipVerify===!0}):await Np({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 tc({...t,profile:ae})}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 Op({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 Vu({profile:ae})}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 Rp({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 zp({profile:ae,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 rp({profile:ae})}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 ds({profile:ae,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Ef=Se.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Ef.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??M("HUB_URL")??Ue(ae)?.hubUrl??We,r=t.token??M("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Cs()){await Ps({profile:ae});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=M("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??M("WORKER_NAME"),i=t.llm??M("WORKER_LLM");await Ft({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ae?{profile:ae}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ef.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ge(ae)&&Cs()){await Ps({profile:ae});return}await wn(ae?{profile:ae}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var jf=Se.command("project").description("Manage CodePipe projects");jf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await ef({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});jf.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 rf({...t,cliProfile:ae})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Es=Se.command("repo").description("Manage the project's git repositories");Es.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 cf({profile:ae,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Es.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 lf({profile:ae,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Es.command("list").description("List the project's repos").action(async()=>{try{await uf({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Se.parseAsync();
|