@code-partner/codepipe 0.6.1-dev.168.gbb28313 → 0.6.1-dev.171.gfa674f8
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 +135 -135
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,28 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var om=Object.defineProperty;var T=(t,e)=>()=>(t&&(e=t(t=0)),e);var im=(t,e)=>{for(var r in e)om(t,r,{get:e[r],enumerable:!0})};var Ie,qe,ri=T(()=>{"use strict";Ie="0.6.1-dev.171.gfa674f8",qe="https://hub.dev.codepipe.dev"});function Dn(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=sm&&t<=Ye}var Ye,sm,zs=T(()=>{"use strict";ri();Ye=4,sm=4});var Js=T(()=>{"use strict";ri()});function Un(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 zs(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 Js(t,e=Vs){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 Xs(t,e=Vs){return e.filter(r=>r.version>t)}var Ve,Fr,Vs,Qs=x(()=>{"use strict";Ve=".codepipe-context.yaml",Fr=".devpipe-context.yaml",Vs=[{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",Ve]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Ve]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]}]});var Zs=x(()=>{"use strict"});var nm,Q$,ea=x(()=>{"use strict";nm=[{id:"intake",label:"Intake",phases:["INTAKE"]},{id:"analysis",label:"Analysis",phases:["ANALYZING","ESTIMATING"]},{id:"ready",label:"Ready",phases:["READY"]},{id:"implementation",label:"Implementation",phases:["IMPLEMENTING","BUILD"]},{id:"delivery",label:"Delivery",phases:["READY_TO_APPLY","APPLYING"]}],Q$=nm.flatMap(t=>t.phases)});function Nt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var ta,ti=x(()=>{"use strict";ta=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function ra(t,e){return e.toLowerCase().includes(t.toLowerCase())}function ia(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||im.every(o=>e.some(i=>ra(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 om){let i=n.find(s=>ra(o,s.id));if(i)return i.id}return n[0].id}var ze,na,De,Hr,oa,ri,ni,om,im,oi=x(()=>{"use strict";ze="claude",na=[ze],De="opus",Hr="sonnet",oa="haiku",ri=[De,Hr,oa],ni={analyze:De,implement:De,"resolve-conflict":De,rework:De,estimate:Hr,build:Hr,"code-review":De,draft:Hr,index:De,backfill:De,analysis:De,chat:De},om=[De,Hr,oa],im=Array.from(new Set(Object.values(ni)))});function mt(t){return sm.has(t)?!0:am.some(e=>t.startsWith(e))}function Bn(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 ii(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function ua(t,e){let r=Bn(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Ot(r.id,"id")??n;if(!sa.test(o))throw new Error(`id must match ${sa} (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=Bn(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>aa)throw new Error(`too many params (max ${aa})`);let f=new Set;a=c.map((u,m)=>cm(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>ca)throw new Error(`too many steps (max ${ca})`);let d=l.map((f,u)=>{let m=Bn(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=ii(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 cm(t,e,r){let n=Bn(t,`params[${e}]`),o=Ot(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=Ot(n.label,`params[${e}].label`),c=Ot(n.help,`params[${e}].help`),l=n.required===!0,d=ii(n.min,`params[${e}].min`),f=ii(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 da(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,sm,am,la,sa,aa,ca,si=x(()=>{"use strict";Ce=/^[A-Z][A-Z0-9_]*$/,sm=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),am=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];la=600,sa=/^[a-z0-9-]+$/,aa=32,ca=64});function ga(t=lm){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...ga(r.groups));return e}function um(t,e){let r=JSON.stringify(e);return ga().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function ha(t){let e=um(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>pa)return{ok:!1,error:`${e.id} must have \u2264 ${pa} 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(mt(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>fa)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${fa} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var pa,fa,ma,lm,ya=x(()=>{"use strict";si();ti();oi();pa=64,fa=2e3,ma=2e3,lm=[{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:[...na],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:[...ri],help:"Overrides the recommended defaults for every role not listed below."},...ta.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...ri],help:`recommended: ${ni[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:ma,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:ma,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 wa=x(()=>{"use strict"});var ka=x(()=>{"use strict"});var ba=x(()=>{"use strict"});var $a=x(()=>{"use strict"});function va(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 it(t){return`${t}${dm}`}var Lt,dm,xa=x(()=>{"use strict";Lt=/^[a-z][a-z0-9-]{1,30}$/,dm="-codepipe-ctx"});var Sa=x(()=>{"use strict"});var Ra=x(()=>{"use strict"});function Jt(t){for(let e of pm){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var pm,Ta=x(()=>{"use strict";pm=[{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 Ia=x(()=>{"use strict"});var Ca=x(()=>{"use strict"});var Pa=x(()=>{"use strict"});function Ea(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function ja(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Ea(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Xt.test(r))return r;let n=Ea(t);return Xt.test(n)?n:ai}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 Wr(t){return`tasks/${t}/issue.yaml`}var Aa,Mn,ai,Xt,ci,pv,Gn,Kr,Na=x(()=>{"use strict";Aa=["bug","feature","epic"],Mn="feature",ai="TASK",Xt=/^[A-Z][A-Z0-9]{1,9}$/;ci={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},pv=ci.backlog,Gn="tracker/config.yaml",Kr="tracker/counter"});var Oa=x(()=>{"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 Fn(t){switch(t){case qr.gitlab:return"oauth2";case qr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var qr,Dt,La=x(()=>{"use strict";qr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Dt="x-bitbucket-api-token-auth"});var Da=x(()=>{"use strict"});var Ua=x(()=>{"use strict";Oa();La();Da()});var Ba,W=x(()=>{"use strict";qs();Ys();Qs();Zs();ea();ti();oi();ya();si();wa();ka();ba();$a();xa();Sa();Ra();Ta();Ia();Ca();Pa();Na();Ua();Ba=20});function M(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Pe=x(()=>{"use strict"});import{existsSync as Ma,renameSync as fm}from"node:fs";function Ut(t,e,r=n=>console.error(n)){if(Ma(e)||!Ma(t))return!1;try{return fm(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 Hn=x(()=>{"use strict"});import{existsSync as Kn,readFileSync as Ga,readdirSync as mm,writeFileSync as gm}from"node:fs";import{dirname as hm,join as gt}from"node:path";import{parse as ym}from"yaml";function wm(t=process.cwd()){let e=t;for(;;){if(Kn(gt(e,Je,"project.yaml")))return e;if(Kn(gt(e,li,"project.yaml")))return Ut(gt(e,li),gt(e,Je))&&bm(e),e;let r=hm(e);if(r===e)return null;e=r}}function km(t){let e=gt(t,Je);return Kn(e)?e:gt(t,li)}function bm(t){let e=gt(t,".gitignore");if(!Kn(e))return;let r=Ga(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 Yn(t){if(t)return{cfg:
|
|
8
|
-
`,{mode:384})}function zn(){return
|
|
9
|
-
`,{mode:384})}function
|
|
5
|
+
`}function Qs(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 Zs(t,e=Xs){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 ea(t,e=Xs){return e.filter(r=>r.version>t)}var Ve,Kr,Xs,ta=T(()=>{"use strict";Ve=".codepipe-context.yaml",Kr=".devpipe-context.yaml",Xs=[{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",Ve]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Ve]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]}]});var ra=T(()=>{"use strict"});var am,rv,na=T(()=>{"use strict";am=[{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"]}],rv=am.flatMap(t=>t.phases)});function Ot(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var oa,ni=T(()=>{"use strict";oa=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function ia(t,e){return e.toLowerCase().includes(t.toLowerCase())}function ca(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||lm.every(o=>e.some(i=>ia(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 cm){let i=n.find(s=>ia(o,s.id));if(i)return i.id}return n[0].id}var ze,sa,De,Wr,aa,oi,ii,cm,lm,si=T(()=>{"use strict";ze="claude",sa=[ze],De="opus",Wr="sonnet",aa="haiku",oi=[De,Wr,aa],ii={analyze:De,implement:De,"resolve-conflict":De,rework:De,estimate:Wr,build:Wr,"code-review":De,draft:Wr,index:De,backfill:De,analysis:De,chat:De},cm=[De,Wr,aa],lm=Array.from(new Set(Object.values(ii)))});function mt(t){return um.has(t)?!0:dm.some(e=>t.startsWith(e))}function Bn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Lt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function ai(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function fa(t,e){let r=Bn(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Lt(r.id,"id")??n;if(!la.test(o))throw new Error(`id must match ${la} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Lt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=Bn(r.env,"env");s={};for(let[u,g]of Object.entries(p)){if(!Ce.test(u))throw new Error(`env name "${u}" must match ${Ce}`);if(typeof g!="string"&&typeof g!="number"&&typeof g!="boolean")throw new Error(`env.${u} must be a scalar`);s[u]=String(g)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>ua)throw new Error(`too many params (max ${ua})`);let p=new Set;a=c.map((u,g)=>pm(u,g,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>da)throw new Error(`too many steps (max ${da})`);let d=l.map((p,u)=>{let g=Bn(p,`steps[${u}]`),f=Lt(g.run,`steps[${u}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${u}].run is required`);let m=Lt(g.name,`steps[${u}].name`),y=ai(g.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:f,...m?{name:m}:{},...y!==void 0?{timeout_sec:y}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:d}}function pm(t,e,r){let n=Bn(t,`params[${e}]`),o=Lt(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 g=n.enum;if(!Array.isArray(g)||g.length===0||!g.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=g}let a=Lt(n.label,`params[${e}].label`),c=Lt(n.help,`params[${e}].help`),l=n.required===!0,d=ai(n.min,`params[${e}].min`),p=ai(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}:{},...p!==void 0?{max:p}:{},...u!=null?{default:u}:{}}}function ma(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,um,dm,pa,la,ua,da,ci=T(()=>{"use strict";Ce=/^[A-Z][A-Z0-9_]*$/,um=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),dm=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];pa=600,la=/^[a-z0-9-]+$/,ua=32,da=64});function wa(t=fm){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...wa(r.groups));return e}function mm(t,e){let r=JSON.stringify(e);return wa().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function ka(t){let e=mm(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>ga)return{ok:!1,error:`${e.id} must have \u2264 ${ga} 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(mt(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>ha)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${ha} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var ga,ha,ya,fm,ba=T(()=>{"use strict";ci();ni();si();ga=64,ha=2e3,ya=2e3,fm=[{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:[...sa],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:[...oi],help:"Overrides the recommended defaults for every role not listed below."},...oa.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...oi],help:`recommended: ${ii[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:ya,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:ya,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 $a=T(()=>{"use strict"});var va=T(()=>{"use strict"});var xa=T(()=>{"use strict"});var Sa=T(()=>{"use strict"});function Ra(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 it(t){return`${t}${gm}`}var Dt,gm,Ta=T(()=>{"use strict";Dt=/^[a-z][a-z0-9-]{1,30}$/,gm="-codepipe-ctx"});var Ia=T(()=>{"use strict"});var Ca=T(()=>{"use strict"});function Qt(t){for(let e of hm){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var hm,Pa=T(()=>{"use strict";hm=[{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 Ea=T(()=>{"use strict"});var Aa=T(()=>{"use strict"});var ja=T(()=>{"use strict"});function _a(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Oa(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=_a(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Zt.test(r))return r;let n=_a(t);return Zt.test(n)?n:li}function La(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 Yr(t){return`tasks/${t}/issue.yaml`}var Na,Mn,li,Zt,ui,hv,Gn,qr,Da=T(()=>{"use strict";Na=["bug","feature","epic"],Mn="feature",li="TASK",Zt=/^[A-Z][A-Z0-9]{1,9}$/;ui={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},hv=ui.backlog,Gn="tracker/config.yaml",qr="tracker/counter"});var Ua=T(()=>{"use strict"});function er(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}function Fn(t){switch(t){case Vr.gitlab:return"oauth2";case Vr.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Vr,Ut,Ba=T(()=>{"use strict";Vr={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Ut="x-bitbucket-api-token-auth"});var Ma=T(()=>{"use strict"});var Ga=T(()=>{"use strict";Ua();Ba();Ma()});var Fa,W=T(()=>{"use strict";zs();Js();ta();ra();na();ni();si();ba();ci();$a();va();xa();Sa();Ta();Ia();Ca();Pa();Ea();Aa();ja();Da();Ga();Fa=20});function B(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var ke=T(()=>{"use strict"});import{existsSync as Ha,renameSync as ym}from"node:fs";function Bt(t,e,r=n=>console.error(n)){if(Ha(e)||!Ha(t))return!1;try{return ym(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 Hn=T(()=>{"use strict"});import{existsSync as Kn,readFileSync as Ka,readdirSync as wm,writeFileSync as km}from"node:fs";import{dirname as bm,join as gt}from"node:path";import{parse as $m}from"yaml";function vm(t=process.cwd()){let e=t;for(;;){if(Kn(gt(e,Je,"project.yaml")))return e;if(Kn(gt(e,di,"project.yaml")))return Bt(gt(e,di),gt(e,Je))&&Sm(e),e;let r=bm(e);if(r===e)return null;e=r}}function xm(t){let e=gt(t,Je);return Kn(e)?e:gt(t,di)}function Sm(t){let e=gt(t,".gitignore");if(!Kn(e))return;let r=Ka(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&&km(e,n)}function Pe(t=process.cwd()){let e=vm(t);if(!e)return null;let r=xm(e),n=Rm(Ka(gt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function Wa(t,e,r){return wm(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 Wn(t,e=process.cwd()){try{let r=Pe(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Rm(t){let e=$m(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,p=d==="bitbucket"?"bitbucket":d==="gitlab"?"gitlab":"github";i.push({name:l,host:p,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 qa(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,di,st=T(()=>{"use strict";Hn();Je=".codepipe",di=".devpipe"});import{homedir as Ya}from"node:os";import{mkdirSync as Tm,readFileSync as Im,writeFileSync as Cm,existsSync as pi}from"node:fs";import{dirname as za,join as qn,resolve as Pm}from"node:path";import{fileURLToPath as Em}from"node:url";function Ja(t){let e=qn(Va,".env");if(pi(e)&&process.loadEnvFile(e),t){let r=qn(Va,"profiles",t,".env");pi(r)&&process.loadEnvFile(r)}}function tr(t){let e=B("CONFIG");return e||(t?qn(Ya(),".codepipe","profiles",t,"config.json"):qn(Ya(),".codepipe","config.json"))}function Ue(t){let e=tr(t);if(!pi(e))return null;let r=Im(e,"utf-8");return JSON.parse(r)}function at(t,e){let r=tr(e);Tm(za(r),{recursive:!0}),Cm(r,JSON.stringify(t,null,2)+`
|
|
7
|
+
`,{mode:384})}function Yn(t){if(t)return{cfg:Ee(t),profile:t};let e;try{e=Pe()?.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:Ee(void 0),profile:void 0}}function Ee(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 ${tr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Va,ve=T(()=>{"use strict";ke();st();Va=Pm(za(Em(import.meta.url)),"..")});import{homedir as ec}from"node:os";import{existsSync as tc,mkdirSync as rc,readFileSync as nc,writeFileSync as oc}from"node:fs";import{dirname as ic,join as sc}from"node:path";function ac(t,e,r){let n=U(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},z(n)}function cc(t,e){let r=U(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],z(r),!0)}function lc(t){return Object.keys(U(t)?.secrets??{}).sort()}function Vn(t,e,r){let n=U(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,z(n),"pinned")}function uc(t,e){let r=U(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],z(r),!0):!1}function Xe(t){return sc(ec(),".codepipe","secrets",`${t}.json`)}function U(t){let e=Xe(t);return tc(e)?JSON.parse(nc(e,"utf-8")):null}function z(t){let e=Xe(t.projectId);rc(ic(e),{recursive:!0}),oc(e,JSON.stringify(t,null,2)+`
|
|
8
|
+
`,{mode:384})}function zn(){return sc(ec(),".codepipe","shared.json")}function fi(){let t=zn();return tc(t)?JSON.parse(nc(t,"utf-8")):null}function dc(t){let e=zn();rc(ic(e),{recursive:!0}),oc(e,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function rr(t){let e=U(t)?.claude?.oauthToken;return e||fi()?.claude?.oauthToken}function zr(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 nr(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var re=T(()=>{"use strict"});import{appendFileSync as Am,existsSync as fc,mkdirSync as jm,renameSync as mc,statSync as _m,unlinkSync as Nm}from"node:fs";import{Writable as Om}from"node:stream";import{join as Lm}from"node:path";function Jn(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Dm(process.env[`${t}_MAX_BYTES`]??String(gc.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):gc.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Dm(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 Xn(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...i)=>{n(...i);try{t.writeLine(Um(o,i))}catch{}};return console.log=r(e.log,"INFO"),console.warn=r(e.warn,"WARN"),console.error=r(e.error,"ERROR"),()=>{console.log=e.log,console.warn=e.warn,console.error=e.error}}function Um(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Bm(o)).join(" ");return`${r} ${t} ${n}`}function Bm(t){try{return JSON.stringify(t)}catch{return String(t)}}var gc,or,mi=T(()=>{"use strict";gc={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},or=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&jm(e.dir,{recursive:!0}),this.currentPath=Lm(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
|
+
`;Am(this.currentPath,r,"utf-8")}asWritable(){return new Om({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||!fc(this.currentPath)||_m(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;fc(n)&&(r>=this.cfg.maxFiles?Nm(n):mc(n,`${this.currentPath}.${r+1}`))}mc(this.currentPath,`${this.currentPath}.1`)}}}});function wc(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
12
|
+
`+t.slice(t.length-e)}async function ht(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let i=(await n.json()).login??"ok",s=n.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(c.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function Qn(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o;try{o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(o.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!o.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${o.status} ${o.statusText}`);if((await o.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function yt(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o;try{o=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(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 qm(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 qm(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Zn(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=kc.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: ${kc.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function wt(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(n){throw new Error(`cannot reach gitlab.com (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function bc(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}function Ym(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}function hi(t,e,r){let n=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${n}`}function Be(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new wi(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new yi(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new ki(e)}return new bi}var Mt,kc,yi,wi,ki,bi,kt=T(()=>{"use strict";Mt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};kc=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];yi=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new 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()}`)}},wi=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new 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 p of d.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.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 p of l.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!u.ok)continue;let g=(await u.json()).jobs??[];for(let f of g.filter(m=>m.conclusion==="failure")){let m=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!m.ok)continue;let y=await m.text();d.push(`### CI job: ${f.name}
|
|
13
|
+
|
|
14
|
+
${wc(y,8e3)}`)}}return d.length===0?void 0:wc(d.join(`
|
|
15
|
+
|
|
16
|
+
`),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()}`)}},ki=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new Mt(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=Ym(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()}`)}};bi=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(hi(e,r,"merge"))}async closePR(e,r,n){throw new Error(hi(e,r,"close"))}async addPRComment(e,r,n){throw new Error(hi(e,r,"comment"))}}});import{X509Certificate as xc}from"node:crypto";import{readFileSync as Vm}from"node:fs";import bt from"node:tls";function zm(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Tc(t=Rc){if($c)return;$c=!0;let e=B("EXTRA_CA_FILE");if(!(!e||!Sc))try{let r=zm(Vm(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}bt.setDefaultCACertificates([...bt.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function Ic(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 Jm(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
17
|
+
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Xm(t,e,r){return new Promise((n,o)=>{let i=bt.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new xc(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=bt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function Qm(t){try{let e=await fetch(t);return e.ok?new xc(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Cc(t,e=443,r=Rc){let n=`${t}:${e}`,o=vc.get(n);if(o)return o;let i=Zm(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return vc.set(n,i),i}async function Zm(t,e,r){if(!Sc)return!1;let n=8e3;if(await $i(t,e,n))return!0;let o=await Xm(t,e,n),i=bt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Jm(o);if(!c)break;let l=await Qm(c);if(!l)break;if(s.push(l.toString()),bt.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 Sc,$c,vc,Rc,Pc=T(()=>{"use strict";ke();Sc=typeof bt.getCACertificates=="function"&&typeof bt.setDefaultCACertificates=="function",$c=!1,vc=new Map,Rc=t=>console.warn(t)});function _c(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Ae(t,e,r){Tc();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(Ic(s)&&await Cc(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function eg(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function tg(){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 vi(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=tg(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Ae(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&&eg(l.status,d)){await Ec(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${d}`)}if(c<o){await Ec(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function $t(t){let e;try{e=await Ae(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Nc(t){try{let e=await Ae(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function rg(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Ac.get(o);if(i)return i;let s=await Ae(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(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 Ac.set(o,l.id),l.id}async function Oc(t,e,r,n=Jr){let o=await rg(t,e,r,n);await vi(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 Lc(t,e,r){return await(await vi(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Dc(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await vi(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Uc(t,e){let r=jc.get(e);if(r)return r;let n=await Ae(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return jc.set(e,i.id),i.id}async function Bc(t,e,r,n,o,i=Jr){let s=await Uc(t,e),a=await Ae(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Mc(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Ae(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}function Hc(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 Kc(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 Wc(t,e){let r=e.stageField??Jr,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=${Fc}&$top=200`,s=await Ae(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Vc(c,r))}async function qc(t,e,r=Jr){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Fc}`,o=await Ae(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Vc(await o.json(),r)}async function Yc(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${og}&$top=500`,o=await Ae(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Hc(s.attachments);return c&&(a.attachments=c),a})}function ig(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 Vc(t,e=Jr){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=Hc(t.attachments);a&&(s.attachments=a);let c=ig(t.links);return c&&(s.links=c),s}async function zc(t,e){let r=await sg(t,e);return r.length>0?r:ag(t,e)}async function sg(t,e){let r=await Uc(t,e),n=await Ae(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),i=[];for(let s of o)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:Jc(s.bundle)});return i}async function ag(t,e){let r=`project: ${e}`,n=await Ae(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:Jc(s.projectCustomField?.bundle)});return i}function Jc(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Ec,Jr,Ac,jc,Gc,ng,Fc,og,Gt=T(()=>{"use strict";Pc();Ec=t=>new Promise(e=>setTimeout(e,t));Jr="Stage",Ac=new Map;jc=new Map;Gc="attachments(id,name,url,size,mimeType)",ng="links(direction,linkType(name),issues(idReadable))",Fc=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Gc},${ng}`,og=`id,text,created,author(login),${Gc}`});function Me(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Xc(t,e){let r=U(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await $t({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail: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 ht(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 yt(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 wt(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 Qn(c,d.owner,d.repoName),n.push({name:`repo:${d.name}`,ok:!0})}catch(p){n.push({name:`repo:${d.name}`,ok:!1,detail:Me(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Qn(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 Qn(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=rr(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 vt(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 vt(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 Qc(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 ir=T(()=>{"use strict";re();kt();Gt()});import cg from"node:http";import xi from"node:crypto";function eo(){let t=Si(xi.randomBytes(32)),e=Si(xi.createHash("sha256").update(t).digest()),r=Si(xi.randomBytes(32));return{verifier:t,challenge:e,state:r}}function Ti(t){let e=new URL(lg);return e.search=new URLSearchParams({response_type:"code",client_id:Zc,redirect_uri:t.redirectUri,scope:dg,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function fg(t,e){let r=t.get("error");if(r)throw new Error(`oauth-error: ${r}`);if(t.get("state")!==e)throw new Error("state-mismatch");let n=t.get("code");if(!n)throw new Error("no-code");return n}function el(t,e){let[r,n]=t.trim().split("#");if(!r)throw new Error("no-code");if(n!==void 0&&n!==e)throw new Error("state-mismatch");return r}function mg(t){let e=t,r=e?.access_token;if(!r||typeof r!="string")throw new Error(`no access_token in response: ${JSON.stringify(t)}`);return{oauthToken:r,...typeof e.refresh_token=="string"?{refreshToken:e.refresh_token}:{},...typeof e.expires_in=="number"?{expiresIn:e.expires_in}:{}}}async function Ii(t){let e=await fetch(ug,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t.code,state:t.state,redirect_uri:t.redirectUri,client_id:Zc,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return mg(await e.json())}async function Ci(t){let e=t.timeoutMs??pg,r=cg.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=Ti({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,d)=>{s=setTimeout(()=>d(new Error("no-callback")),e),r.on("request",(p,u)=>{let g=new URL(p.url??"/",o);if(g.pathname!=="/callback"){u.statusCode=404,u.end();return}clearTimeout(s),u.setHeader("content-type","text/html"),u.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(fg(g.searchParams,t.state))}catch(f){d(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>Ii({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function tl(t){let e=await Ci(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
|
|
18
|
+
${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var Zc,lg,ug,Ri,dg,pg,Si,Pi=T(()=>{"use strict";Zc="9d1c250a-e61b-44d9-88ed-5944d1962f5e",lg="https://platform.claude.com/oauth/authorize",ug="https://platform.claude.com/v1/oauth/token",Ri="https://platform.claude.com/oauth/code/callback",dg="org:create_api_key user:profile user:inference",pg=12e4,Si=t=>Buffer.from(t).toString("base64url")});import{spawn as gg}from"node:child_process";function Ft(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=gg(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var to=T(()=>{"use strict"});import{existsSync as xt,mkdirSync as dl,readFileSync as ji,writeFileSync as sr}from"node:fs";import{homedir as Sg}from"node:os";import{join as Qe}from"node:path";import{simpleGit as Rg}from"simple-git";function Qr(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Qe(t,o);xt(s)||(sr(s,i),r.push(o))}return r}function Ht(t,e,r){let n=Qe(Sg(),".codepipe","profiles",t,"context-config");return dl(n,{recursive:!0}),sr(Qe(n,"project.yaml"),e.projectYaml),sr(Qe(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function oo(t,e,r){if(xt(e))for(let n of ar){let o=Qe(e,n),i=Qe(t,n);if(!(!xt(o)||xt(i)))try{sr(i,ji(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 cr(t){let e=Qe(t,".gitignore"),r=xt(e)?ji(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(ar.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
12
19
|
`)?"":`
|
|
13
|
-
`;return
|
|
20
|
+
`;return sr(e,r+i+Tg.join(`
|
|
14
21
|
`)+`
|
|
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);
|
|
22
|
+
`),!0}async function pl(t,e){try{if(!xt(Qe(t,".git")))return;let r=Rg(t),n=(await r.raw(["ls-files","--",...ar])).split(`
|
|
23
|
+
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;cr(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 Oi(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 _i(t){let e=new Map;for(let r of ar){let n=Qe(t,r);xt(n)&&e.set(r,ji(n))}return e}function Ni(t,e){dl(t,{recursive:!0});for(let[r,n]of e){let o=Qe(t,r);xt(o)||sr(o,n)}}var ar,Tg,ct=T(()=>{"use strict";St();ar=["project.yaml","regimen.yaml"];Tg=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Ig,mkdirSync as Cg,rmSync as Pg,writeFileSync as Li}from"node:fs";import{dirname as Eg,isAbsolute as Ag,join as gl,normalize as ao}from"node:path";import{simpleGit as hl}from"simple-git";async function Di(t,e){let r=ao(t),o=(so.get(r)??Promise.resolve()).catch(()=>{}).then(e);so.set(r,o);try{return await o}finally{so.get(r)===o&&so.delete(r)}}async function lt(t,e,r){return Di(t,()=>Ui(t,e,r))}async function Ui(t,e,r){if(!Ig(gl(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=de(t,a.path);if(a.deleted){Pg(c,{force:!0});continue}Cg(Eg(c),{recursive:!0}),a.encoding==="base64"?Li(c,Buffer.from(a.content,"base64")):Li(c,a.content)}let n=hl(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+=io)await n.raw(["add","-A","-f","--",...o.slice(a,a+io)]);for(let a=0;a<i.length;a+=io)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+io)]);await n.raw(["reset","-q","--",...ar]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await Oi(t))}async function Oi(t){let e=hl(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=fl;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 Ng(e);if(i.length>0&&i.every(a=>jg.has(a)||ml.test(a))){for(let a of i)ml.test(a)?await _g(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 ${fl} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function _g(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(`
|
|
24
|
+
`)){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);Li(de(e,r),i.join(`
|
|
18
25
|
`)+(i.length>0?`
|
|
19
|
-
`:""))}async function
|
|
20
|
-
`).map(r=>r.trim()).filter(Boolean)}function
|
|
21
|
-
`+t.slice(t.length-e)}async function wt(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 io(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 kt(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 kg(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 kg(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function so(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=_c.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${_c.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function bt(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(n){throw new Error(`cannot reach gitlab.com (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function Nc(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 bg(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 Si(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 Ti(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Ri(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Ii(e)}return new Ci}var Mt,_c,Ri,Ti,Ii,Ci,$t=x(()=>{"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"];Ri=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()}`)}},Ti=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}
|
|
22
|
-
|
|
23
|
-
${jc(y,8e3)}`)}}return d.length===0?void 0:jc(d.join(`
|
|
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()}`)}},Ii=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new Mt(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=bg(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()}`)}};Ci=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(Si(e,r,"merge"))}async closePR(e,r,n){throw new Error(Si(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Si(e,r,"comment"))}}});import{existsSync as vt,readFileSync as sr,readdirSync as Lc}from"node:fs";import{join as Pi}from"node:path";import{simpleGit as Dc}from"simple-git";import{parse as Uc}from"yaml";function Bc(t){try{let e=ue(t,Gn);if(!vt(e))return null;let r=Uc(sr(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Xt.test(n)?null:{prefix:n}}catch{return null}}function Mc(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
26
|
+
`:""))}async function Ng(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
27
|
+
`).map(r=>r.trim()).filter(Boolean)}function de(t,e){if(Ag(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=ao(gl(t,e)),n=ao(t+"/");if(r!==ao(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var fl,jg,ml,io,so,St=T(()=>{"use strict";ct();fl=3,jg=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),ml=/^tasks\/[^/]+\/comments\.jsonl$/,io=500,so=new Map});import{existsSync as Rt,readFileSync as lr,readdirSync as xl}from"node:fs";import{join as Mi}from"node:path";import{simpleGit as Sl}from"simple-git";import{parse as Rl}from"yaml";function Tl(t){try{let e=de(t,Gn);if(!Rt(e))return null;let r=Rl(lr(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 Il(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
26
28
|
# The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
|
|
27
29
|
# later would orphan existing tasks/<KEY>/ directories.
|
|
28
30
|
prefix: ${t}
|
|
@@ -30,15 +32,15 @@ prefix: ${t}
|
|
|
30
32
|
# Statuses are the built-in default set for now:
|
|
31
33
|
# Backlog | To Do | In Progress | Review | Done | Rejected
|
|
32
34
|
# A configurable status set / pipeline mapping is a planned extension.
|
|
33
|
-
`}function
|
|
34
|
-
`}function
|
|
35
|
+
`}function Gi(t=0){return`${t}
|
|
36
|
+
`}function Yg(t){return t==="depends_on"||t==="subtask"}function Vg(t){let e;try{e=Rl(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=Na.includes(r.type)?r.type:Mn,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;Yg(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 Fi(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
37
|
`)+`
|
|
36
|
-
`}function
|
|
38
|
+
`}function en(t,e){let r=de(t,Yr(e));return Rt(r)?Vg(lr(r,"utf-8")):null}function Cl(t){let e=Mi(t,"tasks");if(!Rt(e))return[];let r=[];for(let n of xl(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=en(t,n.name);o&&r.push(o)}return r}function zg(t,e){let r=de(t,`tasks/${e}/task.md`);if(!Rt(r))return;let n=lr(r,"utf-8").split(`
|
|
37
39
|
`),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
|
|
40
|
+
`).trim();if(!(!a||a==="_(no description)_"))return a}function tn(t,e,r={}){let n=r.withDescription?zg(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:Jg(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function Jg(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Xg(t){let e=de(t,qr);if(!Rt(e))return 0;let r=Number.parseInt(lr(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function Qg(t,e){let r=Mi(t,"tasks");if(!Rt(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of xl(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 Zg(t,e){return Math.max(Xg(t),Qg(t,e))+1}async function Pl(t,e,r,n){return Di(t,()=>eh(t,e,r,n))}async function eh(t,e,r,n){if(!Rt(Mi(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Zr(t);let o=null;for(let i=0;i<vl;i++){let s=Zg(t,e),a=`${e}-${s}`,c=[...r(a),{path:qr,content:Gi(s)}];try{return await Ui(t,c,n(a)),a}catch(l){if(o=l,await rh(t,n(a)),await Zr(t),th(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${vl} attempts: ${o instanceof Error?o.message:String(o)}`)}function th(t,e){for(let r of e){let n=de(t,r.path);if(!Rt(n)||(r.encoding==="base64"?lr(n).toString("base64"):lr(n,"utf-8"))!==r.content)return!1}return!0}async function Zr(t){let e=Sl(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 rh(t,e){let r=Sl(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
|
|
39
41
|
`)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
|
|
40
42
|
`).some(i=>i.trim()===e.split(`
|
|
41
|
-
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var
|
|
43
|
+
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var vl,lo=T(()=>{"use strict";W();St();vl=5});function ur(t,e,r,n){return[{path:"README.md",content:fh(t,e)},{path:".gitignore",content:ah()},{path:"CLAUDE.md",content:lh(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:ch()},{path:"knowledge/README.md",content:uh()},{path:"knowledge/build.yaml",content:ph()},{path:"actions/README.md",content:dh()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:sh()},{path:"adr/README.md",content:nh()},{path:"adr/0000-template.md",content:oh()},{path:"adr/INDEX.md",content:ih()},{path:Ve,content:Un()},...t.trackerProvider==="internal"?[{path:Gn,content:Il(t.youtrackProjectKey??li)},{path:qr,content:Gi()}]:[]]}function nh(){return`# ADR \u2014 architecture decision records
|
|
42
44
|
|
|
43
45
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
44
46
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -66,7 +68,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
66
68
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
67
69
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
68
70
|
open a PR to this repository.
|
|
69
|
-
`}function
|
|
71
|
+
`}function oh(){return`# ADR-NNNN: <title>
|
|
70
72
|
|
|
71
73
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
72
74
|
- **Date:** YYYY-MM-DD
|
|
@@ -88,12 +90,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
88
90
|
## Alternatives considered
|
|
89
91
|
|
|
90
92
|
- **<alternative>** \u2014 why it was rejected.
|
|
91
|
-
`}function
|
|
93
|
+
`}function ih(){return`# ADR index
|
|
92
94
|
|
|
93
95
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
94
96
|
|
|
95
97
|
(no accepted ADRs yet)
|
|
96
|
-
`}function
|
|
98
|
+
`}function sh(){return`# Audit
|
|
97
99
|
|
|
98
100
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
99
101
|
project appends only to its own file \u2014
|
|
@@ -102,14 +104,14 @@ project appends only to its own file \u2014
|
|
|
102
104
|
|
|
103
105
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
104
106
|
shared aggregate here.
|
|
105
|
-
`}function Ze(t,e,r,n,o="auto",i=ze,s){let a=t.trackerProvider==="internal";return{projectYaml:a?
|
|
107
|
+
`}function Ze(t,e,r,n,o="auto",i=ze,s){let a=t.trackerProvider==="internal";return{projectYaml:a?mh(t,o):gh(t,r,n,o),regimenYaml:hh(t.automationLevel,a?!0:e,a,i,s)}}function ah(){return`# codepipe project config is local to each member's workspace
|
|
106
108
|
project.yaml
|
|
107
109
|
regimen.yaml
|
|
108
110
|
|
|
109
111
|
# codepipe runtime
|
|
110
112
|
session.log
|
|
111
113
|
apply-queue.json
|
|
112
|
-
`}function
|
|
114
|
+
`}function ch(){return`# Index prompt
|
|
113
115
|
|
|
114
116
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
115
117
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -166,7 +168,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
166
168
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
167
169
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
168
170
|
empty or unavailable, say so briefly rather than inventing content.
|
|
169
|
-
`}function
|
|
171
|
+
`}function lh(t){return`# Project context for the CodePipe agent
|
|
170
172
|
|
|
171
173
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
172
174
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -194,7 +196,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
194
196
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
195
197
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
196
198
|
only after the analysis is approved.
|
|
197
|
-
`}function
|
|
199
|
+
`}function uh(){return`# Knowledge
|
|
198
200
|
|
|
199
201
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
200
202
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -211,7 +213,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
211
213
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
212
214
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
213
215
|
any merge conflict in it as noise (either side converges on the next run).
|
|
214
|
-
`}function
|
|
216
|
+
`}function dh(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
|
|
215
217
|
|
|
216
218
|
One \`<id>.yml\` per action. Every file here appears as a button on the
|
|
217
219
|
project's **RUN** tab; an action with \`params\` opens a small wizard first.
|
|
@@ -250,7 +252,7 @@ steps:
|
|
|
250
252
|
Parameter values are passed to the commands **only as env vars** \u2014 reference
|
|
251
253
|
them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
|
|
252
254
|
command text itself.
|
|
253
|
-
`}function
|
|
255
|
+
`}function ph(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
254
256
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
255
257
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
256
258
|
#
|
|
@@ -266,7 +268,7 @@ command text itself.
|
|
|
266
268
|
# - name: test
|
|
267
269
|
# run: npm test
|
|
268
270
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
269
|
-
`}function
|
|
271
|
+
`}function fh(t,e){return`# ${e.name}
|
|
270
272
|
|
|
271
273
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
272
274
|
|
|
@@ -292,7 +294,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
292
294
|
pipeline \u2014 don't edit them by hand.
|
|
293
295
|
|
|
294
296
|
Automation level: **${t.automationLevel}**.
|
|
295
|
-
`}function
|
|
297
|
+
`}function mh(t,e="auto"){return`# Project description for CodePipe.
|
|
296
298
|
id: ${t.projectId}
|
|
297
299
|
name: ${t.name}
|
|
298
300
|
|
|
@@ -315,15 +317,15 @@ branch:
|
|
|
315
317
|
pattern: codepipe/<TASK_ID>
|
|
316
318
|
|
|
317
319
|
repos:
|
|
318
|
-
${
|
|
319
|
-
`}function
|
|
320
|
+
${El(t)}
|
|
321
|
+
`}function El(t){return t.repos.length===0?` [] # add repos here
|
|
320
322
|
`:t.repos.map(e=>` - name: ${e.name}
|
|
321
323
|
host: ${e.host}
|
|
322
324
|
owner: ${e.owner}
|
|
323
325
|
repo: ${e.repoName}
|
|
324
326
|
mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
|
|
325
327
|
default_branch: ${e.defaultBranch}`:"")).join(`
|
|
326
|
-
`)}function
|
|
328
|
+
`)}function gh(t,e,r,n="auto"){let o=e?`
|
|
327
329
|
tracker_url: ${e}`:`
|
|
328
330
|
# tracker_url: https://your.youtrack.cloud`,i=r?`require_assignee: true
|
|
329
331
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -371,7 +373,7 @@ ${Hc(t)}
|
|
|
371
373
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
372
374
|
${i}`:` # project_key: \u2026
|
|
373
375
|
# tracker_url: https://your.youtrack.cloud
|
|
374
|
-
poll_interval_sec: 60`,a=
|
|
376
|
+
poll_interval_sec: 60`,a=El(t);return`# Project description for CodePipe.
|
|
375
377
|
id: ${t.projectId}
|
|
376
378
|
name: ${t.name}
|
|
377
379
|
|
|
@@ -402,7 +404,7 @@ branch:
|
|
|
402
404
|
|
|
403
405
|
repos:
|
|
404
406
|
${a}
|
|
405
|
-
`}function
|
|
407
|
+
`}function hh(t,e,r=!1,n=ze,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
|
|
406
408
|
# model in the recommended per-role split, so CodePipe set a single default
|
|
407
409
|
# your subscription can serve for all roles. Tune per role later from the
|
|
408
410
|
# dashboard (Project Settings \u2192 llm.models) or by editing this file.
|
|
@@ -546,19 +548,18 @@ ${a}
|
|
|
546
548
|
# # the previous task's branch (auto-merge without reworking the
|
|
547
549
|
# # tail of the chain).
|
|
548
550
|
# mode: parallel
|
|
549
|
-
`}var
|
|
550
|
-
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function wh(t,e,r){return new Promise((n,o)=>{let i=xt.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 pl(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Li(t,e,r){return new Promise(n=>{let o=xt.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 kh(t){try{let e=await fetch(t);return e.ok?new pl(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function yl(t,e=443,r=ml){let n=`${t}:${e}`,o=dl.get(n);if(o)return o;let i=bh(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return dl.set(n,i),i}async function bh(t,e,r){if(!fl)return!1;let n=8e3;if(await Li(t,e,n))return!0;let o=await wh(t,e,n),i=xt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=yh(o);if(!c)break;let l=await kh(c);if(!l)break;if(s.push(l.toString()),xt.setDefaultCACertificates([...i,...s]),await Li(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 Li(t,e,n)}var fl,ul,dl,ml,wl=x(()=>{"use strict";Pe();fl=typeof xt.getCACertificates=="function"&&typeof xt.setDefaultCACertificates=="function",ul=!1,dl=new Map,ml=t=>console.warn(t)});function vl(){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){gl();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(hl(s)&&await yl(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function $h(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function vh(){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 Di(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=vh(),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&&$h(l.status,d)){await kl(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${d}`)}if(c<o){await kl(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function St(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 xl(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 xh(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=bl.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 bl.set(o,l.id),l.id}async function Sl(t,e,r,n=nn){let o=await xh(t,e,r,n);await Di(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 Rl(t,e,r){return await(await Di(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Tl(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Di(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Il(t,e){let r=$l.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 $l.set(e,i.id),i.id}async function Cl(t,e,r,n,o,i=nn){let s=await Il(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 Pl(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 jl(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 Nl(t,e){let r=e.stageField??nn,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=${Al}&$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=>Dl(c,r))}async function Ol(t,e,r=nn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Al}`,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 Dl(await o.json(),r)}async function Ll(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Rh}&$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=jl(s.attachments);return c&&(a.attachments=c),a})}function Th(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 Dl(t,e=nn){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=jl(t.attachments);a&&(s.attachments=a);let c=Th(t.links);return c&&(s.links=c),s}async function Ul(t,e){let r=await Ih(t,e);return r.length>0?r:Ch(t,e)}async function Ih(t,e){let r=await Il(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:Bl(s.bundle)});return i}async function Ch(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:Bl(s.projectCustomField?.bundle)});return i}function Bl(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var kl,nn,bl,$l,El,Sh,Al,Rh,Ft=x(()=>{"use strict";wl();kl=t=>new Promise(e=>setTimeout(e,t));nn="Stage",bl=new Map;$l=new Map;El="attachments(id,name,url,size,mimeType)",Sh="links(direction,linkType(name),issues(idReadable))",Al=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${El},${Sh}`,Rh=`id,text,created,author(login),${El}`});function Me(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Ml(t,e){let r=D(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 St({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 wt(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 kt(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 io(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 io(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 io(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=er(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await ur(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 ur(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 Gl(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 on=x(()=>{"use strict";te();$t();Ft()});function sn(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 an(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 cn(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 Ui(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 Fl(t,e=process.env){return Ui(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>sn(t,e),e)}function Hl(t,e=process.env){return Ui(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>an(t,e),e)}function Kl(t,e=process.env){return Ui(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Dt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>cn(t,e),e)}var po=x(()=>{"use strict";W()});import{homedir as ny}from"node:os";import{existsSync as oy,mkdirSync as iy,readFileSync as sy,writeFileSync as ay}from"node:fs";import{dirname as cy,join as ly}from"node:path";function Hi(){return M("FARM_PINS")??ly(ny(),".codepipe","farm-pins.json")}function uu(){let t=Hi();if(!oy(t))return{};try{return JSON.parse(sy(t,"utf-8"))}catch{return{}}}function uy(t){let e=Hi();iy(cy(e),{recursive:!0}),ay(e,JSON.stringify(t,null,2)+`
|
|
551
|
-
`,{mode:384})}function dy(t){return uu()[t]}function wo(t,e){let r=uu();r[t]=e,uy(r)}function ko(t,e){let r=ke(e),n=dy(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 ${Hi()}.`);return r}var Ki=x(()=>{"use strict";Pe();je()});import{setTimeout as py}from"node:timers/promises";import fy from"ws";function bo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new fy(r)}async function Rt(t,e,r){return Ge(t,e,"/projects",r)}async function du(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 $o(t,e,r,n){return Ge(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function pu(t,e,r,n){return Ge(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function fu(t,e,r,n){return Ge(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function mu(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 vo(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 Wi(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 gu(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Wi(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 py(r.delayMs??1500)}throw o}async function hu(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new pn(e)}if(!r.ok)throw new N(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function yu(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 wu(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 ku(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 bu(t,e,r,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function $u(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function vu(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function xu(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function fn(t,e,r,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function qi(t,e,r,n){await Ge(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Su(t,e,r,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Ru(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,pn,fe=x(()=>{"use strict";N=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};pn=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{execFileSync as Ly}from"node:child_process";import{mkdtempSync as Dy,mkdirSync as Uy,readFileSync as Wu,rmSync as By,writeFileSync as My}from"node:fs";import{tmpdir as Gy}from"node:os";import{dirname as Fy,join as qu}from"node:path";function Yu(t="codepipe-context"){let e=Dy(qu(Gy(),"codepipe-ssh-")),r=qu(e,"id_ed25519");try{return Ly("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Wu(r,"utf-8"),publicKey:Wu(`${r}.pub`,"utf-8").trim()}}finally{By(e,{recursive:!0,force:!0})}}async function Vu(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 zu(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function Ju(t,e){Uy(Fy(t),{recursive:!0});let r=e.endsWith(`
|
|
551
|
+
`}var Kt=T(()=>{"use strict";W();lo()});import{createCipheriv as Oh,createDecipheriv as Lh,createHash as Dh,createPrivateKey as Uh,createPublicKey as qi,diffieHellman as ql,generateKeyPairSync as Yl,hkdfSync as Vl,randomBytes as Bh}from"node:crypto";function fo(){let{publicKey:t,privateKey:e}=Yl("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(Dh("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function ut(t,e){let r=qi({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Yl("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=ql({privateKey:o,publicKey:r}),c=Buffer.from(Vl("sha256",a,Buffer.concat([i,s]),zl,32)),l=Bh(12),d=Oh("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,u=Buffer.concat([d.update(p),d.final()]),g=d.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:g.toString("base64"),ct:u.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function pr(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=Uh({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=qi({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=qi(n).export({type:"spki",format:"der"}),a=ql({privateKey:n,publicKey:o}),c=Buffer.from(Vl("sha256",a,Buffer.concat([i,s]),zl,32)),l=Lh("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 zl,je=T(()=>{"use strict";zl=Buffer.from("devpipe-sealedbox-v1","utf-8")});function an(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(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 cn(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(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 ln(t,e=process.env){if(!t)return!1;let r=`https://${Ut}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Yi(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function Xl(t,e=process.env){return Yi(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>an(t,e),e)}function Ql(t,e=process.env){return Yi(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>cn(t,e),e)}function Zl(t,e=process.env){return Yi(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Ut}:${encodeURIComponent(t)}@bitbucket.org/`,()=>ln(t,e),e)}var mo=T(()=>{"use strict";W()});import{homedir as gy}from"node:os";import{existsSync as hy,mkdirSync as yy,readFileSync as wy,writeFileSync as ky}from"node:fs";import{dirname as by,join as $y}from"node:path";function Qi(){return B("FARM_PINS")??$y(gy(),".codepipe","farm-pins.json")}function ku(){let t=Qi();if(!hy(t))return{};try{return JSON.parse(wy(t,"utf-8"))}catch{return{}}}function vy(t){let e=Qi();yy(by(e),{recursive:!0}),ky(e,JSON.stringify(t,null,2)+`
|
|
552
|
+
`,{mode:384})}function xy(t){return ku()[t]}function bo(t,e){let r=ku();r[t]=e,vy(r)}function $o(t,e){let r=be(e),n=xy(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 ${Qi()}.`);return r}var Zi=T(()=>{"use strict";ke();je()});import{setTimeout as Sy}from"node:timers/promises";import Ry from"ws";function vo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Ry(r)}async function Tt(t,e,r){return Ge(t,e,"/projects",r)}async function bu(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new O(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function xo(t,e,r,n){return Ge(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function $u(t,e,r,n){return Ge(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function vu(t,e,r,n){return Ge(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function xu(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new O(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function So(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new O(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function es(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new O(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Su(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await es(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 Sy(r.delayMs??1500)}throw o}async function Ru(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new fn(e)}if(!r.ok)throw new O(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Tu(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new O(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Iu(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new O(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Cu(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new O(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 Eu(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function Au(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function ju(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function mn(t,e,r,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function ts(t,e,r,n){await Ge(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function _u(t,e,r,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Nu(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new O(o.status,s,a)}return s}async function J(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new O(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function 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 O(o.status,s,a)}return s}var O,fn,me=T(()=>{"use strict";O=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};fn=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{execFileSync as Vy}from"node:child_process";import{mkdtempSync as zy,mkdirSync as Jy,readFileSync as ed,rmSync as Xy,writeFileSync as Qy}from"node:fs";import{tmpdir as Zy}from"node:os";import{dirname as ew,join as td}from"node:path";function rd(t="codepipe-context"){let e=zy(td(Zy(),"codepipe-ssh-")),r=td(e,"id_ed25519");try{return Vy("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:ed(r,"utf-8"),publicKey:ed(`${r}.pub`,"utf-8").trim()}}finally{Xy(e,{recursive:!0,force:!0})}}async function nd(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let 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 od(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function id(t,e){Jy(ew(t),{recursive:!0});let r=e.endsWith(`
|
|
552
553
|
`)?e:e+`
|
|
553
|
-
`;return
|
|
554
|
-
`,{mode:384})}var
|
|
555
|
-
`}async function
|
|
556
|
-
`))!==-1;){let
|
|
557
|
-
`)){let
|
|
554
|
+
`;return Qy(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var ss=T(()=>{"use strict"});import{existsSync as sd,mkdirSync as ad}from"node:fs";import{dirname as cd}from"node:path";import{simpleGit as mr}from"simple-git";function tw(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 rw(t,e){return e?.contextWrite?.token?{user:Fn(t),secret:e.contextWrite.token}:t===Vr.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Vr.bitbucket?e?.bitbucket?.apiToken?{user:Ut,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function ld(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 Co))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 Po(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await J(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new Co(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=rw(er(s.cloneUrl),r);if(a){let c=await nw({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 ow({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 nw(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=tw(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(sd(`${r}/.git`)){let l=mr(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let d=_i(r);await l.reset(["--hard",`origin/${s}`]),Ni(r,d),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else ad(cd(r),{recursive:!0}),await mr().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await ud(r)}catch(l){return o.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function ow(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=id(i,n),a=od(e.cloneUrl),c=e.branch;try{if(sd(`${r}/.git`)){let l=mr(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=_i(r);await l.reset(["--hard",`origin/${c}`]),Ni(r,d),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ad(cd(r),{recursive:!0}),await mr().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await mr(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await ud(r),{root:r,contextDir:r,repos:[]}}catch(l){return o.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function ud(t){let e=mr(t);await e.raw(["config","user.email"]).then(n=>n.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}var Co,as=T(()=>{"use strict";W();me();ct();ss();Co=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as iw}from"node:child_process";function sw(){try{return iw("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function pd(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:sw(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var fd=T(()=>{"use strict"});import{homedir as gr}from"node:os";import{mkdirSync as aw,readFileSync as md,writeFileSync as cw,existsSync as ls}from"node:fs";import{dirname as lw,join as It}from"node:path";function uw(){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=B("SANDBOX_CONFIG");if(e)return e;let r=It(gr(),".codepipe","worker");return t?It(r,"profiles",t,"config.json"):It(r,"config.json")}function gd(){return It(gr(),".devpipe-sandbox","config.json")}function Eo(){Bt(It(gr(),".devpipe"),It(gr(),".codepipe")),B("SANDBOX_CONFIG")||Bt(It(gr(),".devpipe-sandbox"),It(gr(),".codepipe-sandbox"))}function hd(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function he(t){let e=Fe(t),r=null;return ls(e)?r=JSON.parse(md(e,"utf-8")):!t&&!B("SANDBOX_CONFIG")&&ls(gd())&&(r=JSON.parse(md(gd(),"utf-8"))),r?(r.planningLane=uw(),r):null}function yd(t,e){let r=Fe(e);aw(lw(r),{recursive:!0}),cw(r,JSON.stringify(t,null,2)+`
|
|
555
|
+
`,{mode:384})}var Ao=T(()=>{"use strict";ke();Hn();ls(".env")&&process.loadEnvFile(".env")});import dw from"ws";var hr,us=T(()=>{"use strict";hr=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 dw(e)}}});import{hostname as pw}from"node:os";async function Wt(t){Eo();let e=he(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Fe(t.profile)}.`),process.exit(1));let r=t.name??pw(),n=pd({projects:t.projects??[],llm:t.llm??null}),o=new hr(t.hub.replace(/\/$/,"")),i=fo(),s=be(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});yd({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 wd=T(()=>{"use strict";je();fd();Ao();us()});import{spawn as fw}from"node:child_process";function ds(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function gw(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 hw(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function qt(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ps(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
|
|
556
|
+
`}async function vd(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new dt;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 p=c.message;for(let u of p?.content??[]){let g=u.type;if(g==="text"){let f=String(u.text??"").trim();f&&o({ts:l,kind:"text",author:"agent",text:ds(f,kd)})}else if(g==="tool_use"){let f=String(u.name??""),m=u.input?.file_path??u.input?.path,y=gw(m,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:f,...y?{file:y}:{}})}}return}if(d==="user"){let p=c.message;for(let u of p?.content??[])if(u.type==="tool_result"){let g=u.is_error===!0,f=g?ds(hw(u.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:g,...f?{text:f}:{}})}return}if(d==="result"){s=c;let p=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...p?{text:p}:{}});return}if(d==="system"){let p=String(c.subtype??"").trim();p&&o({ts:l,kind:"system",author:"agent",text:p})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let d=fw(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 p=!1,u=!1,g=null,f=()=>{p=!0,d.kill("SIGTERM"),g=setTimeout(()=>d.kill("SIGKILL"),bd)};e.signal?.addEventListener("abort",f,{once:!0});let m=null,y=()=>{m&&clearTimeout(m),m=setTimeout(()=>{u=!0,console.warn(`[claude:chat] idle for ${$d}ms \u2014 ending session`),d.kill("SIGTERM"),g=setTimeout(()=>d.kill("SIGKILL"),bd)},$d)},k=()=>{g&&clearTimeout(g),m&&clearTimeout(m),e.signal?.removeEventListener("abort",f)},w=!0,b=P=>{if(!(!w||d.stdin.destroyed))try{d.stdin.write(P)}catch{}};b(ps(e.prompt)),y(),(async()=>{try{for await(let P of e.interactive.inbox){if(p||!w)break;if(y(),P.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:ds(P.text,kd)}),b(ps(P.text));else{b(ps(mw)),w=!1;try{d.stdin.end()}catch{}break}}}catch{}})();let R="",G=P=>{let N;try{N=JSON.parse(P)}catch{return}a(N)};d.stdout.on("data",P=>{i.push(P),y(),R+=P;let N;for(;(N=R.indexOf(`
|
|
557
|
+
`))!==-1;){let F=R.slice(0,N).trim();R=R.slice(N+1),F&&G(F)}}),d.stderr.on("data",P=>{i.push(P);for(let N of P.split(`
|
|
558
|
+
`)){let F=N.trim();F&&console.warn(`[claude:chat:stderr] ${F}`)}}),d.on("error",P=>{k(),l(P)}),d.on("close",P=>{if(k(),p){l(new dt);return}if(u){l(new Error("chat session ended: idle for too long without a reply"));return}R.trim()&&G(R.trim()),console.log(`[claude:chat] exit code=${P}`),c({artifactPaths:[],log:i.join(""),usage:yw(s)})})})}function yw(t){let e=Ot();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=qt(r.input_tokens),e.outputTokens=qt(r.output_tokens),e.cacheReadInputTokens=qt(r.cache_read_input_tokens),e.cacheCreationInputTokens=qt(r.cache_creation_input_tokens)),e.totalCostUsd=qt(t.total_cost_usd),e.numTurns=qt(t.num_turns),e.durationMs=qt(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var kd,bd,$d,mw,xd=T(()=>{"use strict";W();yr();kd=16e3,bd=5e3,$d=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),mw="\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 ww}from"node:child_process";import{existsSync as kw}from"node:fs";function $w(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Sd(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: ${Ct(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=Sw(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=Td(o.content);console.log(`[claude] tool_result (error)${i?`: ${Ct(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)} ${Ct(JSON.stringify(e),200)}`),e}function vw(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(Ct(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(Ct(r.trim().split(`
|
|
558
559
|
`).slice(-5).join(`
|
|
559
|
-
`),500)),n.join(" \u2014 ")}function
|
|
560
|
-
`))!==-1;){let
|
|
561
|
-
`)){let
|
|
560
|
+
`),500)),n.join(" \u2014 ")}function xw(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 Td(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Sw(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=${Ct(r,80)}`}return""}function Ct(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function $e(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Rw(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=$e(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:$e(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 Tw(t,e,r,n){let o=Ot(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=$e(i.input_tokens),o.outputTokens=$e(i.output_tokens),o.cacheReadInputTokens=$e(i.cache_read_input_tokens),o.cacheCreationInputTokens=$e(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=$e(t?.total_cost_usd),o.numTurns=t&&$e(t.num_turns)>0?$e(t.num_turns):r,o.durationMs=$e(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function Iw(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:Ct(c,Rd)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,d=l?.file_path??l?.path??l?.notebook_path,p=Cw(d,e);i.push({ts:r,kind:"tool",tool:c,...p?{file:p}:{}})}}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?Ct(Td(s.content),Rd):"";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 Cw(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 wr,dt,bw,yn,Rd,yr=T(()=>{"use strict";W();xd();wr=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},dt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},bw=5e3;yn=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return vd(this.binary,e);if(e.signal?.aborted)throw new dt;let r=["-p",$w(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,d=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let m=Rw(f.rate_limit_info);m&&(!l||m.utilization>l.utilization)&&(l=m);return}if(f.type==="assistant"){let m=f.message;typeof m?.model=="string"&&(c=m.model);let y=m?.usage;y&&(a+=1,s.input+=$e(y.input_tokens),s.output+=$e(y.output_tokens),s.cacheRead+=$e(y.cache_read_input_tokens),s.cacheCreate+=$e(y.cache_creation_input_tokens))}}},p=e.role,u=e.onActivity,g=f=>{if(u)for(let m of Iw(f,e.workspaceDir))try{u(m)}catch{}};return u?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,m)=>{let y=ww(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});y.stdout.setEncoding("utf-8"),y.stderr.setEncoding("utf-8");let k=!1,w=null,b=()=>{k=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),y.kill("SIGTERM"),w=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),y.kill("SIGKILL")},bw)};e.signal?.addEventListener("abort",b,{once:!0});let R=()=>{w&&clearTimeout(w),e.signal?.removeEventListener("abort",b)},G="";y.stdout.on("data",P=>{n.push(P),G+=P;let N;for(;(N=G.indexOf(`
|
|
561
|
+
`))!==-1;){let F=G.slice(0,N).trim();if(G=G.slice(N+1),F){let fe=Sd(F);d(fe),fe&&g(fe)}}}),y.stderr.on("data",P=>{n.push(P),o.push(P);for(let N of P.split(`
|
|
562
|
+
`)){let F=N.trim();F&&console.warn(`[claude:stderr] ${F}`)}}),y.on("error",P=>{R(),m(P)}),y.on("close",P=>{if(R(),k){m(new dt);return}if(G.trim()){let F=Sd(G.trim());d(F),F&&g(F)}let N=i?.is_error===!0;if(P!==0||N){let F=typeof i?.api_error_status=="number"?i.api_error_status:void 0,fe=typeof i?.subtype=="string"?i.subtype:void 0,Ne=typeof i?.result=="string"?i.result:void 0;m(new wr(vw(P,i,o.join("")),{code:P,apiErrorStatus:F,subtype:fe,resultText:Ne,retryAfterMs:xw(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:Tw(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("/")&&kw(n))}};Rd=200});import{mkdirSync as Pw,writeFileSync as kr}from"node:fs";import{dirname as Ew,join as br}from"node:path";function Id(t,e,r){let n=br(t,e);Pw(Ew(n),{recursive:!0}),kr(n,r)}function Aw(t,e,r){return`# ${t} \u2014 Estimate
|
|
562
563
|
|
|
563
564
|
**Title:** ${e}
|
|
564
565
|
|
|
@@ -579,7 +580,7 @@ production-grade estimates.)
|
|
|
579
580
|
${r.split(`
|
|
580
581
|
`).slice(0,8).join(`
|
|
581
582
|
`).trim()||"(empty)"}
|
|
582
|
-
`}function
|
|
583
|
+
`}function jw(t,e,r,n){let o=n?`
|
|
583
584
|
## Reviewer rework instruction
|
|
584
585
|
|
|
585
586
|
> ${n.split(`
|
|
@@ -608,10 +609,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
608
609
|
${r.split(`
|
|
609
610
|
`).slice(0,8).join(`
|
|
610
611
|
`).trim()||"(empty)"}
|
|
611
|
-
`}function
|
|
612
|
+
`}function _w(t){return`# ${t} \u2014 Open questions
|
|
612
613
|
|
|
613
614
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
614
|
-
`}function
|
|
615
|
+
`}function Nw(t,e,r){let n=r?` (rework: ${r.split(`
|
|
615
616
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
616
617
|
index 0000000..1111111 100644
|
|
617
618
|
--- a/CHANGELOG.md
|
|
@@ -622,7 +623,7 @@ index 0000000..1111111 100644
|
|
|
622
623
|
+- mock-runner placeholder change for slice 5 testing.
|
|
623
624
|
+
|
|
624
625
|
# Changelog
|
|
625
|
-
`}function
|
|
626
|
+
`}function Ow(t,e,r){return`# ${t} \u2014 Diff summary
|
|
626
627
|
|
|
627
628
|
**Title:** ${e}
|
|
628
629
|
${r?`
|
|
@@ -633,142 +634,141 @@ ${r?`
|
|
|
633
634
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
634
635
|
|
|
635
636
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
636
|
-
`}var
|
|
637
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:
|
|
637
|
+
`}var wn,fs=T(()=>{"use strict";W();yr();wn=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=Aw(n,o,i);kr(br(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;kr(br(e.workspaceDir,"SOLUTION.md"),jw(n,o,i,a)),s.push("SOLUTION.md"),kr(br(e.workspaceDir,"QUESTIONS.md"),_w(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Id(e.workspaceDir,"changes/sample.patch",Nw(n,o,a)),s.push("changes/sample.patch"),Id(e.workspaceDir,"diff-summary.md",Ow(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(kr(br(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
638
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:Ot()}}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 dt;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 kr(br(e.workspaceDir,"DRAFT.md"),`${o}
|
|
638
639
|
|
|
639
640
|
\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).
|
|
640
|
-
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:
|
|
641
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Ot()}}}});function Cd(t){switch(t){case"mock":return new wn;case"claude-headless":return new yn;default:return null}}function Pd(t,e){let r=e&&e.trim().length>0?e.trim():ze;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var Ed=T(()=>{"use strict";W();yr();fs();yr();fs()});function _d(t=process.env){return{maxAttempts:jo(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:jo(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:jo(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:jo(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function Bw(t){if(t instanceof wr){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return Dw.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&Uw.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:Lw.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Ad.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 Ad.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Nd(t){if(t instanceof wr){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&jd.test(n)}let e=t instanceof Error?t.message:String(t);return jd.test(e)}function Mw(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 Od(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=Bw(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=Mw(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 jo(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var Lw,Ad,Dw,Uw,jd,Ld=T(()=>{"use strict";yr();Lw=new Set([429,500,502,503,529]),Ad=/(\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,Dw=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,Uw=new Set(["error_max_turns"]);jd=/(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 Gw,rmSync as Fw,writeFileSync as Dd}from"node:fs";import{tmpdir as Hw}from"node:os";import{join as ms}from"node:path";function _o(t){return`[url "https://${t}/"]
|
|
641
642
|
insteadOf = git@${t}:
|
|
642
643
|
insteadOf = ssh://git@${t}/
|
|
643
|
-
`}function
|
|
644
|
+
`}function Ud(t,e){if(t.length===0)return null;let r=Gw(ms(Hw(),"devpipe-gitcreds-")),n=ms(r,"credentials"),o=ms(r,"gitconfig");return Dd(n,t.join(`
|
|
644
645
|
`)+`
|
|
645
|
-
`,{mode:384}),
|
|
646
|
+
`,{mode:384}),Dd(o,`[credential]
|
|
646
647
|
helper = store --file=${n}
|
|
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{
|
|
648
|
-
`).map(
|
|
649
|
-
`).map(l=>l.trim()).filter(l=>l.length>0),c=await
|
|
650
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function
|
|
651
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
652
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=
|
|
653
|
-
`+e.subarray(e.length-
|
|
654
|
-
\u2026 [${r.length-e} bytes elided]`}var
|
|
648
|
+
`+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{Fw(r,{recursive:!0,force:!0})}catch{}}}}function gs(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Kw)),t.bitbucket?.apiToken&&(e.push(`https://${Ut}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Ww)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(qw)),Ud(e,r)}function Bd(t,e){if(t.contextWrite?.token){let r=er(e)??"github.com",n=Fn(r);return Ud([`https://${n}:${t.contextWrite.token}@${r}`],[_o(r)])}return gs(t)}var Kw,Ww,qw,Md=T(()=>{"use strict";W();Kw=_o("github.com"),Ww=_o("bitbucket.org"),qw=_o("gitlab.com")});import{spawn as Fd}from"node:child_process";import{existsSync as No,mkdirSync as kn,readFileSync as Yw,rmSync as hs,symlinkSync as Vw}from"node:fs";import{homedir as zw}from"node:os";import{dirname as vr,join as Pt}from"node:path";function Hd(t){let e=Pt(zw(),".codepipe-sandbox","repos");return t?Pt(e,t):e}function Kd(t,e){let n=($r.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{$r.get(t)===o&&$r.delete(t)},()=>{$r.get(t)===o&&$r.delete(t)});return $r.set(t,o),n}function Gd(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 Jw(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 Wd(t,e,r,n,o){let i=async c=>{await Q(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await Q(t,["reset","--hard",`origin/${c}`],o),await Q(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!Gd(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{No(t)&&hs(t,{recursive:!0,force:!0}),kn(vr(t),{recursive:!0});try{return await Q(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Gd(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),No(t)&&hs(t,{recursive:!0,force:!0}),kn(vr(t),{recursive:!0}),await Q(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(No(Pt(t,".git")))try{return await s()}catch(c){if(!Jw(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 qd(t){await Q(t.workspacePath,["reset","--hard",t.baseSha]),await Q(t.workspacePath,["clean","-fdx"])}async function Yd(t,e){let r=t.workspacePath;await Q(r,["add","-A"]);let n=(await ge(r,["write-tree"])).trim(),o=(await ge(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:xr,GIT_AUTHOR_EMAIL:Sr,GIT_COMMITTER_NAME:xr,GIT_COMMITTER_EMAIL:Sr};return(await ge(r,["commit-tree",n,"-m",e],i)).trim()}async function Vd(t,e,r,n,o){try{await Q(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw er(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 zd(t,e){return ge(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Jd(t,e,r,n,o){await Q(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await Q(t.workspacePath,["checkout","--force",r])}async function Xd(t,e,r,n,o,i){let s=t.workspacePath;await Q(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await ge(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=f=>ge(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await ge(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Q(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(m=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(m)}`)}),await c(n)||await Q(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:xr,GIT_AUTHOR_EMAIL:Sr,GIT_COMMITTER_NAME:xr,GIT_COMMITTER_EMAIL:Sr},d=(await ge(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await ge(s,["commit-tree",d,"-p",n,"-m","delivery"],l)).trim();await Q(s,["cherry-pick","--quit"],l).catch(()=>{});let u=null;try{await Q(s,["cherry-pick","--no-commit",p],l)}catch(f){u=f instanceof Error?f.message:String(f)}let g=(await ge(s,["diff","--name-only","--diff-filter=U"])).split(`
|
|
649
|
+
`).map(f=>f.trim()).filter(f=>f.length>0);if(u&&g.length===0)throw await Q(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${u}`);return g}async function ys(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:xr,GIT_AUTHOR_EMAIL:Sr,GIT_COMMITTER_NAME:xr,GIT_COMMITTER_EMAIL:Sr};(await ge(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Q(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await Q(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await Q(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await ge(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
650
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await ge(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function Q(t,e,r){return new Promise((n,o)=>{let i=Fd("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}):
|
|
651
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function ge(t,e,r){return new Promise((n,o)=>{let i=Fd("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}):
|
|
652
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function Qd(t,e){No(t)&&hs(t,{recursive:!0,force:!0}),kn(vr(t),{recursive:!0}),Vw(e,t,"dir")}async function Zd(t,e,r){await Q(t,["worktree","prune"]).catch(()=>{}),kn(vr(r),{recursive:!0}),await Q(t,["worktree","add","--detach",r,`origin/${e}`])}async function Xw(t,e,r){kn(vr(r),{recursive:!0}),await Q(vr(r),["clone","--quiet","--no-checkout",t,r]),await Q(r,["checkout","--force","--detach",e])}async function ep(t,e,r,n="worktree",o,i){return r.length===0?[]:Kd(e,async()=>{let s=[];for(let a of r){let c=Pt(Hd(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await Wd(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 ge(c,["rev-parse","HEAD"])).trim(),p=Pt(t,"code",a.name);n==="direct"?(Qd(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${d.slice(0,10)}`)):n==="clone"?(await Xw(c,d,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${d.slice(0,10)}`)):(await Zd(c,l,p),console.log(`[git] code: worktree ${p} \u2190 ${c} @ ${d.slice(0,10)}`)),s.push({name:a.name,workspacePath:p,cachePath:c,ref:l,baseSha:d})}return s})}async function tp(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return Kd(e,async()=>{let a=Pt(Hd(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await Wd(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=Pt(t,"context");n==="direct"?(Qd(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Zd(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await ge(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function rp(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await Q(r,["add","-A",...n]).catch(()=>{});let o;try{o=await ge(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
|
|
653
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Yw(Pt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var $r,xr,Sr,np=T(()=>{"use strict";W();$r=new Map;xr="CodePipe Agent",Sr="codepipe@codepartner.ee"});import{readFileSync as Qw}from"node:fs";import{join as Zw}from"node:path";function op(t){let e=Zw(t,bn),r;try{r=Qw(e,"utf-8")}catch{throw new Et(`BUILD produced no ${bn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(d){throw new Et(`${bn} is not valid JSON: ${d instanceof Error?d.message:String(d)}`)}if(!n||typeof n!="object")throw new Et(`${bn} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Et(`${bn}: "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 p=d,u=typeof p.name=="string"?p.name:null,g=typeof p.exitCode=="number"?p.exitCode:null;if(u===null||g===null)return[];let f={name:u,exitCode:g};return typeof p.durationMs=="number"&&(f.durationMs=p.durationMs),[f]}),c=typeof o.logTail=="string"?ek(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(p=>p.exitCode!==0);d&&(l.failedStep=d.name)}return l}function ek(t){let e=Buffer.from(t,"utf-8");return e.length<=ws?t:`\u2026 [${e.length-ws} bytes elided] \u2026
|
|
654
|
+
`+e.subarray(e.length-ws).toString("utf-8")}var ws,Et,bn,ip=T(()=>{"use strict";ws=8*1024,Et=class extends Error{},bn="meta/build-result.json"});import{readFileSync as tk}from"node:fs";import{join as rk}from"node:path";function ap(t){let e=rk(t,Rr),r;try{r=tk(e,"utf-8")}catch{throw new pt(`code review produced no ${Rr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new pt(`${Rr} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new pt(`${Rr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new pt(`${Rr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?sp(o.remarks,nk):"";if(!i&&s.trim().length===0)throw new pt(`${Rr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?sp(o.summary,ok):"";return{approved:i,remarks:s,summary:a}}function sp(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
|
|
655
|
+
\u2026 [${r.length-e} bytes elided]`}var nk,ok,pt,Rr,cp=T(()=>{"use strict";nk=16*1024,ok=4*1024,pt=class extends Error{},Rr="meta/review-result.json"});import{readFileSync as ik,statSync as sk}from"node:fs";import{join as lp}from"node:path";function fk(t){return t.startsWith("meta/")||pk.has(t)}function mk(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 gk(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function up(t,e,r){let n=r?.maxBytes??ak,o=r?.totalBytes??ck,i=r?.maxCount??lk,s=e.map((f,m)=>{let y=null;try{y=sk(lp(t,f)).size}catch{}return{path:f,index:m,size:y}}),a=[...s].sort((f,m)=>{let y=k=>fk(k.path)?0:1;return y(f)!==y(m)?y(f)-y(m):(f.size??0)-(m.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((f,m)=>f.index-m.index).map(f=>f.path),d=new Array(s.length),p=[],u=0;for(let f of c){let m=null;if(f.size!==null&&f.size<=n&&u+f.size<=o)try{m=ik(lp(t,f.path))}catch{}if(m!==null){u+=m.length,d[f.index]={path:f.path,contentBase64:m.toString("base64")};continue}let y=f.size===null?gk(f.path):mk(f.path,f.size,n,o),k=Buffer.from(y,"utf-8");u+=k.length,d[f.index]={path:f.path,contentBase64:k.toString("base64")},p.push({path:f.path,bytes:f.size??0})}let g=d.filter(f=>f!==void 0);if(l.length>0){let f=l.slice(0,dk),m=`# Artifacts omitted from upload
|
|
655
656
|
|
|
656
657
|
${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.
|
|
657
658
|
|
|
658
|
-
`+
|
|
659
|
-
`).join("")+(l.length>
|
|
660
|
-
\u2026and ${l.length-
|
|
661
|
-
`:"");
|
|
659
|
+
`+f.map(y=>`- ${y}
|
|
660
|
+
`).join("")+(l.length>f.length?`
|
|
661
|
+
\u2026and ${l.length-f.length} more.
|
|
662
|
+
`:"");g.push({path:uk,contentBase64:Buffer.from(m,"utf-8").toString("base64")})}return{artifacts:g,omitted:p,dropped:l}}var ak,ck,lk,uk,dk,pk,dp=T(()=>{"use strict";ak=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),ck=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),lk=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),uk="artifacts-omitted.md",dk=500,pk=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 hk,mkdtempSync as yk,readFileSync as wk,readdirSync as fp,rmSync as pp}from"node:fs";import{tmpdir as kk}from"node:os";import{join as Oo,relative as bk}from"node:path";function mp(t){let e=yk(Oo(kk(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>pp(e,{recursive:!0,force:!0}),listFiles:()=>gp(e,e),readFile:r=>wk(Oo(e,r),"utf-8"),clean:()=>{for(let r of fp(e))vk.has(r)||pp(Oo(e,r),{recursive:!0,force:!0})}}}function gp(t,e){let r=[];for(let n of fp(e)){let o=Oo(e,n),i=hk(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&$k.has(n))continue;r.push(...gp(t,o))}else r.push(bk(t,o))}return r}var $k,vk,hp=T(()=>{"use strict";$k=new Set(["code","context","scratch"]),vk=new Set(["code","context"])});import{mkdirSync as xk,readFileSync as yp,readdirSync as Sk,writeFileSync as Rk}from"node:fs";import{homedir as Tk}from"node:os";import{dirname as Ik,join as Tr}from"node:path";function Pk(t){let e=Buffer.from(t,"utf-8");if(e.length<=Lo)return t;let r=Math.floor(Lo/4),n=Lo-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}
|
|
662
663
|
|
|
663
|
-
\u2026 [${s} bytes elided \u2014 log capped at ${
|
|
664
|
+
\u2026 [${s} bytes elided \u2014 log capped at ${Lo} bytes for upload] \u2026
|
|
664
665
|
|
|
665
|
-
${i}`}function
|
|
666
|
+
${i}`}function Ek(){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 $n(t={}){Eo();let e=he(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=hd(t.profile,e.sandboxId,!!B("SANDBOX_CONFIG")),s=Tr(Tk(),".codepipe","logs"),a=Jn("SANDBOX_LOG",i,s);if(a.enabled){let E=new or(a);Xn(E),console.log(`[log] file logging \u2192 ${E.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ie} (protocol ${Ye})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Cd(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=_d();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let d=new hr(e.hubUrl,e.token),p=!1,u=new AbortController,g=new Map,f=null,m=null,y=!1,k=()=>{let E=d.openControlSocket();return f=E,E.on("open",()=>{console.log("[ws] connected");let h={type:"sandbox_hello",platformVersion:Ie,protocolVersion:Ye};E.send(JSON.stringify(h))}),E.on("message",h=>{let S=h.toString("utf-8"),x=null;try{let v=JSON.parse(S);v&&typeof v=="object"&&(x=v)}catch{}if(x&&x.type==="hello"){let v=x;m=Dn(v.protocolVersion);let j=m?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${v.platformVersion} (protocol ${v.protocolVersion}) \u2014 ${j}`),m&&(y=!1);return}if(x&&x.type==="pause_job"){let v=typeof x.jobId=="string"?x.jobId:"",j=v?g.get(v):void 0;j?(console.warn(`[ws] pause_job ${v} \u2014 aborting agent`),j.paused=!0,j.abort.abort()):console.log(`[ws] pause_job ${v} \u2014 not a running job, ignoring`),v&&E.send(JSON.stringify({type:"job_paused",jobId:v}));return}if(x&&(x.type==="chat_user_message"||x.type==="chat_finalize")){let v=typeof x.jobId=="string"?x.jobId:"",j=v?g.get(v):void 0;if(j?.chatInbox)if(x.type==="chat_user_message"){let A=typeof x.text=="string"?x.text:"";A.trim()&&j.chatInbox.push({kind:"user",text:A})}else j.chatInbox.finalize();else console.log(`[ws] ${String(x.type)} ${v} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${S}`)}),E.on("close",(h,S)=>{console.log(`[ws] closed code=${h} reason=${S?.toString()||""}`),f===E&&(f=null),!p&&setTimeout(k,2e3)}),E.on("error",h=>console.warn(`[ws] error: ${h.message}`)),E},w=k(),b=async E=>{for(;!p;){if(m===!1){y||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ie}, protocol ${Ye}) \u2014 not claiming jobs until versions align.`),y=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await d.claim(u.signal,E);if(h.status===204)continue;if(h.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,p=!0;break}if(!h.ok){console.warn(`[claim:${E}] ${h.status} \u2014 backoff 5s`),await new Promise(x=>setTimeout(x,5e3));continue}let S=await h.json();await R(d,S)}catch(h){if(u.signal.aborted)break;let S=h instanceof Error?h.message:String(h);console.warn(`[claim:${E}] error: ${S} \u2014 backoff 5s`),await new Promise(x=>setTimeout(x,5e3))}}};async function R(E,h){let S={abort:new AbortController,paused:!1};h.role==="chat"&&(S.chatInbox=Ek()),g.set(h.jobId,S);let x=!1,v=null,j=null,A=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),$=async()=>{try{await E.heartbeat(h.jobId)==="claim_lost"&&(x=!0,console.warn(`[job] ${h.jobId} claim lost \u2014 HUB sweeper took it`))}catch(K){let X=K instanceof Error?K.message:String(K);console.warn(`[job] ${h.jobId} heartbeat error: ${X}`)}};$();let I=setInterval(()=>{$()},A),M=new Date().toISOString();console.log(`[job] ${h.jobId} claimed \u2014 role=${h.role} task=${h.taskId} phase=${h.phase}`),console.log(`[job] ${h.jobId} prompt (${h.prompt.length} chars):`),console.log(P(h.prompt," \u2502 "));let Y=[],We=null,Vo=400,Nn=25,zo=500,_=()=>{if(We&&(clearTimeout(We),We=null),Y.length===0)return;let K=Y.splice(0,Y.length),X=f;if(!X||X.readyState!==X.OPEN)return;let rt={type:"agent_activity",jobId:h.jobId,taskId:h.taskId,projectId:h.projectId,role:h.role,phase:h.phase,events:K};try{X.send(JSON.stringify(rt))}catch{}},oe=K=>{Y.push(K),Y.length>zo&&Y.shift(),Y.length>=Nn?_():We||(We=setTimeout(_,Vo))},Te=h.role==="analysis"&&h.taskId.startsWith("draft::")?h.taskId.slice(7):null,Oe=new Set,ft=null;try{if(!c){x||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:M,finishedAt:new Date().toISOString()});return}if(!Pd(o,h.provider??null)){x||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${h.provider??"claude"}"`},startedAt:M,finishedAt:new Date().toISOString()});return}let K=mp(h.jobId);console.log(`[job] ${h.jobId} workspace=${K.dir}`);let X=G(h,r);v=X.gitCreds,j=X.contextGitCreds;let rt=v?.env,Fs=X.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:X.claudeOauthToken}:void 0,nt=[],Mr=null,Jo=null;try{let L=h.role==="build"?"clone":"worktree";nt=await ep(K.dir,h.projectId,h.projectRepos,L,rt,n);let D=await tp(K.dir,h.projectId,h.contextRepo,"worktree",rt,n);Jo=D,Mr=D?.workspacePath??null}catch(L){let D=L instanceof Error?L.message:String(L);console.warn(`[job] ${h.jobId} materialize failed: ${D}`),x||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${D}`},startedAt:M,finishedAt:new Date().toISOString()}),K.dispose();return}let Hs=async()=>{if(!h.deliveries||h.deliveries.length===0)return[];let L=h.contextRepo?.cloneUrl;if(!L||!rt)throw new Error(L?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let D=[];for(let V of h.deliveries){let q=nt.find(le=>le.name===V.name);if(q){if(h.role==="implement"&&V.baseSha&&V.baseSha!==q.baseSha){let le=await Xd(q,V.deliveryRef,V.deliverySha,V.baseSha,L,rt);console.log(`[job] ${h.jobId} ${q.name}: base moved ${V.baseSha.slice(0,10)} \u2192 ${q.baseSha.slice(0,10)} \u2014 re-applied delivery ${V.deliverySha.slice(0,10)} (${le.length} conflicted file(s))`),le.length>0&&D.push(`- **${q.name}**:`,...le.map(Gr=>` - \`${Gr}\``));continue}await Jd(q,V.deliveryRef,V.deliverySha,L,rt),console.log(`[job] ${h.jobId} ${q.name}: checked out delivery ${V.deliverySha.slice(0,10)} for ${h.role}`)}}return D},Xo=[];if(h.role==="build"||h.role==="implement"||h.role==="code-review")try{Xo=await Hs()}catch(L){let D=L instanceof Error?L.message:String(L);console.warn(`[job] ${h.jobId} delivery checkout failed: ${D}`),x||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${D}`},startedAt:M,finishedAt:new Date().toISOString()}),K.dispose();return}let Qo=h.role==="resolve-conflict"?h.metadata?.taskBranchByRepo??{}:{},Ks="";if(h.role==="resolve-conflict"){if(!nt.some(L=>Qo[L.name])){let L="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] ${h.jobId} ${L}`),x||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:L},startedAt:M,finishedAt:new Date().toISOString()}),K.dispose();return}try{let L=[];for(let D of nt){let V=Qo[D.name];if(!V)continue;let q=await ys(D,V,rt);console.log(`[job] ${h.jobId} ${D.name}: merged ${V} into ${D.ref} \u2014 ${q.length} conflicted file(s)`),q.length>0?L.push(`- **${D.name}**:`,...q.map(le=>` - \`${le}\``)):L.push(`- **${D.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Ks=`
|
|
666
667
|
|
|
667
668
|
## Conflicts to resolve
|
|
668
669
|
|
|
669
|
-
`+(
|
|
670
|
+
`+(L.length>0?L.join(`
|
|
670
671
|
`):"(no task branches to merge)")+`
|
|
671
|
-
`}catch(
|
|
672
|
+
`}catch(L){let D=L instanceof Error?L.message:String(L);console.warn(`[job] ${h.jobId} conflict merge failed: ${D}`),x||await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${D}`},startedAt:M,finishedAt:new Date().toISOString()}),K.dispose();return}}let em=Xo.length>0?`
|
|
672
673
|
|
|
673
674
|
## Base branch moved \u2014 conflicts to resolve
|
|
674
675
|
|
|
675
676
|
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:
|
|
676
677
|
|
|
677
|
-
`+
|
|
678
|
+
`+Xo.join(`
|
|
678
679
|
`)+`
|
|
679
|
-
`:"",
|
|
680
|
-
`).map(
|
|
681
|
-
`)}function E
|
|
682
|
-
[${
|
|
683
|
-
${
|
|
684
|
-
${e}`);let r=await Pk({message:"Authorization code \u2014 blank to skip"});if(hp(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=fp(r,t.state);return await gs({code:n,verifier:t.verifier,state:t.state,redirectUri:fs})}catch(n){return He.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function _k(t){if(di()?.claude?.oauthToken&&!t.farm)return He.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`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN==="0"||!process.stdout.isTTY)return null;He.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=pp(),n;try{n=await mp({...r,openUrl:$n,log:i=>He.message(i)})}catch(i){He.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await jk(r);if(s===null)return null;n=s}let o=await ur(n.oauthToken);return o==="invalid"?(He.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(He.success(`Claude: logged in \u2014 ${Ak(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function Nk(t){He.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.farm?`
|
|
685
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=Ek(await Ck({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||He.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`."),e):(He.warn(t.farm?"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`."),"")}var yp,wp=x(()=>{"use strict";us();on();te();gp();yp={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:_k,promptManual:Nk,validate:ur}});function kp(t){return yp}async function bp(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var $p=x(()=>{"use strict";wp()});async function Ir(t,e,r){return e.host==="github"?Lk(t,e,r):e.host==="gitlab"?Hk(t,e,r):Wk(t,e,r)}async function vp(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await At(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await xp(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await Et(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Sp(e.gitlabToken,t):o}}return e.bitbucket?(await Tr(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Rp(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 xp(t,e){let r=!1;try{r=(await At(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 Sp(t,e){let r=!1;try{r=(await Et(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function Rp(t,e){let r=!1;try{r=(await Tr(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}async function At(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(Ok+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 Lk(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 Dk(n,e,r),i=await Bk(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 Mk(n,o.owner,o.name,a.path,i)||await Gk(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 Dk(t,e,r){let n=await At(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 xp(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Uk(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 At(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 Uk(t,e){let{status:r,data:n}=await At(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Bk(t,e,r){let{data:n}=await At(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Mk(t,e,r,n,o){let{status:i,data:s}=await At(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Gk(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 At(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Et(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(Fk+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 Hk(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Et(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Sp(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Et(n,"GET","/user"),u={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let p=await Et(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 Et(n,"POST","/projects",u);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ar(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let m=(await Et(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let 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 Et(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 Tr(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let i=await fetch(Kk+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 Wk(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 Tr(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 Rp(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let f=await Tr(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);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 Tr(n,"GET",`${o}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let m of l)f.set(m.path,m.content);if((await Tr(n,"POST",`${o}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let d=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 Ok,Fk,Kk,Oo=x(()=>{"use strict";Gt();Ok="https://api.github.com";Fk="https://gitlab.com/api/v4";Kk="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=qk[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 qk,Lo=x(()=>{"use strict";qk={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as Yk}from"node:crypto";import{existsSync as Tp,mkdirSync as Vk,readFileSync as Ip,readdirSync as zk,rmSync as Do,writeFileSync as Jk}from"node:fs";import{homedir as Xk}from"node:os";import{dirname as Qk,join as hs}from"node:path";function Cp(){return hs(Xk(),".codepipe","init-drafts")}function ys(t){let e=Yk("sha256").update(t).digest("hex").slice(0,16);return hs(Cp(),`${e}.json`)}function Pp(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Zk)}function Ep(t){let e=ys(t);if(!Tp(e))return null;try{let r=JSON.parse(Ip(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Pp(r.savedAt)?(Do(e,{force:!0}),null):r}catch{return null}}function ws(t){Do(ys(t),{force:!0})}function Ap(){let t=Cp();if(Tp(t))for(let e of zk(t)){let r=hs(t,e);try{let n=JSON.parse(Ip(r,"utf-8"));Pp(n.savedAt)&&Do(r,{force:!0})}catch{Do(r,{force:!0})}}}var Zk,Cr,jp=x(()=>{"use strict";Zk=24*60*60*1e3;Cr=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(){ws(this.cwd)}persist(){let e=ys(this.cwd);Vk(Qk(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Jk(e,JSON.stringify(r,null,2)+`
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
`))
|
|
690
|
-
`)};m.
|
|
691
|
-
[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 bs=x(()=>{"use strict";je();Rr();$e();ct();Qi();Gt();fe();te();st();Sn()});import{existsSync as Pr,mkdirSync as Vp,readFileSync as zp,readdirSync as wb,writeFileSync as Jp}from"node:fs";import{join as Wt,resolve as Xp}from"node:path";import{setTimeout as vs}from"node:timers/promises";import{cancel as kb,confirm as Er,intro as Qp,isCancel as Mo,log as C,outro as xs,password as Rn,select as Ke,spinner as Rs,text as ie}from"@clack/prompts";import{simpleGit as Fo}from"simple-git";function ee(t){kb(t),process.exit(1)}function he(t){return Mo(t)&&ee("aborted"),t}function Q(t){return Mo(t)&&ee("aborted"),typeof t=="string"?t:""}async function Zp(t={}){Qp("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Ap();let r=Ep(e),n,o=!1;r&&Object.keys(r.answers).length>0?he(await Er({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(C.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Cr(e,r),o=!0):(ws(e),n=new Cr(e)):n=new Cr(e);let i=t.force===!0?null:await $s(e),s=await n.ask("target",async()=>he(await Ke({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?C.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||tf(e,t.force===!0));let c=await n.ask("hubUrl",async()=>Q(await ie({message:"HUB URL",placeholder:qe,initialValue:M("HUB_URL")??qe,validate:_=>_.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Ar()),{cliToken:d,accountEmail:f}=await n.ask("bootstrap",()=>jr(c,l)),u=null;s==="farm"&&(u=await bb(c,d));let m=a?vb(a.parsed.repoName):"",p=await n.ask("projectId",async()=>Q(await ie({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:_=>Lt.test(_.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await n.ask("projectName",async()=>Q(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 Ke({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 Ke({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 Ke({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",S=null,U,P=!0;if(v){let _,ne=Rs();ne.start("checking task-key prefixes on your account\u2026");try{_=await gu(c,d,{excludeProjectId:p}),ne.stop("prefixes checked")}catch{ne.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 Te=_a(ja(h),_);U=await n.ask("trackerPrefix",async()=>Q(await ie({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Te,initialValue:Te,validate:Oe=>{let ft=Oe.trim();if(!Xt.test(ft))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(_.has(ft.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else S=await n.ask("youtrack",()=>lf()),U=await n.ask("youtrackProjectKey",async()=>Q(await ie({message:"YouTrack project key",placeholder:"DEV",validate:_=>_.trim().length>0?void 0:"required"})).trim()),P=await n.ask("youtrackWrites",async()=>he(await Er({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",()=>Rb(E,l,a,{onCred:B,initial:n.get("reposPartial")??[],onProgress:_=>n.set("reposPartial",_)}));n.delete("reposPartial");let we=await Tb(await n.ask("contextRepo",()=>sf(p,pe,E,l)),p,pe,E,l,B,_=>n.set("contextRepo",_)),{spec:A,mode:g}=we,I;v||(C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),I=await n.ask("assigneeLogin",async()=>Q(await ie({message:"your YouTrack login (the assignee value)",...S?.login?{initialValue:S.login}:{},validate:_=>_.trim().length>0?void 0:"required"})).trim()));let k=await n.ask("llmProvider",async()=>{for(;;){if(he(await Ke({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";C.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),R=k==="claude"?await n.ask("claudeToken",()=>bp(kp("claude"),{farm:s==="farm"})):"",j;if(R){let _=await Gl(R);if(_){let ne=ia(_);ne&&(j=ne,C.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${ne} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let b={projectId:p,name:h,automationLevel:y,repos:pe,trackerProvider:w,youtrackProjectKey:U};C.step(`${g==="attach"?"attaching to":"provisioning"} Context Repo ${A.owner}/${A.name} (${A.host})\u2026`);let T;try{T=await Ir(b,A,{...af(E),youtrackWrites:P,...S?{trackerUrl:S.url}:{},mode:g,log:{info:_=>C.message(_),warn:_=>C.warn(_)}})}catch(_){ee(`Context Repo provisioning failed: ${_ instanceof Error?_.message:String(_)}`)}b.contextRepo=T,C.success(`Context Repo ready: ${T.owner}/${T.name}@${T.branch}`),C.step(`registering project on ${c}\u2026`);let K;try{K=await Rt(c,d,b)}catch(_){if(_ instanceof N&&_.status===409){C.warn(`project ${p} already exists on HUB \u2014 reusing it`);try{K=await V(c,d,p)}catch(ne){throw ne instanceof N&&ee(`HUB \u2192 ${ne.status} ${ne.message}`),ne}}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??T;C.success(`project ${K.projectId} ready (${K.provisioningStatus})`);let Re=await Ab(G),We=S?{url:S.url,token:S.token}:void 0;if(s==="farm"){let _=u,ne={...E,...Re?{contextWrite:Re}:{},...R?{claude:{oauthToken:R}}:{},...We?{youtrack:We}:{}},Te=E.github?.token;if(G.host==="github"&&Te)try{let z=Yu(`devpipe-${p}`);await Vu(G,Te,z.publicKey,`devpipe-${p}`),ne.contextSsh={privateKey:z.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(z){C.warn(`could not set up Context Repo SSH deploy key (${z instanceof Error?z.message:String(z)}); the farm will fall back to the token path.`)}let Oe={projectId:p,config:{hubUrl:c,cliToken:d,projectId:p},secrets:ne,contextRepo:G,projectConfig:Ze(b,P,S?.url,I||void 0,"auto",k,j)},ft=ut(_.farm.publicKey,JSON.stringify(Oe));C.step(`handing project ${p} to farm ${_.farm.name}\u2026`);let H;try{H=await $o(c,d,_.farm.farmId,{projectId:p,sealedBundle:ft})}catch(z){throw z instanceof N&&ee(z.status===409?`farm ${_.farm.name} is offline \u2014 start it and re-run.`:z.status===504?`farm ${_.farm.name} did not respond in time.`:`HUB \u2192 ${z.status} ${z.message}`),z}H.ok||ee(`farm rejected provisioning: ${H.error??"unknown error"}`),await Ss(c,d,p,G,Te,K.repos,null,E),n.clear(),xs(`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}cf(E),await rf(e,G.cloneUrl,G.branch),of(e),a&&await Sb(e);{let _=Wt(e,Je);ir(_);let ne=Ze(b,P,S?.url,I||void 0,$,k,j),Te=zr(_,ne);Te.length>0&&C.success(`local project config \u2192 .codepipe/{${Te.join(", ")}}`),Bt(p,ne,{info:Oe=>C.message(Oe),warn:Oe=>C.warn(Oe)})}await nf(e,K.repos);let qo={hubUrl:c,cliToken:d,projectId:p,...E,...Re?{contextWrite:Re}:{},...R?{claude:{oauthToken:R}}:{},...We?{youtrack:We}:{}};X(qo),at({hubUrl:c,cliToken:d,projectId:p,accountEmail:f},p),C.success(`secrets \u2192 ${Xe(p)}`),await Ss(c,d,p,G,E.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,K.repos,e,E),n.clear();let Nn=`${c}/?project=${encodeURIComponent(p)}`;$n(Nn),xs(`done. your project on the dashboard (sign in there to work with it):
|
|
680
|
+
`:"",tm=F(N(h.prompt,nt,Mr),Mr,h.taskId)+Ks+em,Zo=[...nt.map(L=>L.workspacePath),...Mr?[Mr]:[]];Zo.length>0&&console.log(`[job] ${h.jobId} --add-dir: ${Zo.join(", ")}`),Te&&(ft=setInterval(()=>{let D=f;if(!D||D.readyState!==D.OPEN)return;let V;try{V=Sk(Tr(K.dir,"drafts")).filter(q=>q.endsWith(".json")).sort()}catch{return}for(let q of V){if(Oe.has(q))continue;if(Oe.size>=Fa)break;let le;try{let Le=JSON.parse(yp(Tr(K.dir,"drafts",q),"utf-8")),Xt=typeof Le.localRef=="string"?Le.localRef:"",On=typeof Le.title=="string"?Le.title:"",ei=typeof Le.body=="string"?Le.body:"";if(!Xt||!On)continue;le={localRef:Xt,title:On,body:ei,...Le.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Le.links)?{links:Le.links}:{}}}catch{continue}Oe.add(q);let Gr={type:"child_draft",jobId:h.jobId,projectId:h.projectId,draftId:Te,child:le};try{D.send(JSON.stringify(Gr))}catch{}}},1500));try{let L={workspaceDir:K.dir,role:h.role,prompt:tm,addDirs:Zo,metadata:h.metadata??{},...h.model?{model:h.model}:{},...Fs?{env:Fs}:{},signal:S.abort.signal,onActivity:oe},D=S.chatInbox?await c.run({...L,interactive:{inbox:S.chatInbox.iterable}}):await Od(c,L,{jobId:h.jobId,policy:l,onBeforeRetry:async()=>{K.clean();for(let ee of nt)try{await qd(ee);let ue=Qo[ee.name];h.role==="resolve-conflict"&&ue&&await ys(ee,ue,rt)}catch(ue){let Fr=ue instanceof Error?ue.message:String(ue);console.warn(`[job] ${h.jobId} worktree reset failed (${ee.name}): ${Fr}`)}try{await Hs()}catch(ee){let ue=ee instanceof Error?ee.message:String(ee);console.warn(`[job] ${h.jobId} delivery re-checkout failed: ${ue}`)}},aborted:()=>x||S.paused}),V=[];if(Ck.has(h.role)&&nt.length>0){let ee=h.metadata??{},ue=typeof ee.commitMessage=="string"?ee.commitMessage:`${h.taskId}: changes`,Fr=h.contextRepo?.cloneUrl,qs=j?.env;if(!Fr||!qs)throw new Error("delivery requested but "+(Fr?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let rm=h.taskId.includes(":")?h.taskId.slice(h.taskId.indexOf(":")+1):h.taskId;for(let ot of nt){let Hr=await Yd(ot,ue);if(!Hr){console.log(`[job] ${h.jobId} ${ot.name}: no changes \u2014 no delivery`);continue}let ti=`codepipe/deliveries/${rm}/${h.jobId}/${ot.name}`;await Vd(ot,Hr,ti,Fr,qs),V.push({name:ot.name,deliveryRef:ti,deliverySha:Hr,baseSha:ot.baseSha}),console.log(`[job] ${h.jobId} ${ot.name}: delivered ${Hr.slice(0,10)} \u2192 ${ti}`);let Ys=await zd(ot,Hr);if(Ys.trim().length>0){let nm=Tr("display",`${ot.name}.diff`),Vs=Tr(K.dir,nm);xk(Ik(Vs),{recursive:!0}),Rk(Vs,Ys)}}}if(h.role==="resolve-conflict"&&V.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let q;h.role==="build"&&(q=op(K.dir),console.log(`[job] ${h.jobId} build verdict: ok=${q.ok}`+(q.failedStep?` failedStep=${q.failedStep}`:"")));let le;h.role==="code-review"&&(le=ap(K.dir),console.log(`[job] ${h.jobId} review verdict: approved=${le.approved}`));let Gr=D.artifactPaths.length>0?D.artifactPaths:K.listFiles(),Le=Array.from(new Set(Gr)),Xt;if(Jo)try{let ee=h.role==="index"?["adr/SOURCES.md"]:h.role==="backfill"?["adr"]:[],ue=await rp(Jo,ee);ue.length>0&&(Xt=ue,console.log(`[job] ${h.jobId} captured ${ue.length} knowledge file(s) for Context Repo`))}catch(ee){let ue=ee instanceof Error?ee.message:String(ee);console.warn(`[job] ${h.jobId} knowledge capture failed (non-fatal): ${ue}`)}let{artifacts:On,omitted:ei,dropped:Ws}=up(K.dir,Le);for(let ee of ei)console.warn(`[job] ${h.jobId} artifact ${ee.path} (${ee.bytes} bytes) exceeded upload budget \u2014 content omitted`);Ws.length>0&&console.warn(`[job] ${h.jobId} artifact listing truncated: ${Ws.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Ln={jobId:h.jobId,status:"succeeded",artifacts:On,...Xt?{contextWrites:Xt}:{},...V.length>0?{deliveries:V}:{},log:Pk(D.log),startedAt:M,finishedAt:new Date().toISOString(),usage:D.usage,...D.rateLimit?{rateLimit:D.rateLimit}:{},...q?{build:q}:{},...le?{review:le}:{}};if(x||S.paused)console.warn(`[job] ${h.jobId} skipping result upload \u2014 ${S.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await E.submitResult(Ln),console.log(`[job] ${h.jobId} done \u2014 uploaded ${Ln.artifacts.length} artifact(s):`);for(let ee of Ln.artifacts){let ue=Buffer.from(ee.contentBase64,"base64").length;console.log(` \xB7 ${ee.path} (${ue} bytes)`)}Ln.artifacts.length===0&&console.warn(`[job] ${h.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(L){let D=L instanceof Error?L.message:String(L);if(S.paused)console.log(`[job] ${h.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(x)console.warn(`[job] ${h.jobId} failed after claim lost (${D}) \u2014 skipping result upload`);else{let V=Nd(L),q=L instanceof Et,le=L instanceof pt;console.warn(V?`[job] ${h.jobId} failed: ${D} (Claude auth \u2014 token invalid/expired)`:q?`[job] ${h.jobId} failed: ${D} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:le?`[job] ${h.jobId} failed: ${D} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${h.jobId} failed: ${D}`),await E.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:D},startedAt:M,finishedAt:new Date().toISOString(),...V?{authError:!0}:{},...q?{buildInconclusive:!0}:{},...le?{reviewInconclusive:!0}:{}})}}finally{K.dispose()}}finally{clearInterval(I),ft&&clearInterval(ft),_(),S.chatInbox?.close(),g.delete(h.jobId),v?.cleanup(),j?.cleanup()}}function G(E,h){if(!E.credBundle)return{gitCreds:null,contextGitCreds:null};if(!h)return console.warn(`[job] ${E.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let S;try{S=JSON.parse(pr(h,E.credBundle).toString("utf-8"))}catch(A){return console.warn(`[job] ${E.jobId} failed to open credBundle: ${A instanceof Error?A.message:String(A)}`),{gitCreds:null,contextGitCreds:null}}let x=gs(S);x&&console.log(`[job] ${E.jobId} cred bundle opened \u2014 git creds configured`);let v=Bd(S,E.contextRepo.cloneUrl),j={gitCreds:x,contextGitCreds:v};return S.claudeOauthToken&&(j.claudeOauthToken=S.claudeOauthToken),j}function P(E,h){return E.split(`
|
|
681
|
+
`).map(S=>h+S).join(`
|
|
682
|
+
`)}function N(E,h,S){let x=h[0]?.workspacePath??"";return E.replace(/\{\{codeDir\}\}/g,x).replace(/\{\{codeRoot\}\}/g,x?x.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,S??"")}function F(E,h,S){let x=E,v=S.includes("::")?"":S.split(":",2)[1]??"",j=A=>{if(!h||!v)return"";try{return yp(Tr(h,"tasks",v,A),"utf-8").trim()}catch{return""}};if(x.includes("{{solutionMd}}")){let A=j("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";x=x.replace(/\{\{solutionMd\}\}/g,()=>A)}if(x.includes("{{taskDescription}}")){let A=j("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";x=x.replace(/\{\{taskDescription\}\}/g,()=>A)}return x}let fe=E=>{if(p)return;p=!0,console.log(`
|
|
683
|
+
[${E}] shutting down`),u.abort();let h=[...g.keys()];for(let v of g.values())v.abort.abort();let S=new AbortController,x=setTimeout(()=>S.abort(),3e3);(async()=>(await Promise.all(h.map(async v=>{try{await d.releaseJob(v,`sandbox ${E}`,S.signal),console.log(`[${E}] released job ${v}`)}catch(j){let A=j instanceof Error?j.message:String(j);console.warn(`[${E}] release failed: ${A} (sweeper will reclaim)`)}})),clearTimeout(x),w.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>fe("SIGINT")),process.on("SIGTERM",()=>fe("SIGTERM"));let Ne=[b("implementation")];e.planningLane!==!1?Ne.push(b("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(Ne)}var Lo,Ck,wp=T(()=>{"use strict";W();je();mi();Ed();Ld();ke();Ao();Md();us();np();ip();cp();dp();hp();Lo=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Ck=new Set(["implement","resolve-conflict"])});var Ir=T(()=>{"use strict";wd();wp();Ao()});import{cancel as Ak,isCancel as bp,log as He,password as jk,text as _k}from"@clack/prompts";function Nk(t){return bp(t)&&(Ak("aborted"),process.exit(1)),typeof t=="string"?t:""}function Ok(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function Lk(t){let e=Ti({redirectUri:Ri,challenge:t.challenge,state:t.state});He.message(`Open this URL, approve the access, and paste the code shown:
|
|
684
|
+
${e}`);let r=await _k({message:"Authorization code \u2014 blank to skip"});if(bp(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=el(r,t.state);return await Ii({code:n,verifier:t.verifier,state:t.state,redirectUri:Ri})}catch(n){return He.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function Dk(t){if(fi()?.claude?.oauthToken&&!t.farm)return He.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`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN==="0"||!process.stdout.isTTY)return null;He.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=eo(),n;try{n=await tl({...r,openUrl:Ft,log:i=>He.message(i)})}catch(i){He.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await Lk(r);if(s===null)return null;n=s}let o=await vt(n.oauthToken);return o==="invalid"?(He.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(He.success(`Claude: logged in \u2014 ${Ok(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function Uk(t){He.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.farm?`
|
|
685
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=Nk(await jk({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||He.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`."),e):(He.warn(t.farm?"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`."),"")}var $p,vp=T(()=>{"use strict";to();ir();re();Pi();$p={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:Dk,promptManual:Uk,validate:vt}});function xp(t){return $p}async function Sp(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Rp=T(()=>{"use strict";vp()});async function Pr(t,e,r){return e.host==="github"?Mk(t,e,r):e.host==="gitlab"?Yk(t,e,r):zk(t,e,r)}async function Tp(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 jt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ip(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 At(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Cp(e.gitlabToken,t):o}}return e.bitbucket?(await Cr(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Pp(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 Ip(t,e){let r=!1;try{r=(await jt(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 Cp(t,e){let r=!1;try{r=(await At(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 Pp(t,e){let r=!1;try{r=(await Cr(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 jt(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(Bk+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 Mk(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 Gk(n,e,r),i=await Hk(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=ur(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Kk(n,o.owner,o.name,a.path,i)||await Wk(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 Gk(t,e,r){let n=await jt(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 Ip(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Fk(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 jt(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 Fk(t,e){let{status:r,data:n}=await jt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Hk(t,e,r){let{data:n}=await jt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Kk(t,e,r,n,o){let{status:i,data:s}=await jt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Wk(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 jt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function At(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(qk+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 Yk(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 At(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 Cp(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await At(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(p.data?.username!==e.owner){let f=await At(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);u.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await At(n,"POST","/projects",u);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ur(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let g=(await At(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of g)l.add(f.path);if(g.length<100)break}let d=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return d.length>0?await At(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 Cr(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(Vk+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 zk(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 Cr(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 Pp(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let p=await Cr(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(p.status===404||!p.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=p.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ur(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await Cr(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let g of l)p.set(g.path,g.content);if((await Cr(n,"POST",`${o}/src`,{form:p})).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(p=>p.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 Bk,qk,Vk,Do=T(()=>{"use strict";Kt();Bk="https://api.github.com";qk="https://gitlab.com/api/v4";Vk="https://api.bitbucket.org/2.0"});function _e(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=Jk[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 Jk,Uo=T(()=>{"use strict";Jk={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as Xk}from"node:crypto";import{existsSync as Ep,mkdirSync as Qk,readFileSync as Ap,readdirSync as Zk,rmSync as Bo,writeFileSync as eb}from"node:fs";import{homedir as tb}from"node:os";import{dirname as rb,join as ks}from"node:path";function jp(){return ks(tb(),".codepipe","init-drafts")}function bs(t){let e=Xk("sha256").update(t).digest("hex").slice(0,16);return ks(jp(),`${e}.json`)}function _p(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=nb)}function Np(t){let e=bs(t);if(!Ep(e))return null;try{let r=JSON.parse(Ap(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:_p(r.savedAt)?(Bo(e,{force:!0}),null):r}catch{return null}}function $s(t){Bo(bs(t),{force:!0})}function Op(){let t=jp();if(Ep(t))for(let e of Zk(t)){let r=ks(t,e);try{let n=JSON.parse(Ap(r,"utf-8"));_p(n.savedAt)&&Bo(r,{force:!0})}catch{Bo(r,{force:!0})}}}var nb,Er,Lp=T(()=>{"use strict";nb=24*60*60*1e3;Er=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){$s(this.cwd)}persist(){let e=bs(this.cwd);Qk(rb(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};eb(e,JSON.stringify(r,null,2)+`
|
|
686
|
+
`,{mode:384})}}});function Dp(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 Up(){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 Bp(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 Mp=T(()=>{"use strict"});import{existsSync as ob}from"node:fs";import{join as ib}from"node:path";import{simpleGit as sb}from"simple-git";function ub(t){let e=t.split("/");return e[e.length-1]??t}function Gp(t){if(t.filter(r=>!cb.test(ub(r))).length>ab)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(lb.has(n))return!0}return!1}async function db(t){try{let r=(await sb(t).raw(["ls-files"])).split(`
|
|
687
|
+
`).map(n=>n.trim()).filter(Boolean);return Gp(r)}catch{return!1}}async function pb(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)?Gp(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Fp(t,e){for(let r of t)try{let n=e.localRoot!=null?ib(e.localRoot,r.mountAs??r.name):null;if(n&&ob(n)?await db(n):await pb(r,e.tokens))return!0}catch{}return!1}var ab,cb,lb,Hp=T(()=>{"use strict";ab=3,cb=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,lb=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Kp}from"node:fs";import{join as Wp}from"node:path";import{simpleGit as qp}from"simple-git";async function xn(t,e,r={}){let n=r.log??fb,o=[];for(let i of e){let s=Wp(t,i.mountAs),a=qa(i);if(!Kp(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 qp().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(d){let p=vn(d instanceof Error?d.message:String(d));n.warn(`clone failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}continue}if(!Kp(Wp(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=qp(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!mb(l,a)){n.warn(`${i.mountAs}/ origin (${vn(l)||"none"}) != expected (${vn(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:vn(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 p=vn(d instanceof Error?d.message:String(d));n.warn(`fetch failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}}return o}function mb(t,e){return Yp(t)===Yp(e)}function Yp(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function vn(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Vp(t={}){let e=Pe();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 xn(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 fb,Mo=T(()=>{"use strict";st();fb={info:t=>console.log(t),warn:t=>console.warn(t)}});var Jp={};im(Jp,{upCommand:()=>vs});import{spawn as gb}from"node:child_process";import{existsSync as zp}from"node:fs";import{homedir as hb,hostname as yb}from"node:os";import{join as Go}from"node:path";async function wb(t,e,r){let n=he(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Fe(e)} points at a different HUB (${n.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let o;try{o=await xu(t.hubUrl.replace(/\/$/,""),n.token)}catch(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.
|
|
688
|
+
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`),uc(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function kb(t,e,r){let n=he(e)!==null;if(!await wb(t,e,r))return;console.log(n?"[up] re-registering the worker \u2014 requesting an account-issued token from HUB":"[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await So(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof O&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof O&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof O?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await Wt({hub:t.hubUrl,token:o,name:r.name??`${yb()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function bb(t,e){let r=he(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=be(r.sealPublicKey);if(!U(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Vn(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 $b(t,e){let r=process.cwd(),n=Go(r,Je);if(Wn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(zp(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await J(t.hubUrl,t.cliToken,t.projectId)}catch(d){console.warn(`[up] could not fetch the project summary (${d instanceof Error?d.message:String(d)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Ss(r);if(!Wa(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=U(t.projectId),a={info:d=>console.log(d),warn:d=>console.warn(d)},c=await Po({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=Go(hb(),".codepipe",e?Go("profiles",e,"context-config"):"context-config");if(oo(c.contextDir,l,a),!zp(Go(c.contextDir,"project.yaml"))){cr(c.contextDir);let d={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Qr(c.contextDir,Ze(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 vs(t){let{cfg:e,profile:r}=Yn(t.profile);await $b(e,r),await kb(e,r,t),bb(e.projectId,r);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(g,f)=>{let m=y=>k=>{for(let w of k.toString("utf-8").split(`
|
|
689
|
+
`))w.length>0&&y.write(`${f} ${w}
|
|
690
|
+
`)};g.stdout?.on("data",m(process.stdout)),g.stderr?.on("data",m(process.stderr))},i=(g,f)=>{let m=gb(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(m,g),m};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=g=>{if(!l){l=!0,console.log(`
|
|
691
|
+
[up] ${g} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(g);setTimeout(()=>{for(let{name:f,child:m}of c)m.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),m.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>d("SIGINT")),process.on("SIGTERM",()=>d("SIGTERM"));let p=c.map(({name:g,child:f})=>new Promise(m=>{f.on("exit",(y,k)=>m({name:g,code:y??(k?1:0)}))})),u=await Promise.race(p);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),d("SIGTERM")),await Promise.all(p),process.exit(u.code)}var xs=T(()=>{"use strict";je();Ir();ve();ct();as();Kt();me();re();st();Sn()});import{existsSync as Ar,mkdirSync as Qp,readFileSync as Zp,readdirSync as vb,writeFileSync as ef}from"node:fs";import{join as Yt,resolve as tf}from"node:path";import{setTimeout as Rs}from"node:timers/promises";import{cancel as xb,confirm as jr,intro as rf,isCancel as Fo,log as C,outro as Ts,password as Rn,select as Ke,spinner as Cs,text as se}from"@clack/prompts";import{simpleGit as Ko}from"simple-git";function te(t){xb(t),process.exit(1)}function ye(t){return Fo(t)&&te("aborted"),t}function Z(t){return Fo(t)&&te("aborted"),typeof t=="string"?t:""}async function nf(t={}){rf("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Op();let r=Np(e),n,o=!1;r&&Object.keys(r.answers).length>0?ye(await jr({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(C.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Er(e,r),o=!0):($s(e),n=new Er(e)):n=new Er(e);let i=t.force===!0?null:await Ss(e),s=await n.ask("target",async()=>ye(await Ke({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?C.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||sf(e,t.force===!0));let c=await n.ask("hubUrl",async()=>Z(await se({message:"HUB URL",placeholder:qe,initialValue:B("HUB_URL")??qe,validate:_=>_.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>_r()),{cliToken:d,accountEmail:p}=await n.ask("bootstrap",()=>Nr(c,l)),u=null;s==="farm"&&(u=await Sb(c,d));let g=a?Tb(a.parsed.repoName):"",f=await n.ask("projectId",async()=>Z(await se({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:_=>Dt.test(_.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),m=await n.ask("projectName",async()=>Z(await se({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()=>ye(await Ke({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),k=s==="farm"?"auto":await n.ask("applyMode",async()=>ye(await Ke({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()=>ye(await Ke({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"}))),b=w==="internal",R=null,G,P=!0;if(b){let _,oe=Cs();oe.start("checking task-key prefixes on your account\u2026");try{_=await Su(c,d,{excludeProjectId:f}),oe.stop("prefixes checked")}catch{oe.stop("could not reach the HUB",1),te("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 Te=La(Oa(m),_);G=await n.ask("trackerPrefix",async()=>Z(await se({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Te,initialValue:Te,validate:Oe=>{let ft=Oe.trim();if(!Zt.test(ft))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(_.has(ft.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else R=await n.ask("youtrack",()=>ff()),G=await n.ask("youtrackProjectKey",async()=>Z(await se({message:"YouTrack project key",placeholder:"DEV",validate:_=>_.trim().length>0?void 0:"required"})).trim()),P=await n.ask("youtrackWrites",async()=>ye(await jr({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let N=n.get("tokens")??{},F=()=>n.set("tokens",N),fe=await n.ask("repos",()=>Pb(N,l,a,{onCred:F,initial:n.get("reposPartial")??[],onProgress:_=>n.set("reposPartial",_)}));n.delete("reposPartial");let Ne=await Eb(await n.ask("contextRepo",()=>uf(f,fe,N,l)),f,fe,N,l,F,_=>n.set("contextRepo",_)),{spec:E,mode:h}=Ne,S;b||(C.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),S=await n.ask("assigneeLogin",async()=>Z(await se({message:"your YouTrack login (the assignee value)",...R?.login?{initialValue:R.login}:{},validate:_=>_.trim().length>0?void 0:"required"})).trim()));let x=await n.ask("llmProvider",async()=>{for(;;){if(ye(await Ke({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";C.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),v=x==="claude"?await n.ask("claudeToken",()=>Sp(xp("claude"),{farm:s==="farm"})):"",j;if(v){let _=await Qc(v);if(_){let oe=ca(_);oe&&(j=oe,C.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${oe} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let A={projectId:f,name:m,automationLevel:y,repos:fe,trackerProvider:w,youtrackProjectKey:G};C.step(`${h==="attach"?"attaching to":"provisioning"} Context Repo ${E.owner}/${E.name} (${E.host})\u2026`);let $;try{$=await Pr(A,E,{...df(N),youtrackWrites:P,...R?{trackerUrl:R.url}:{},mode:h,log:{info:_=>C.message(_),warn:_=>C.warn(_)}})}catch(_){te(`Context Repo provisioning failed: ${_ instanceof Error?_.message:String(_)}`)}A.contextRepo=$,C.success(`Context Repo ready: ${$.owner}/${$.name}@${$.branch}`),C.step(`registering project on ${c}\u2026`);let I;try{I=await Tt(c,d,A)}catch(_){if(_ instanceof O&&_.status===409){C.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{I=await J(c,d,f)}catch(oe){throw oe instanceof O&&te(`HUB \u2192 ${oe.status} ${oe.message}`),oe}}else if(_ instanceof O&&_.status===401)n.delete("cliToken"),te("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(_ instanceof O)te(`HUB \u2192 ${_.status} ${_.message}`);else throw _}let M=I.contextRepo??$;C.success(`project ${I.projectId} ready (${I.provisioningStatus})`);let Y=await Ob(M),We=R?{url:R.url,token:R.token}:void 0;if(s==="farm"){let _=u,oe={...N,...Y?{contextWrite:Y}:{},...v?{claude:{oauthToken:v}}:{},...We?{youtrack:We}:{}},Te=N.github?.token;if(M.host==="github"&&Te)try{let X=rd(`devpipe-${f}`);await nd(M,Te,X.publicKey,`devpipe-${f}`),oe.contextSsh={privateKey:X.privateKey},C.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(X){C.warn(`could not set up Context Repo SSH deploy key (${X instanceof Error?X.message:String(X)}); the farm will fall back to the token path.`)}let Oe={projectId:f,config:{hubUrl:c,cliToken:d,projectId:f},secrets:oe,contextRepo:M,projectConfig:Ze(A,P,R?.url,S||void 0,"auto",x,j)},ft=ut(_.farm.publicKey,JSON.stringify(Oe));C.step(`handing project ${f} to farm ${_.farm.name}\u2026`);let K;try{K=await xo(c,d,_.farm.farmId,{projectId:f,sealedBundle:ft})}catch(X){throw X instanceof O&&te(X.status===409?`farm ${_.farm.name} is offline \u2014 start it and re-run.`:X.status===504?`farm ${_.farm.name} did not respond in time.`:`HUB \u2192 ${X.status} ${X.message}`),X}K.ok||te(`farm rejected provisioning: ${K.error??"unknown error"}`),await Is(c,d,f,M,Te,I.repos,null,N),n.clear(),Ts(`done. project ${f} is now hosted on farm ${_.farm.name} (daemon ${K.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}pf(N),await af(e,M.cloneUrl,M.branch),lf(e),a&&await Cb(e);{let _=Yt(e,Je);cr(_);let oe=Ze(A,P,R?.url,S||void 0,k,x,j),Te=Qr(_,oe);Te.length>0&&C.success(`local project config \u2192 .codepipe/{${Te.join(", ")}}`),Ht(f,oe,{info:Oe=>C.message(Oe),warn:Oe=>C.warn(Oe)})}await cf(e,I.repos);let Vo={hubUrl:c,cliToken:d,projectId:f,...N,...Y?{contextWrite:Y}:{},...v?{claude:{oauthToken:v}}:{},...We?{youtrack:We}:{}};z(Vo),at({hubUrl:c,cliToken:d,projectId:f,accountEmail:p},f),C.success(`secrets \u2192 ${Xe(f)}`),await Is(c,d,f,M,N.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,I.repos,e,N),n.clear();let Nn=`${c}/?project=${encodeURIComponent(f)}`;Ft(Nn),Ts(`done. your project on the dashboard (sign in there to work with it):
|
|
692
692
|
${Nn}
|
|
693
|
-
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:
|
|
693
|
+
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:zo}=await Promise.resolve().then(()=>(xs(),Jp));await zo({profile:void 0})}async function Is(t,e,r,n,o,i=[],s=null,a={}){let c=await Bp(n,o);if(!c){let p=!1;try{p=await Fp(i,{localRoot:s,tokens:a})}catch{p=!1}if(p){let u=Up(),g=await Ke({message:u.message,options:u.options,initialValue:u.initialValue});if(!Fo(g)&&g===u.proceedValue)try{let{jobId:f}=await mn(t,e,r,{reindex:!1,backfill:!0});C.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){C.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}}}let l=Dp(c),d=await Ke({message:l.message,options:l.options,initialValue:l.initialValue});if(!(Fo(d)||d!==l.proceedValue))try{let{jobId:p}=await mn(t,e,r,{reindex:l.reindex});C.success(`indexing queued (job ${p}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(p){C.warn(`could not start indexing: ${p instanceof Error?p.message:String(p)}. You can retry later \u2014 registration is not affected.`)}}async function Sb(t,e){let r;try{r=await bu(t,e)}catch(c){throw c instanceof O&&te(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&te("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=ye(await Ke({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=$o(i.farmId,i.publicKey)}catch(c){te(c instanceof Error?c.message:String(c))}return ye(await jr({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
694
694
|
${s}
|
|
695
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||
|
|
695
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||te("farm fingerprint not confirmed \u2014 aborting."),bo(i.farmId,s),{farm:i,fingerprint:s}}async function of(t){rf(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();sf(e,t.force===!0);let r=Z(await se({message:"HUB URL",initialValue:B("HUB_URL")??qe,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await _r(),{cliToken:o,accountEmail:i}=await Nr(r,n);C.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await J(r,o,t.projectId)}catch(u){throw u instanceof O&&te(`HUB \u2192 ${u.status} ${u.message}`),u}s.contextRepo||te(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await ff(),l={},d=new Set(s.repos.map(u=>u.host));d.add(s.contextRepo.host);for(let u of d){let g=s.repos.find(f=>f.host===u);await Ho(u,l,g?.owner??s.contextRepo.owner,n,g?.repoName)}pf(l),await af(e,s.contextRepo.cloneUrl,s.contextRepo.branch),lf(e);{let u=Yt(e,Je);cr(u);let g={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},f=Ze(g,!0,c?.url,void 0,"auto",s.llmProvider??ze),m=Qr(u,f);m.length>0&&C.success(`local project config \u2192 .codepipe/{${m.join(", ")}} (defaults \u2014 review and adjust)`),Ht(t.projectId,f,{info:y=>C.message(y),warn:y=>C.warn(y)})}await cf(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};z(p),at({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),C.success(`secrets \u2192 ${Xe(t.projectId)}`),await Is(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),Ts("done.")}function sf(t,e){if(!Ar(t)){Qp(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=vb(t).filter(o=>!r.has(o));n.length!==0&&(e||te(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Ss(t){if(!Ar(Yt(t,".git")))return null;try{let r=(await Ko(t).remote(["get-url","origin"])||"").toString().trim(),n=r?_e(r):null;return n?{parsed:n,defaultBranch:await Rb(t)}:null}catch{return null}}async function Rb(t){let e=Ko(t);try{let n=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(n)return n}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function Tb(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Dt.test(e)?e:""}function Ib(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Cb(t){let e=Yt(t,".gitignore"),r=Ar(e)?Zp(e,"utf-8"):"";if(Ib(r))return;if(!ye(await jr({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){C.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
|
|
696
696
|
`)?"":`
|
|
697
|
-
`;
|
|
697
|
+
`;ef(e,r+o+`
|
|
698
698
|
# codepipe workspace (added by \`codepipe init\`)
|
|
699
699
|
.codepipe/
|
|
700
|
-
`),C.success(`.codepipe/ added to ${
|
|
700
|
+
`),C.success(`.codepipe/ added to ${tf(e)}`)}async function _r(){let t="";try{t=(await Ko().raw(["config","--global","user.email"])||"").trim()}catch{}return Z(await se({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Nr(t,e){C.step(`connecting account ${e}`);let r;try{r=await Ru(t,e)}catch(s){throw s instanceof fn&&te(`${e} is not authorized on this HUB yet.
|
|
701
701
|
Sign up at ${t} (registration form on the login screen),
|
|
702
702
|
wait for the operator to approve it by email, then re-run
|
|
703
|
-
\`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(
|
|
703
|
+
\`codepipe init\` with the same email.`),s}r.accountCreated&&C.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&C.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Ft(r.authorizeUrl),C.message(`a browser tab was opened to confirm this CLI:
|
|
704
704
|
${r.authorizeUrl}
|
|
705
705
|
`+(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
|
|
706
|
-
otherwise use the emailed link the page offers.`))),r.approvalRequired&&C.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),C.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await
|
|
707
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
706
|
+
otherwise use the emailed link the page offers.`))),r.approvalRequired&&C.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),C.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await Tu(t,r.requestId)}catch(a){C.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Rs(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&C.message(`connected as ${a} (the account confirmed in the browser).`),C.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&te("the HUB rejected this account"),s.status==="expired"&&te("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,C.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
707
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Rs(5e3);continue}await Rs(2e3)}te("bootstrap timed out")}async function af(t,e,r){let n=Yt(t,Je);if(Ar(Yt(n,".git"))){C.message(`${n} already cloned \u2014 skipping`);return}Ar(n)&&te(`${n} exists but is not a git repo \u2014 remove it and re-run`),Qp(n,{recursive:!0}),C.step(`cloning Context Repo \u2192 ${n}`);try{await Ko().clone(e,n,["--branch",r]),C.success(`cloned ${e}`)}catch(o){te(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function cf(t,e){if(e.length===0)return;C.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await xn(t,r,{log:{info:o=>C.message(o),warn:o=>C.warn(o)}});for(let o of n)C.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function lf(t){let e=Yt(t,Je,".gitignore"),r="";if(Ar(e)&&(r=Zp(e,"utf-8")),Xp.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
|
|
708
708
|
`)||r.length===0?"":`
|
|
709
|
-
`,i=
|
|
709
|
+
`,i=Xp.join(`
|
|
710
710
|
`)+`
|
|
711
|
-
`;
|
|
712
|
-
`:"")+i),C.message(`appended runtime entries to ${
|
|
711
|
+
`;ef(e,r+o+(r?`
|
|
712
|
+
`:"")+i),C.message(`appended runtime entries to ${tf(e)}`)}async function Pb(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;C.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Ho(s.host,t,s.owner,e,s.repoName),i?.();let c=Z(await se({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=Z(await se({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(;ye(await jr({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=Z(await se({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||_e(g)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=_e(a);C.message(`${c.host}: ${c.owner}/${c.repoName}`),await Ho(c.host,t,c.owner,e,c.repoName),i?.();let l=Z(await se({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:g=>g.trim().length>0?void 0:"required"})).trim(),d=Z(await se({message:"default branch (optional)",placeholder:"main"})).trim(),p=Z(await se({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),p&&p!==l&&(u.mountAs=p),o.push(u),n.onProgress?.(o)}return o}async function uf(t,e,r,n){C.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=ye(await Ke({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&C.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=Z(await se({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:it(t),validate:d=>{let p=(d??"").trim();if(!p)return"required";if(!_e(p)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(p))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=_e(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Ab(),l=Z(await se({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),d=Z(await se({message:"Context Repo name",placeholder:it(t),initialValue:it(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:d}}return{spec:a,mode:o}}function df(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??nr()}}async function Eb(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Ho(c.host,n,c.owner,o),i?.();let d=Cs();d.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await Tp(c,df(n),{explain:l==="attach"});if(p.found===!0)return d.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(p.found==="unknown")return d.stop(`could not check ${c.owner}/${c.name} (${p.detail}) \u2014 continuing`,1),a;if(l==="create")return d.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;d.stop(p.detail,1);let u=ye(await Ke({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"&&te("aborted"),u==="create")return a={spec:c,mode:"create"},s(a),a;a=await uf(e,r,n,o),s(a)}}async function Ab(){return ye(await Ke({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Tn(t,e){let r=Cs();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 pf(t){an(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),cn(t.gitlab?.token??process.env.GITLAB_TOKEN),ln(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Ho(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await jb(r);i?e.github=i:C.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await _b(r,n,o);i?e.bitbucket=i:C.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await Nb();i?e.gitlab=i:C.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function jb(t){for(;;){let e=Z(await Rn({message:`GitHub PAT \u2014 blank to skip
|
|
713
713
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
714
714
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
715
715
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
716
716
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
717
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Tn("GitHub",()=>
|
|
717
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Tn("GitHub",()=>ht(e,t?{owner:t}:void 0)))return{token:e};C.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function _b(t,e,r){for(C.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
718
718
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
719
719
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
|
|
720
720
|
read:repository:bitbucket + write:repository:bitbucket +
|
|
721
721
|
read:pullrequest:bitbucket + write:pullrequest:bitbucket
|
|
722
722
|
\u2014 write scopes do NOT include read: pick BOTH scopes of each pair
|
|
723
723
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
724
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let n=
|
|
725
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Tn("GitLab",()=>
|
|
724
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let n=Z(await se({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=Z(await Rn({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){C.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Tn("Bitbucket",async()=>{let i=await yt(n,o,t);if(t&&r){let s=await Zn(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};C.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Nb(){for(;;){let t=Z(await Rn({message:`GitLab PAT \u2014 blank to skip
|
|
725
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Tn("GitLab",()=>wt(t))){let e=await bc(t);return e&&C.warn(e),{token:t}}C.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Ob(t){if(ye(await jr({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
726
726
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
727
727
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
728
728
|
your trusted network.`,initialValue:!1})))for(t.host==="github"?C.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
729
729
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
730
730
|
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):C.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
731
|
-
(${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=
|
|
732
|
-
`),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
|
|
733
|
-
`),a=s.findIndex(
|
|
734
|
-
`).replace(/^\n+/,""),y=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${
|
|
731
|
+
(${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=Z(await Rn({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Tn("contextWrite",()=>Lb(r,t)))return{token:r};C.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Lb(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 ff(){for(;;){let t=Z(await se({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=Z(await Rn({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Tn("YouTrack",()=>$t({baseUrl:t,token:e}))){let r=await Nc({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}C.warn("re-enter the YouTrack URL / token.")}}var Xp,Sn=T(()=>{"use strict";ke();W();je();Rp();to();ve();ct();Kt();ir();Do();ss();Uo();kt();Gt();Lp();me();Mp();Hp();Zi();mo();re();Mo();st();Xp=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});W();ke();ve();import{Command as q$}from"commander";Hn();import{homedir as Xa}from"node:os";import{join as Qa}from"node:path";function Za(){Bt(Qa(Xa(),".devpipe"),Qa(Xa(),".codepipe"))}ve();re();async function pc(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 ${tr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");at({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...U(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};z(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${tr(e)}`)}mi();ve();import{homedir as cs}from"node:os";import{join as hn}from"node:path";ke();W();import{existsSync as Zu,rmSync as Gy}from"node:fs";import{join as gn}from"node:path";import{simpleGit as Fy}from"simple-git";import"ws";ke();re();import{createHash as Mm}from"node:crypto";import{existsSync as Gm,readFileSync as Fm}from"node:fs";import{homedir as Hm,hostname as gi}from"node:os";import{join as Km}from"node:path";function hc(t){return Mm("sha256").update(t).digest("hex").slice(0,12)}function Wm(){let t=B("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Km(Hm(),".claude","credentials.json");if(!Gm(e))return;let r=JSON.parse(Fm(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 yc(t){let e=Wm(),r=B("ACCOUNT_ID")?.trim(),n=B("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=rr(t);return o?{accountId:`acct-${hc(o)}`,label:n||gi(),...e?{email:e}:{}}:{accountId:`acct-${hc(`host:${gi()}`)}`,label:n||gi(),...e?{email:e}:{}}}ke();ir();re();Pi();async function rl(t,e,r,n,o){let i=c=>{e.readyState===e.OPEN&&e.send(JSON.stringify(c))},s=c=>i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,error:c});if(B("ORIGIN")==="farm"||B("CLAUDE_AUTOLOGIN")==="0"){s("autologin_disabled");return}let a;try{a=await Ci(eo())}catch(c){s(`listener failed: ${c instanceof Error?c.message:String(c)}`);return}i({type:"agent_login_url",requestId:r.requestId,projectId:t.projectId,authUrl:a.authUrl}),n.info(`[agent-auth] authorize Claude in a browser on THIS machine: ${a.authUrl}`),n.info(`[agent-auth] waiting for the redirect on ${a.redirectUri} \u2026`);try{let c=await a.waitForToken(),l=await vt(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let d=U(t.projectId);if(!d){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}d.claude={oauthToken:c.oauthToken},z(d),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}ke();function nl(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?B("ORIGIN")==="farm"||B("CLAUDE_AUTOLOGIN")==="0"||e?"none":"open":r?.ok===!0?"rearm":"none"}function ol(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}to();import{existsSync as hg}from"node:fs";import{join as yg}from"node:path";import{simpleGit as wg}from"simple-git";async function il(t,e){if(!hg(yg(t,".git")))return{status:"skipped"};let r=wg(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${kg(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 kg(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Ai,readFileSync as ul,readdirSync as vg,watch as xg}from"node:fs";import{join as Xr}from"node:path";W();import{existsSync as sl,readFileSync as al,readdirSync as bg,statSync as $g}from"node:fs";import{join as Ei}from"node:path";import{parse as cl}from"yaml";function ro(t){let e=Ei(t,"actions"),r=[],n=[];if(!sl(e))return{defs:r,errors:n};let o;try{o=bg(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=Ei(e,s);try{if(!$g(a).isFile())continue;let c=fa(s,cl(al(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 ll(t){let e={},r=Ei(t,"project.yaml");if(!sl(r))return e;let n;try{n=cl(al(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)||mt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var no=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,Xr(this.contextDir,"prompts"),Xr(this.contextDir,"actions")];for(let n of r)if(Ai(n))try{let o=xg(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=ro(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=Xr(this.contextDir,e);if(!Ai(r))return null;try{return ul(r,"utf-8")}catch{return null}}readPrompts(){let e=Xr(this.contextDir,"prompts"),r={};if(!Ai(e))return r;let n;try{n=vg(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=ul(Xr(e,o),"utf-8")}catch{}}return r}};St();import{existsSync as Bi,readFileSync as yl,readdirSync as Og}from"node:fs";import{join as wl}from"node:path";import{simpleGit as Lg}from"simple-git";var Dg=/^(\d{4})-(.+)\.md$/,Ug="0000-template.md";function Bg(t){let e=t.split(`
|
|
732
|
+
`),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 Mg(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
733
|
+
`),a=s.findIndex(k=>k.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),d=[],p="",u=null,g=a>=0?a+1:0;for(let k=g;k<s.length;k++){let w=(s[k]??"").trim();if(w===""){g=k+1;continue}let b=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(w);if(!b)break;let R=(b[1]??"").trim().toLowerCase(),G=(b[2]??"").trim(),P=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(w);P&&(u=parseInt(P[1]??"",10)),R==="tasks"&&(p=G),l.has(R)||d.push(w),g=k+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,m=s.slice(g).join(`
|
|
734
|
+
`).replace(/^\n+/,""),y=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...d,"",m].join(`
|
|
735
735
|
`);return{content:y.endsWith(`
|
|
736
736
|
`)?y:y+`
|
|
737
|
-
`,supersedes:u}}function
|
|
737
|
+
`,supersedes:u}}function Gg(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
|
|
738
738
|
|
|
739
|
-
- **Status:** superseded by ADR-${r}`):n}function
|
|
739
|
+
- **Status:** superseded by ADR-${r}`):n}function Fg(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(`
|
|
740
740
|
`)+`
|
|
741
|
-
`}async function
|
|
742
|
-
`)}async function
|
|
743
|
-
${l.trim()}`)}}let i=
|
|
744
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function
|
|
745
|
-
${w.trim()}`)}}let
|
|
746
|
-
`).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
|
|
747
|
-
`,o.length>
|
|
748
|
-
`))!==-1;)o(
|
|
749
|
-
`)}function
|
|
750
|
-
`)){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=
|
|
741
|
+
`}async function kl(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Lg(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 k=de(t,i(y));if(!Bi(k)){a.push(y);continue}s.push({slug:y,content:yl(k,"utf-8")})}let c=wl(t,"adr"),l=new Map;if(Bi(c))for(let y of Og(c)){let k=Dg.exec(y);!k||y===Ug||l.set(y,{num:parseInt(k[1]??"",10),slug:k[2]??"",content:yl(wl(c,y),"utf-8")})}let d=Math.max(0,...[...l.values()].map(y=>y.num))+1,p=new Map,u=[],g=[];for(let y of s){if([...l.entries()].find(([,P])=>P.slug===y.slug&&P.content.includes(e))){g.push(y.slug);continue}let w=d++,b=`${String(w).padStart(4,"0")}-${y.slug}.md`,{content:R,supersedes:G}=Mg(y.content,w,y.slug,e,n);if(p.set(b,R),l.set(b,{num:w,slug:y.slug,content:R}),u.push(`adr/${b}`),G!==null){let P=[...l.keys()].find(N=>N.startsWith(`${String(G).padStart(4,"0")}-`));if(P&&P!==b){let N=Gg(p.get(P)??l.get(P).content,w);p.set(P,N),l.set(P,{...l.get(P),content:N})}}}let f=[];if(o==="staging")for(let y of s)Bi(de(t,`adr/DRAFT-${y.slug}.md`))&&f.push({path:`adr/DRAFT-${y.slug}.md`,content:"",deleted:!0});if(u.length===0&&f.length===0)return{promoted:u,skipped:g,missing:a};if(u.length>0){let y=[...l.entries()].map(([k,w])=>({num:w.num,file:k,header:Bg(w.content)}));p.set("INDEX.md",Fg(y))}for(let[y,k]of p.entries())f.push({path:`adr/${y}`,content:k});let m=u.length>0?`adr(${e}): promote ${s.map(y=>y.slug).join(", ")}`:`adr(${e}): drop stale staged ${g.join(", ")}`;return await lt(t,f,m),{promoted:u,skipped:g,missing:a}}St();ct();W();import{existsSync as bl,readFileSync as Kg}from"node:fs";import{join as $l}from"node:path";function Wg(t){for(let e of[Ve,Kr]){let r=$l(t,e);if(bl(r))try{return Qs(Kg(r,"utf-8"))}catch{return 0}}return 0}function qg(t,e,r,n=3){let o=e<n,i=o?Zs(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function co(t,e){return qg(e,Wg(t),r=>bl($l(t,r)))}W();kt();import{existsSync as Al,mkdirSync as yh,mkdtempSync as wh,rmSync as jl,writeFileSync as _l}from"node:fs";import{tmpdir as kh}from"node:os";import{dirname as bh,join as uo}from"node:path";import{simpleGit as Hi}from"simple-git";Kt();function $h(t){return`codepipe/context-migration-v${t}`}function vh(t){let e=ea(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 \`${Ve}\` stamp (renamed from \`${Kr}\``,"when the legacy file is present). Hand-edited files are never touched.","","## Format changes",""];for(let n of e){r.push(`- **v${n.version}** \u2014 ${n.summary}`);for(let o of n.addedPaths)r.push(` - \`${o}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
|
|
742
|
+
`)}async function Nl(t,e,r,n){let o=Hi(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=co(t,e);if(!i.outdated)return i;let s=$h(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 xh(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 p=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:vh(i)});return n.info(`[ctx] migration PR opened: ${p.url}`),{...i,migrationPrUrl:p.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 xh(t,e,r,n,o,i,s){let a=Hi(t),c=wh(uo(kh(),"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`},p=new Map(ur(l,d).map(m=>[m.path,m.content])),u=0;for(let m of n.missingPaths){if(m===Ve)continue;let y=p.get(m);if(y==null){s.warn(`[ctx] migration: no template for ${m} \u2014 skipped`);continue}let k=uo(c,m);Al(k)||(yh(bh(k),{recursive:!0}),_l(k,y),u++)}_l(uo(c,Ve),Un(n.currentVersion)),u++;let g=uo(c,Kr);Al(g)&&(jl(g,{force:!0}),u++);let f=Hi(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${u} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),jl(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as Sh,readFileSync as Rh,writeFileSync as Th}from"node:fs";import{homedir as Ih}from"node:os";import{join as Ol}from"node:path";import{parseDocument as Ch}from"yaml";function Ph(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 Eh(t,e){let r=Ch(t);return r.set("repos",e.map(Ph)),r.toString()}function Ah(t,e){let r=[Ol(Ih(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Ol(e,"project.yaml")),r}function rn(t,e,r){let n=[],o=[];for(let i of Ah(t,r))if(Sh(i))try{let s=Rh(i,"utf-8"),a=Eh(s,e);a!==s&&(Th(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 jh}from"node:os";import{existsSync as _h,mkdirSync as Nh}from"node:fs";import{join as Ki}from"node:path";import{simpleGit as Wi}from"simple-git";var Ll=t=>console.log(t);function Dl(t){Ll=t}function nn(t,e="info"){Ll(t,e)}function xe(t,e,r){let n=r??Ki(jh(),".codepipe","repos");return Ki(n,t,e)}async function dr(t,e,r={}){let n=xe(t,e.name,r.baseDir),o=r.cloneUrlOverride??sn(e);if(!_h(Ki(n,".git"))){Nh(n,{recursive:!0});let a=Wi();nn(`[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}
|
|
743
|
+
${l.trim()}`)}}let i=Wi(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
|
|
744
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function on(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var Ul=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function po(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&&nn(`[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 on(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await on(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([...Ul,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Bl(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await on(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await on(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 Ml(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:d,force:p}=r,u=await Bl(t,i,()=>po(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let g=`origin/${c}`;if(await on(t,g)||(g=`origin/${d??c}`),(await t.revparse([g])).trim()===s)await t.raw(["branch","-f",a,u]),await t.checkout(a);else{await t.checkout(["-B",a,g]);try{await t.raw([...Ul,"cherry-pick",u])}catch(k){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let w=k instanceof Error?k.message:String(k);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
745
|
+
${w.trim()}`)}}let m=(await t.revparse(["HEAD"])).trim(),y=r.push!==!1;if(y){let k=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(k)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:m,pushed:y}}async function Gl(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 Fl(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,d=await Bl(t,i,()=>po(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 Hl(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 sn(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 Kl(t){return(await Wi().listRemote(["--heads",t])).split(`
|
|
746
|
+
`).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 Wl(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}je();re();function Mh(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 Jl(t,e,r,n){let o=Mh(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=Vn(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=ut(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}je();re();kt();Gt();ir();mo();function eu(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=fo();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},z(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:be(e.sealKey.publicKey)}}async function tu(t,e,r,n){let o;try{o=JSON.parse(pr(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=U(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await ht(o.token);return i.github={token:o.token},fr(i,()=>{process.env.GH_TOKEN=o.token,Xl(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await wt(o.token);return i.gitlab={token:o.token},fr(i,()=>{process.env.GITLAB_TOKEN=o.token,Ql(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 yt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},fr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Zl(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await $t({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},fr(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 vt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},fr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},fr(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 fr(t,e){z(t),e()}W();W();import{spawn as Gh}from"node:child_process";var Fh=124,ru=16*1024,nu=4e3;function Hh(t,e,r,n,o,i){let s={...t},a=(c,l)=>{mt(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 ou(t){let{def:e,onEvent:r}=t,n=Hh(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
747
|
+
`,o.length>ru&&(o=o.slice(o.length-ru))},s=(a,c)=>{let l=c.length>nu?c.slice(0,nu)+"\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 Kh(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 Kh(t,e,r,n,o){return new Promise(i=>{let s=Gh("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??pa)*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=g=>{let f="";return{data:m=>{f+=m.toString("utf-8");let y;for(;(y=f.indexOf(`
|
|
748
|
+
`))!==-1;)o(g,f.slice(0,y).replace(/\r$/,"")),f=f.slice(y+1)},flush:()=>{f.length>0&&o(g,f.replace(/\r$/,"")),f=""}}},p=d("stdout"),u=d("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",u.data),s.on("error",g=>{clearTimeout(l),o("stderr",`spawn failed: ${g.message}`),i(127)}),s.on("close",(g,f)=>{clearTimeout(l),p.flush(),u.flush(),i(a?Fh:g??(f?1:0))})})}St();import{existsSync as Wh,readFileSync as qh,statSync as iu}from"node:fs";var su=2*1024*1024;function Yh(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function au(t,e){let r=de(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!Wh(r)||!iu(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=iu(r);if(n>su)throw new Error(`file too large: ${e} is ${n} bytes (limit ${su})`);let o=qh(r);return Yh(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}re();W();import{existsSync as Vh,readFileSync as zh,writeFileSync as Jh}from"node:fs";import{join as Xh}from"node:path";import{parseDocument as Qh}from"yaml";async function cu(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=ka(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=Xh(t,o);if(!Vh(s))throw new Error(`${o} not found in context repo (${t})`);let a=Qh(zh(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);Jh(s,a.toString()),n.push(o)}return{files:n}}W();import{existsSync as Zh,readFileSync as ey,writeFileSync as ty}from"node:fs";import{join as ry}from"node:path";import{isMap as lu,parseDocument as ny}from"yaml";async function uu(t,e){let r=e.repoName?.trim(),n=e.defaultBranch?.trim();if(!r)throw new Error("repoName must be a non-empty string");if(!n||!Ra(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=ry(t,"project.yaml");if(!Zh(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=ny(ey(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>lu(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!lu(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),ty(o,i.toString()),{repoName:r,defaultBranch:n}}import{existsSync as Vi,readFileSync as zi,writeFileSync as oy}from"node:fs";import{join as go}from"node:path";import{parseDocument as Ji}from"yaml";async function du(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=go(t,"project.yaml");if(!Vi(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Ji(zi(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=go(t,"regimen.yaml");if(!Vi(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Ji(zi(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)oy(go(t,i.path),i.content);return{files:r.map(i=>i.path)}}function ho(t){if(!t)return"Stage";try{let e=go(t,"project.yaml");if(!Vi(e))return"Stage";let n=Ji(zi(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 mu,readFileSync as gu}from"node:fs";import{join as hu}from"node:path";import{parseDocument as yu}from"yaml";Gt();var un=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Wc(this.cfg,e)}getIssue(e,r){return qc(this.cfg,e,r??ho(this.contextDir))}listComments(e,r){return Yc(this.cfg,e,r)}downloadAttachment(e){return Kc(this.cfg,e)}updateStatus(e,r){return Oc(this.cfg,e,r,ho(this.contextDir))}addComment(e,r,n){return Lc(this.cfg,e,r)}createIssue(e){return Bc(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,ho(this.contextDir))}editIssue(e,r){return Dc(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Mc(this.cfg,e,r,n)}fetchStateFields(e){return zc(this.cfg,e)}};W();St();import{existsSync as dy,readFileSync as py}from"node:fs";import{randomBytes as fy}from"node:crypto";import{existsSync as pu,readFileSync as iy,readdirSync as sy}from"node:fs";W();St();function yo(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=uy(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:ay(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:ly(cy(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 wo(t,e,r){if(r.length===0)return;let n=yo(t,e,r),o=r.map(i=>i.issue.key);await lt(t,n,`sync(${o.join(", ")}): task data`)}function ay(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(`
|
|
749
|
+
`)}function cy(t,e,r){let n=new Map,o=de(t,`tasks/${e}/comments.jsonl`);if(pu(o))for(let i of iy(o,"utf-8").split(`
|
|
750
|
+
`)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Qt(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function ly(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
751
751
|
`)+(t.length>0?`
|
|
752
|
-
`:"")}function
|
|
752
|
+
`:"")}function uy(t,e,r){let n=[],o=de(t,`tasks/${e}/attachments`);if(pu(o))for(let i of sy(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}lo();var dn=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Zr(this.contextDir);let r=e.columns??[];return Cl(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>tn(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=en(this.contextDir,e);return r?tn(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return fu(this.contextDir,e).map(n=>({id:n.id,issueId:e,author:n.author,body:n.body,createdAt:n.createdAt}))}async downloadAttachment(e){throw new Error(`internal tracker: no remote attachments (${e})`)}async updateStatus(e,r){await this.mutateRecord(e,n=>({...n,status:r}))}async addComment(e,r,n){if(await Zr(this.contextDir),!en(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${fy(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Qt(r);s&&(i.parsedCommand=s);let c=[...fu(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
|
|
753
753
|
`)+`
|
|
754
|
-
`;return await lt(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
|
|
755
|
-
`)){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}ao();function Fi(t){if(!t)return"youtrack";try{let e=au(t,"project.yaml");return iu(e)&&cu(su(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function et(t){let e=Fi(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=Bc(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=ry(n);return i?{ok:!0,kind:e,provider:new un(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=vl();return r?{ok:!0,kind:e,provider:new ln(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function ry(t){try{let e=au(t,"project.yaml");if(!iu(e))return null;let r=cu(su(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var yo=new Map;async function dn(t,e){let n=(yo.get(t)??Promise.resolve()).catch(()=>{}).then(e);yo.set(t,n);try{return await n}finally{yo.get(t)===n&&yo.delete(t)}}async function lu(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;en(`[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 dn(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await Zc(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 re({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 dn(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir);return await el(s,a,{branchName:e.branchName,force:e.force}),re({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 dn(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await tl(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return re({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return F("no repo spec");let i=Be(r),s=await i.createPullRequest(r,e);return re({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 re({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),re({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return dn(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{mergedSha:c}=await rl(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return re({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return F("no repo spec");let i=t.cloneUrlOverride??rn(r),a=(await nl(i)).filter(d=>ol(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 re({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),re({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=et({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),re({issueId:t.trackerIssueId,newStatus:e.newStatus})):F("no tracker_issue_id provided"):F(i.error)}case"tracker_comment":{let i=et({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 re({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=et({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 re({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=et({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 re({applied:s})}case"set_project_setting":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await Zl(t.contextDir,e.edits);return re({files:i.files})}case"tracker_edit":{let i=et({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 ho(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),re({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await ru(t.contextDir,e);return re({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await tu(t.contextDir,e);return re({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),re({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 re({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}=Qn(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=da(c,e.input);if(!l.ok)return F(l.error);let d=kc(t.contextDir),f=D(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),dn(`${e.projectId}/${r.name}`,async()=>{await cr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=ve(e.projectId,r.name,t.baseDir),p=await zl({cwd:m,def:c,input:l.values,variables:d,secrets:f?.secrets??{},credEnv:u,onEvent:h=>i(e.runId,h)});return re({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=Ql(t.contextDir,e.path);return re({path:e.path,...i})}default:return F(`unsupported action type: ${e.type}`)}}catch(i){return F(i instanceof Error?i.message:String(i))}}function re(t){return{status:"done",result:t}}function F(t){return{status:"failed",error:t}}je();Ki();fe();te();import{existsSync as Tu,readFileSync as Iu}from"node:fs";import{join as Cu}from"node:path";async function Pu(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=ke(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");ko(e.farmId,e.farmPublicKey);let s=D(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await V(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=Cu(r,"project.yaml"),m=Cu(r,"regimen.yaml");Tu(u)&&Tu(m)?c={projectYaml:Iu(u,"utf-8"),regimenYaml:Iu(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=ut(e.farmPublicKey,JSON.stringify(l));wo(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await $o(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))}}je();Pe();je();import{homedir as my}from"node:os";import{existsSync as gy,mkdirSync as hy,readFileSync as yy,writeFileSync as wy}from"node:fs";import{dirname as ky,join as by}from"node:path";function Yi(){return M("RUNNER_PINS")??by(my(),".codepipe","runner-pins.json")}function Eu(){let t=Yi();if(!gy(t))return{};try{return JSON.parse(yy(t,"utf-8"))}catch{return{}}}function $y(t){let e=Yi();hy(ky(e),{recursive:!0}),wy(e,JSON.stringify(t,null,2)+`
|
|
756
|
-
`,{mode:384})}function vy(t){return Eu()[t]}function Vi(t,e){let r=Eu();r[t]=e,$y(r)}function Au(t,e){let r=ke(e),n=vy(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 ${Yi()}.`);return r}fe();te();var _u=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function ju(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:_u(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 xy={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:_u(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)=>ju(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>ju(t,e,r,"remove-token")},Nu={api:xy,fetchProject:V,provisionOnRunner:pu,teardownOnRunner:fu};async function Ou(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(ke(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Au(e.runnerId,e.runnerPublicKey);let i=D(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).filter(c=>c.host==="github");if(a.length===0)throw new Error("the project has no GitHub repositories \u2014 nothing to connect a runner to");return{githubToken:i,repos:a}}async function Lu(t,e,r,n=Nu){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 Ou(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=ut(e.runnerPublicKey,JSON.stringify(l));Vi(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 Du(t,e,r,n=Nu){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 Ou(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=ut(e.runnerPublicKey,JSON.stringify(c));Vi(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();je();te();var Uu=16*1024;function Sy(t){return Ce.test(t)?mt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ce}`}function Bu(t,e,r,n){let o=Sy(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>Uu)return{ok:!1,detail:`secret value too large (max ${Uu} chars)`};try{return oc(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Mu(t,e){try{return ic(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)}}}on();te();$t();var xo=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 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=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=Ry(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function Ry(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 So=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??(()=>et({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}:{},S=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,...S}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...v})]),we=new Map;for(let A of[...B,...pe])we.set(A.id,A);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,...S})}}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 S=await Fu(r,v.id,e.sinceMs,this.log);S&&i.set(v.id,S)}let c=[];for(let v of e.offBoardIssueIds){if(s.has(v))continue;let S=await Fu(r,v,e.sinceMs,this.log);if(S&&S.length>0&&i.set(v,S),e.requireAssignee||S&&S.length>0){let U=await Cy(r,v,e.stageField,this.log);if(U)c.push(U);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(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 ho(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let v of f)this.shippedAttachments.add(v)}catch(v){let S=v instanceof Error?v.message:String(v);this.abandonTick(`context task sync failed: ${S}`);return}let m=this.options.isSelfComment??(()=>!1),p=[],h=[];for(let[v,S]of i){let U=S.filter(E=>!m(E.id));if(U.length===0)continue;p.push({issueId:v,comments:U.map(Ty)});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(Gu),commentsBatch:p,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Gu)}:{},observedAtMs:n};this.send(y);let $=p.reduce((v,S)=>v+S.comments.length,0),w=h.reduce((v,S)=>v+S.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=Iy(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 Gu(t){let{description:e,...r}=t;return r}function Ty(t){let{body:e,...r}=t;return r}function Iy(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 Cy(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 Fu(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 zi="npm i -g @code-partner/codepipe@latest";function Ro(t,e={}){let r=e.log??{info:p=>console.log(p),warn:p=>console.warn(p)};r.info(`codepipe-cli v${Ie} (protocol ${Ye})`);let n=p=>e.onEvent?.(p),o=e.workspace;o?.contextDir&&vc(o.contextDir,r);let i=Hu("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Hu("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=bo(t.hubUrl,t.cliToken),h=null,y=new xo(i,g=>{p.readyState===p.OPEN&&p.send(JSON.stringify(g))},r),$=new So(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:Fi(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 I=await Ml(t.projectId,g);if(p.readyState!==p.OPEN)return;let k={type:"cli_readiness",projectId:t.projectId,ready:I.ready,checks:I.checks,creds:I.creds,secretNames:sc(t.projectId),checkedAt:I.checkedAt};if(p.send(JSON.stringify(k)),I.ready)r.info("[readiness] ready");else{let R=I.checks.filter(j=>!j.ok).map(j=>`${j.name}(${j.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${R.join(", ")}`)}}catch(g){r.warn(`[readiness] check failed: ${g instanceof Error?g.message:String(g)}`)}},S=()=>{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 I=E.get(g);if(!I||(I.timer&&clearTimeout(I.timer),E.delete(g),I.events.length===0||p.readyState!==p.OPEN))return;let k={type:"run_activity",projectId:t.projectId,runId:g,events:I.events};p.send(JSON.stringify(k))},pe=(g,I)=>{let k=E.get(g);if(k||(k={events:[],timer:null},E.set(g,k)),k.events.push(I),I.kind==="result"){B(g);return}k.timer||(k.timer=setTimeout(()=>B(g),P),k.timer.unref?.())},we=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 I;try{I=(await V(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let k=await Yc(g,t.projectId,I,r);return p.readyState===p.OPEN&&p.send(JSON.stringify(k)),k};return p.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let g=mc(t.projectId),I=M("ORIGIN")==="farm"?"farm":"local",k=M("FARM_ID"),R=t.accountEmail??g.email,j;try{let T=Wl(t.projectId);T&&(j=T.publicKey,r.info(`[cred-channel] key fingerprint: ${T.fingerprint}`))}catch(T){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${T instanceof Error?T.message:String(T)}`)}let b={type:"register",projectId:t.projectId,platformVersion:Ie,protocolVersion:Ye,accountId:g.accountId,accountLabel:g.label,origin:I,inFlightActionIds:[...d],...R?{accountEmail:R}:{},...I==="farm"&&k?{farmId:k}:{},...j?{sealPublicKey:j}:{}};p.send(JSON.stringify(b))}),p.on("message",async g=>{let I=g.toString("utf-8");if(I==="pong"||I==="ping")return;let k;try{k=JSON.parse(I)}catch{return}if(!k||typeof k!="object")return;let R=k.type;if(R==="registered"){let b=k;if(b.ok){if(r.info(`[ws] registered for project ${b.projectId}`),n({kind:"registered",projectId:b.projectId??t.projectId}),y.start(),we?.start(),S(),Ji(t,o,r),o?.contextDir)try{let T=oo(o.contextDir,t.projectId);p.readyState===p.OPEN&&p.send(JSON.stringify(T)),T.outdated&&(r.warn(`[ctx] context format outdated: v${T.templateVersion} \u2192 v${T.currentVersion}`+(T.missingPaths.length>0?` (missing: ${T.missingPaths.join(", ")})`:"")),l||(l=!0,A().catch(()=>{})))}catch(T){r.warn(`[ctx] context-format detect failed (non-fatal): ${T instanceof Error?T.message:String(T)}`)}}else r.warn(`[ws] register rejected: ${b.reason??"unknown"}`),n({kind:"register_rejected",reason:b.reason??"unknown"}),c=!0,p.close();return}if(R==="hello"){let b=k;h=Dn(b.protocolVersion);let T=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${T}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ie}, protocol ${Ye}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${zi}`),n({kind:"incompatible",hubVersion:typeof b.platformVersion=="string"?b.platformVersion:null,hubProtocol:typeof b.protocolVersion=="number"?b.protocolVersion:null,updateCommand:zi}));return}if(R==="tracking_targets"){y.setTargets(k.targets);return}if(R==="youtrack_sync_request"){$.setRequest(k);return}if(R==="youtrack_force_sync"){$.forceSync();return}if(R==="sync_local"){await _y(k,o,p,r);return}if(R==="provision_repo"){let b=k;r.info(`[repo] provision_repo: ${b.repo.name} (${b.repo.host}:${b.repo.owner}/${b.repo.repoName})`),await Ay(t,o,b.repo,r),await Ji(t,o,r);return}if(R==="remove_repo"){let b=k;r.info(`[repo] remove_repo: ${b.repoName}${b.purge?" (purge)":""}`),await Ji(t,o,r),b.purge&&jy(t,o,b.repoName,r);return}if(R==="context_write"){await Ny(k,o,p,r);return}if(R==="adr_promote"){await Oy(k,o,p,r);return}if(R==="cred_update"){let b=k,T=D(t.projectId),K=T?.sealKey?await ql(t.projectId,b.kind,b.sealed,T.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},G={type:"cred_update_result",updateId:b.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] ${b.kind} replaced${K.detail?` \u2014 ${K.detail}`:""}`),v()):r.warn(`[cred] ${b.kind} replacement rejected: ${K.detail??"unknown"}`);return}if(R==="move_to_farm"){let b=k;r.info(`[farm-move] request to move ${t.projectId} onto farm ${b.farmName} (${b.farmId})`);let T=await Pu(t,b,o?.contextDir,r);p.readyState===p.OPEN&&p.send(JSON.stringify(T)),T.ok?r.info(`[farm-move] done \u2014 farm daemon ${T.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${T.error??"unknown error"}`);return}if(R==="gh_runner_setup"){let b=k;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let T=await Lu(t,b,r);p.readyState===p.OPEN&&p.send(JSON.stringify(T)),T.ok?r.info(`[ghr] runners connected on ${b.runnerName}`):r.warn(`[ghr] setup failed: ${T.error??"see per-repo statuses"}`);return}if(R==="gh_runner_teardown"){let b=k;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let T=await Du(t,b,r);p.readyState===p.OPEN&&p.send(JSON.stringify(T)),T.ok?r.info(`[ghr] runners disconnected from ${b.runnerName}`):r.warn(`[ghr] teardown failed: ${T.error??"unknown error"}`);return}if(R==="tracker_fields_request"){let b=k,T={type:"tracker_fields_result",requestId:b.requestId,projectId:t.projectId,ok:!1},K=et({contextDir:o?.contextDir??null});if(!K.ok)T.error=K.error;else try{T.fields=await K.provider.fetchStateFields(b.projectKey),T.ok=!0}catch(G){T.error=G instanceof Error?G.message:String(G)}p.readyState===p.OPEN&&p.send(JSON.stringify(T)),T.ok||r.warn(`[yt-fields] listing failed: ${T.error??"unknown"}`);return}if(R==="project_secret_update"||R==="project_secret_delete"){let b=k,T;if(b.type==="project_secret_update"){let G=D(t.projectId);T=G?.sealKey?Bu(t.projectId,b.name,b.sealed,G.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else T=Mu(t.projectId,b.name);let K={type:"project_secret_update_result",updateId:b.updateId,projectId:t.projectId,ok:T.ok,...T.detail?{detail:T.detail}:{}};p.readyState===p.OPEN&&p.send(JSON.stringify(K)),T.ok?(r.info(`[secret] ${b.name} ${b.type==="project_secret_update"?"saved":"deleted"}`+(T.detail?` \u2014 ${T.detail}`:"")),v()):r.warn(`[secret] ${b.name} rejected: ${T.detail??"unknown"}`);return}if(R==="sandbox_keys"){let b=D(t.projectId);if(!b){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let T=er(t.projectId),K=ll(k,b,T,r);for(let G of K)p.readyState===p.OPEN&&p.send(JSON.stringify(G));return}if(R!=="dispatch_action")return;let j=k;if(h===!1){let b=`refused: HUB protocol incompatible with CLI v${Ie} (protocol ${Ye})`;p.send(JSON.stringify({type:"action_result",actionId:j.actionId,status:"failed",error:b})),r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 REFUSED: ${b}`),r.warn(`[exec] update the CLI to clear this: ${zi}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:!1,error:b});return}d.add(j.actionId);try{let b=await lu({action:j.action,repo:j.repo,trackerIssueId:j.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:we?()=>we.reportNow():void 0,refreshContextStatus:o?.contextDir?A:void 0,onRunActivity:pe}).catch(G=>({status:"failed",error:G instanceof Error?G.message:String(G)}));j.action.type==="tracker_comment"&&b.status==="done"&&"result"in b&&typeof b.result?.commentId=="string"&&f.add(b.result.commentId),p.send(JSON.stringify({type:"action_result",actionId:j.actionId,...b}));let T=b.status!=="failed",K=!T&&"error"in b?b.error:void 0;T?r.info(`[exec] ${j.actionId} (${j.action.type}) \u2192 done`):r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 FAILED: ${K??"?"}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:T,...K?{error:K}:{}})}finally{d.delete(j.actionId)}}),p.on("close",(g,I)=>{let k=I?.toString("utf-8")??"";if(r.info(`[ws] closed code=${g}${k?` reason=${k}`:""}`),y.stop(),$.stop(),we?.stop(),U(),k==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:g}),!c&&setTimeout(()=>{u=m()},2e3)}),p.on("error",g=>r.warn(`[ws] error: ${g.message}`)),p}return{stop(){c=!0,u.close()}}}async function Ji(t,e,r){try{let n=await V(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Zr(t.projectId,n.repos,e?.contextDir);for(let s of o)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function 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?mn(e.root,o):ve(t.projectId,r.name);if(Ku(mn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await Ey().clone(rn(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 jy(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?mn(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(!Ku(mn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Py(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 _y(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=mn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await gc(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function Ny(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await lt(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function Oy(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=t.source??"task",s=await Pc(e.contextDir,t.taskKey,t.slugs,void 0,i);if(n.info(`[adr] adr_promote ${t.id}: promoted ${s.promoted.length}, skipped ${s.skipped.length}`+(s.promoted.length>0?` (${s.promoted.join(", ")})`:"")),s.missing.length>0){let a=l=>i==="staging"?`adr/DRAFT-${l}.md`:`tasks/${t.taskKey}/adr/DRAFT-${l}.md`,c=`draft file(s) missing in clone: ${s.missing.map(a).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${c}`),o("failed",c);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function Hu(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}fe();te();ct();Qi();st();po();async function rd(t={profile:void 0}){let{cfg:e,profile:r}=Yn(t.profile),n=D(e.projectId);n&&Yr(n),sn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),an(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),cn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=gn(Zi(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Jn("CLI_LOG",i,o);if(s.enabled){let u=new rr(s);Xn(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=Wn(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=gn(Zi(),".codepipe",r?gn("profiles",r,"context"):"context");if(await qi(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await ed(()=>Io({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 qi(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=gn(Zi(),".codepipe",r?gn("profiles",r,"context-config"):"context-config");eo(a.contextDir,m,{info:p=>console.log(p),warn:p=>console.warn(p)})}}let l=Ro(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(`
|
|
757
|
-
[${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}Rr();$e();fe();async function up(t={profile:void 0}){let e=Ae(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=bo(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`)")}Sn();import{readFileSync as _b}from"node:fs";W();$e();ct();Oo();Gt();$t();Ft();fe();te();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 In(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 Nb(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");Lt.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 S=w,U=de(S.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(S.name,`project.repos[${v}].name`),host:U,owner:de(S.owner,`project.repos[${v}].owner`),repoName:de(S.repoName,`project.repos[${v}].repoName`)},E=In(S.defaultBranch,`project.repos[${v}].defaultBranch`);E&&(P.defaultBranch=E);let B=In(S.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=In(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:In(u.name,"project.contextRepo.name")??it(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:d,contextRepo:p}},y=In(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 S=w.github;v.github={token:de(S.token,"secrets.github.token")}}if(w.bitbucket){let S=w.bitbucket;v.bitbucket={email:de(S.email,"secrets.bitbucket.email"),apiToken:de(S.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let S=w.gitlab;v.gitlab={token:de(S.token,"secrets.gitlab.token")}}if(w.youtrack){let S=w.youtrack;v.youtrack={url:de(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:de(S.token,"secrets.youtrack.token")}}if(w.contextWrite){let S=w.contextWrite;v.contextWrite={token:de(S.token,"secrets.contextWrite.token")}}h.secrets=v}return h}async function Ob(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Lb(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await wt(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 kt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await so(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 St({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function uf(t){let e=!t.configPath||t.configPath==="-"?await Ob():_b(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=Nb(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 Lb(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){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 Rt(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(X(f),at({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Xe(s.id)}`),Bt(s.id,Ze(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??ze),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await fn(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();te();import{cancel as df,intro as pf,isCancel as ff,log as Ts,outro as Db,password as mf}from"@clack/prompts";async function Ub(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function gf(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Ub(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){pf("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ts.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await mf({message:"Claude OAuth token"});ff(i)&&(df("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),cc({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${zn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ae(t.profile);if(!e){pf(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ts.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await mf({message:"Claude OAuth token"});ff(i)&&(df("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=D(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},X(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Ts.success("Claude OAuth token saved."),Db("It will be sealed into job bundles when a SANDBOX (re)connects."))}W();$e();ct();Oo();Gt();Lo();fe();te();import{cancel as Bb,confirm as Mb,intro as Gb,isCancel as hf,log as ye,outro as Fb,select as yf,text as jt}from"@clack/prompts";function wf(t){Bb(t),process.exit(1)}function _r(t){return hf(t)&&wf("aborted"),t}function Cn(t){return hf(t)&&wf("aborted"),typeof t=="string"?t:""}async function Hb(t,e){let r=_r(await yf({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=Cn(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=Cn(await jt({message:"Context Repo name",placeholder:it(t),initialValue:it(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function kf(t={profile:void 0}){let e=Ae(t.profile);Gb(`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=>Lt.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 yf({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 Mb({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=Cn(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=Cn(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=Cn(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 Hb(r,a),d=D(e.projectId);ye.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=>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 Rt(e.hubUrl,e.cliToken,c);ye.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Bt(r,Ze(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}`),Fb("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)}}Rr();$e();fe();te();st();Sn();import{existsSync as Kb,rmSync as Wb}from"node:fs";import{confirm as qb,intro as Yb,isCancel as Vb,log as _t,outro as zb,spinner as Jb}from"@clack/prompts";function tt(t){_t.error(t),process.exit(1)}var bf=t=>t.trim().replace(/\/+$/,"");async function $f(t){Yb("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Ee()?.spec.projectId??void 0;e||tt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Ue(e);r||tt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=bf(r.hubUrl),o=r.projectId,i=bf(t.hub);i.startsWith("http")||tt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&tt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let $=Jb();$.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&&tt(`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||tt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let d=D(o),f=(t.account??r.accountEmail??await Ar()).trim().toLowerCase();if(_t.message(`move project '${o}'
|
|
754
|
+
`;return await lt(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 Pl(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:ui.statusColumns}]}async mutateRecord(e,r,n){let o=en(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=tn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Yr(e),content:Fi(i)},...yo(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await lt(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Mn,status:r.targetStatus,links:[],created:n,updated:n},i=tn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Yr(e),content:Fi(o)},...yo(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function fu(t,e){let r=de(t,`tasks/${e}/comments.jsonl`);if(!dy(r))return[];let n=[];for(let o of py(r,"utf-8").split(`
|
|
755
|
+
`)){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}lo();function Xi(t){if(!t)return"youtrack";try{let e=hu(t,"project.yaml");return mu(e)&&yu(gu(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function et(t){let e=Xi(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=Tl(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=my(n);return i?{ok:!0,kind:e,provider:new dn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=_c();return r?{ok:!0,kind:e,provider:new un(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function my(t){try{let e=hu(t,"project.yaml");if(!mu(e))return null;let r=yu(gu(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var ko=new Map;async function pn(t,e){let n=(ko.get(t)??Promise.resolve()).catch(()=>{}).then(e);ko.set(t,n);try{return await n}finally{ko.get(t)===n&&ko.delete(t)}}async function wu(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;nn(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return pn(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{commit:c,pushed:l}=await Ml(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 ne({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 H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return pn(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir);return await Gl(s,a,{branchName:e.branchName,force:e.force}),ne({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return pn(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{commit:c,pushed:l}=await Fl(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ne({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return H("no repo spec");let i=Be(r),s=await i.createPullRequest(r,e);return ne({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return H("no repo spec");let i=Be(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ne({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return H("no repo spec");let i=Be(r);return await i.closePR(r,e.prNumber,e.comment),ne({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return pn(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=xe(i,r.name,t.baseDir),{mergedSha:c}=await Hl(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ne({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return H("no repo spec");let i=t.cloneUrlOverride??sn(r),a=(await Kl(i)).filter(d=>Wl(d,e.issueKey)),c=Be(r),l=null;if(c.findOpenPrByBranch)for(let d of a){let p=await c.findOpenPrByBranch(r,d).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return ne({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return H("no repo spec");let i=Be(r);return await i.addPRComment(r,e.prNumber,e.body),ne({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=et({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ne({issueId:t.trackerIssueId,newStatus:e.newStatus})):H("no tracker_issue_id provided"):H(i.error)}case"tracker_comment":{let i=et({contextDir:t.contextDir});if(!i.ok)return H(i.error);if(!t.trackerIssueId)return H("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ne({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=et({contextDir:t.contextDir});if(!i.ok)return H(i.error);if(!e.projectKey)return H("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ne({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=et({contextDir:t.contextDir});if(!i.ok)return H(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 H(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ne({applied:s})}case"set_project_setting":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await cu(t.contextDir,e.edits);return ne({files:i.files})}case"tracker_edit":{let i=et({contextDir:t.contextDir});if(!i.ok)return H(i.error);if(!t.contextDir)return H("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 wo(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ne({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await du(t.contextDir,e);return ne({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await uu(t.contextDir,e);return ne({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ne({reported:!0})):H("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return H("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ne({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return H("no project workspace on this CLI");if(!r)return H("no repo spec");if(!t.onRunActivity)return H("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=ro(t.contextDir),c=s.find(g=>g.id===e.actionId);if(!c){let g=a.find(f=>f.file===`actions/${e.actionId}.yml`);return H(g?`action "${e.actionId}" failed to parse: ${g.error}`:`unknown action "${e.actionId}"`)}let l=ma(c,e.input);if(!l.ok)return H(l.error);let d=ll(t.contextDir),p=U(e.projectId),u={};return p?.github?.token&&(u.GH_TOKEN=p.github.token),p?.gitlab?.token&&(u.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(u.BITBUCKET_EMAIL=p.bitbucket.email,u.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(u.YOUTRACK_URL=p.youtrack.url,u.YOUTRACK_TOKEN=p.youtrack.token),pn(`${e.projectId}/${r.name}`,async()=>{await dr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let g=xe(e.projectId,r.name,t.baseDir),f=await ou({cwd:g,def:c,input:l.values,variables:d,secrets:p?.secrets??{},credEnv:u,onEvent:m=>i(e.runId,m)});return ne({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=au(t.contextDir,e.path);return ne({path:e.path,...i})}default:return H(`unsupported action type: ${e.type}`)}}catch(i){return H(i instanceof Error?i.message:String(i))}}function ne(t){return{status:"done",result:t}}function H(t){return{status:"failed",error:t}}je();Zi();me();re();import{existsSync as Ou,readFileSync as Lu}from"node:fs";import{join as Du}from"node:path";async function Uu(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=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)");$o(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 J(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=Du(r,"project.yaml"),g=Du(r,"regimen.yaml");Ou(u)&&Ou(g)?c={projectYaml:Lu(u,"utf-8"),regimenYaml:Lu(g,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},d=ut(e.farmPublicKey,JSON.stringify(l));bo(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await xo(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:d});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}je();ke();je();import{homedir as Ty}from"node:os";import{existsSync as Iy,mkdirSync as Cy,readFileSync as Py,writeFileSync as Ey}from"node:fs";import{dirname as Ay,join as jy}from"node:path";function rs(){return B("RUNNER_PINS")??jy(Ty(),".codepipe","runner-pins.json")}function Bu(){let t=rs();if(!Iy(t))return{};try{return JSON.parse(Py(t,"utf-8"))}catch{return{}}}function _y(t){let e=rs();Cy(Ay(e),{recursive:!0}),Ey(e,JSON.stringify(t,null,2)+`
|
|
756
|
+
`,{mode:384})}function Ny(t){return Bu()[t]}function ns(t,e){let r=Bu();r[t]=e,_y(r)}function Mu(t,e){let r=be(e),n=Ny(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 ${rs()}.`);return r}me();re();var Fu=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Gu(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Fu(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var Oy={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Fu(t)});if(!n.ok)throw new Error(`github GET /repos/${e}/${r}: HTTP ${n.status}`);return(await n.json()).permissions?.admin===!0},mintRegistrationToken:(t,e,r)=>Gu(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Gu(t,e,r,"remove-token")},Hu={api:Oy,fetchProject:J,provisionOnRunner:$u,teardownOnRunner:vu};async function Ku(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(be(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Mu(e.runnerId,e.runnerPublicKey);let 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 Wu(t,e,r,n=Hu){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await Ku(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=ut(e.runnerPublicKey,JSON.stringify(l));ns(e.runnerId,e.fingerprint),r.info(`[ghr] ${c.length} registration token(s) sealed for runner host ${e.runnerName} \u2014 handing off`);let p=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:p.ok,...p.runners?{runners:p.runners}:{},...p.error?{error:p.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function qu(t,e,r,n=Hu){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await Ku(t,e,n),a=[];for(let p of s)try{a.push({owner:p.owner,repo:p.repoName,removeToken:await n.api.mintRemoveToken(i,p.owner,p.repoName)})}catch(u){r.warn(`[ghr] remove-token for ${p.owner}/${p.repoName} failed (${u instanceof Error?u.message:u}) \u2014 the runner host will force-remove`),a.push({owner:p.owner,repo:p.repoName})}let c={projectId:t.projectId,runners:a},l=ut(e.runnerPublicKey,JSON.stringify(c));ns(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))}}me();W();je();re();var Yu=16*1024;function Ly(t){return Ce.test(t)?mt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ce}`}function Vu(t,e,r,n){let o=Ly(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(pr(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>Yu)return{ok:!1,detail:`secret value too large (max ${Yu} chars)`};try{return ac(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function zu(t,e){try{return cc(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)}}}ir();re();kt();var Ro=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let 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 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=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=Dy(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function Dy(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 To=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??(()=>et({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let b=e.stageField?{stageField:e.stageField}:{},R=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},P=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(P){let N=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[F,fe]=await Promise.all([N.length>0?r.listIssues({projectKey:e.projectKey,columns:N,...b,...R}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...b})]),Ne=new Map;for(let E of[...F,...fe])Ne.set(E.id,E);o=[...Ne.values()]}else{let N=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:N,...b,...R})}}catch(b){this.log.warn(`[yt-sync] listIssues failed: ${b instanceof Error?b.message:String(b)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let b of o){if(s.add(b.id),a.has(b.status))continue;let R=await Xu(r,b.id,e.sinceMs,this.log);R&&i.set(b.id,R)}let c=[];for(let b of e.offBoardIssueIds){if(s.has(b))continue;let R=await Xu(r,b,e.sinceMs,this.log);if(R&&R.length>0&&i.set(b,R),e.requireAssignee||R&&R.length>0){let G=await My(r,b,e.stageField,this.log);if(G)c.push(G);else if(R&&R.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(b=>!a.has(b.status)),{attachmentsByIssue:d,attachmentKeys:p}=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(b=>({issue:b,comments:i.get(b.id)??[],attachments:d.get(b.id)??[]}));try{await wo(this.options.contextDir,e.projectId,u),this.abandonedTicks=0;for(let b of p)this.shippedAttachments.add(b)}catch(b){let R=b instanceof Error?b.message:String(b);this.abandonTick(`context task sync failed: ${R}`);return}let g=this.options.isSelfComment??(()=>!1),f=[],m=[];for(let[b,R]of i){let G=R.filter(N=>!g(N.id));if(G.length===0)continue;f.push({issueId:b,comments:G.map(Uy)});let P=G.flatMap(N=>{let F=Qt(N.body);return F?[{commentId:N.id,author:N.author,name:F.name,args:F.args,createdAt:N.createdAt}]:[]});P.length>0&&m.push({issueId:b,commands:P})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Ju),commentsBatch:f,...m.length>0?{commandsBatch:m}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Ju)}:{},observedAtMs:n};this.send(y);let k=f.reduce((b,R)=>b+R.comments.length,0),w=m.reduce((b,R)=>b+R.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${k} commands=${w} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,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 p=`${s.id}:${d.id}`;if(this.shippedAttachments.has(p))continue;let u;try{u=await n.downloadAttachment(d.url)}catch(f){this.log.warn(`[yt-sync] attachment ${d.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let g=By(d.name);l.has(g)&&(g=`${d.id}-${g}`),l.add(g),c.push({name:g,contentBase64:u.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Ju(t){let{description:e,...r}=t;return r}function Uy(t){let{body:e,...r}=t;return r}function By(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 My(t,e,r,n){try{return await t.getIssue(e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Xu(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var os="npm i -g @code-partner/codepipe@latest";function Io(t,e={}){let r=e.log??{info:m=>console.log(m),warn:m=>console.warn(m)};r.info(`codepipe-cli v${Ie} (protocol ${Ye})`);let n=m=>e.onEvent?.(m),o=e.workspace;o?.contextDir&&pl(o.contextDir,r);let i=Qu("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Qu("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let m=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(m)&&m>0?m*1e3:6e5})(),c=!1,l=!1,d=!1,p=new Set,u=new Set,g=f();function f(){let m=vo(t.hubUrl,t.cliToken),y=null,k=new Ro(i,S=>{m.readyState===m.OPEN&&m.send(JSON.stringify(S))},r),w=new To(s,S=>{m.readyState===m.OPEN&&m.send(JSON.stringify(S))},r,{contextDir:o?.contextDir??null,isSelfComment:S=>u.has(S)}),b=null,R=async()=>{try{let S={trackerProvider:Xi(o?.contextDir??null)};try{let A=await J(t.hubUrl,t.cliToken,t.projectId);S={...S,repos:A.repos,contextRepo:A.contextRepo}}catch(A){r.warn(`[readiness] could not fetch project summary for push checks: ${A instanceof Error?A.message:String(A)}`)}let x=await Xc(t.projectId,S);if(m.readyState!==m.OPEN)return;let v={type:"cli_readiness",projectId:t.projectId,ready:x.ready,checks:x.checks,creds:x.creds,secretNames:lc(t.projectId),checkedAt:x.checkedAt};if(m.send(JSON.stringify(v)),x.ready)r.info("[readiness] ready");else{let A=x.checks.filter($=>!$.ok).map($=>`${$.name}(${$.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${A.join(", ")}`)}let j=nl(x.creds,d);if(j==="open"){d=!0;let A=ol(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${A}`),Ft(A)}else j==="rearm"&&(d=!1)}catch(S){r.warn(`[readiness] check failed: ${S instanceof Error?S.message:String(S)}`)}},G=()=>{R(),b=setInterval(()=>void R(),a),typeof b.unref=="function"&&b.unref()},P=()=>{b&&(clearInterval(b),b=null)},N=150,F=new Map,fe=S=>{let x=F.get(S);if(!x||(x.timer&&clearTimeout(x.timer),F.delete(S),x.events.length===0||m.readyState!==m.OPEN))return;let v={type:"run_activity",projectId:t.projectId,runId:S,events:x.events};m.send(JSON.stringify(v))},Ne=(S,x)=>{let v=F.get(S);if(v||(v={events:[],timer:null},F.set(S,v)),v.events.push(x),x.kind==="result"){fe(S);return}v.timer||(v.timer=setTimeout(()=>fe(S),N),v.timer.unref?.())},E=o?.contextDir?new no(o.contextDir,t.projectId,S=>{m.readyState===m.OPEN&&m.send(JSON.stringify(S))},r):null,h=async()=>{let S=o?.contextDir;if(!S)throw new Error("no context repo clone on this CLI");let x;try{x=(await J(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let v=await Nl(S,t.projectId,x,r);return m.readyState===m.OPEN&&m.send(JSON.stringify(v)),v};return m.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let S=yc(t.projectId),x=B("ORIGIN")==="farm"?"farm":"local",v=B("FARM_ID"),j=t.accountEmail??S.email,A;try{let I=eu(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 $={type:"register",projectId:t.projectId,platformVersion:Ie,protocolVersion:Ye,accountId:S.accountId,accountLabel:S.label,origin:x,inFlightActionIds:[...p],...j?{accountEmail:j}:{},...x==="farm"&&v?{farmId:v}:{},...A?{sealPublicKey:A}:{}};m.send(JSON.stringify($))}),m.on("message",async S=>{let x=S.toString("utf-8");if(x==="pong"||x==="ping")return;let v;try{v=JSON.parse(x)}catch{return}if(!v||typeof v!="object")return;let j=v.type;if(j==="registered"){let $=v;if($.ok){if(r.info(`[ws] registered for project ${$.projectId}`),n({kind:"registered",projectId:$.projectId??t.projectId}),k.start(),E?.start(),G(),is(t,o,r),o?.contextDir)try{let I=co(o.contextDir,t.projectId);m.readyState===m.OPEN&&m.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,h().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: ${$.reason??"unknown"}`),n({kind:"register_rejected",reason:$.reason??"unknown"}),c=!0,m.close();return}if(j==="hello"){let $=v;y=Dn($.protocolVersion);let I=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${I}`),y||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ie}, protocol ${Ye}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${os}`),n({kind:"incompatible",hubVersion:typeof $.platformVersion=="string"?$.platformVersion:null,hubProtocol:typeof $.protocolVersion=="number"?$.protocolVersion:null,updateCommand:os}));return}if(j==="tracking_targets"){k.setTargets(v.targets);return}if(j==="youtrack_sync_request"){w.setRequest(v);return}if(j==="youtrack_force_sync"){w.forceSync();return}if(j==="sync_local"){await Wy(v,o,m,r);return}if(j==="provision_repo"){let $=v;r.info(`[repo] provision_repo: ${$.repo.name} (${$.repo.host}:${$.repo.owner}/${$.repo.repoName})`),await Hy(t,o,$.repo,r),await is(t,o,r);return}if(j==="remove_repo"){let $=v;r.info(`[repo] remove_repo: ${$.repoName}${$.purge?" (purge)":""}`),await is(t,o,r),$.purge&&Ky(t,o,$.repoName,r);return}if(j==="context_write"){await qy(v,o,m,r);return}if(j==="adr_promote"){await Yy(v,o,m,r);return}if(j==="cred_update"){let $=v,I=U(t.projectId),M=I?.sealKey?await tu(t.projectId,$.kind,$.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},Y={type:"cred_update_result",updateId:$.updateId,projectId:t.projectId,ok:M.ok,...M.detail?{detail:M.detail}:{}};m.readyState===m.OPEN&&m.send(JSON.stringify(Y)),M.ok?(r.info(`[cred] ${$.kind} replaced${M.detail?` \u2014 ${M.detail}`:""}`),R()):r.warn(`[cred] ${$.kind} replacement rejected: ${M.detail??"unknown"}`);return}if(j==="agent_login_start"){rl(t,m,v,r,R);return}if(j==="move_to_farm"){let $=v;r.info(`[farm-move] request to move ${t.projectId} onto farm ${$.farmName} (${$.farmId})`);let I=await Uu(t,$,o?.contextDir,r);m.readyState===m.OPEN&&m.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(j==="gh_runner_setup"){let $=v;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${$.runnerName} (${$.runnerId})`);let I=await Wu(t,$,r);m.readyState===m.OPEN&&m.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${$.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if(j==="gh_runner_teardown"){let $=v;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${$.runnerName} (${$.runnerId})`);let I=await qu(t,$,r);m.readyState===m.OPEN&&m.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${$.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if(j==="tracker_fields_request"){let $=v,I={type:"tracker_fields_result",requestId:$.requestId,projectId:t.projectId,ok:!1},M=et({contextDir:o?.contextDir??null});if(!M.ok)I.error=M.error;else try{I.fields=await M.provider.fetchStateFields($.projectKey),I.ok=!0}catch(Y){I.error=Y instanceof Error?Y.message:String(Y)}m.readyState===m.OPEN&&m.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(j==="project_secret_update"||j==="project_secret_delete"){let $=v,I;if($.type==="project_secret_update"){let Y=U(t.projectId);I=Y?.sealKey?Vu(t.projectId,$.name,$.sealed,Y.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else I=zu(t.projectId,$.name);let M={type:"project_secret_update_result",updateId:$.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};m.readyState===m.OPEN&&m.send(JSON.stringify(M)),I.ok?(r.info(`[secret] ${$.name} ${$.type==="project_secret_update"?"saved":"deleted"}`+(I.detail?` \u2014 ${I.detail}`:"")),R()):r.warn(`[secret] ${$.name} rejected: ${I.detail??"unknown"}`);return}if(j==="sandbox_keys"){let $=U(t.projectId);if(!$){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=rr(t.projectId),M=Jl(v,$,I,r);for(let Y of M)m.readyState===m.OPEN&&m.send(JSON.stringify(Y));return}if(j!=="dispatch_action")return;let A=v;if(y===!1){let $=`refused: HUB protocol incompatible with CLI v${Ie} (protocol ${Ye})`;m.send(JSON.stringify({type:"action_result",actionId:A.actionId,status:"failed",error:$})),r.warn(`[exec] ${A.actionId} (${A.action.type}) \u2192 REFUSED: ${$}`),r.warn(`[exec] update the CLI to clear this: ${os}`),n({kind:"action",actionId:A.actionId,actionType:A.action.type,ok:!1,error:$});return}p.add(A.actionId);try{let $=await wu({action:A.action,repo:A.repo,trackerIssueId:A.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:E?()=>E.reportNow():void 0,refreshContextStatus:o?.contextDir?h:void 0,onRunActivity:Ne}).catch(Y=>({status:"failed",error:Y instanceof Error?Y.message:String(Y)}));A.action.type==="tracker_comment"&&$.status==="done"&&"result"in $&&typeof $.result?.commentId=="string"&&u.add($.result.commentId),m.send(JSON.stringify({type:"action_result",actionId:A.actionId,...$}));let I=$.status!=="failed",M=!I&&"error"in $?$.error:void 0;I?r.info(`[exec] ${A.actionId} (${A.action.type}) \u2192 done`):r.warn(`[exec] ${A.actionId} (${A.action.type}) \u2192 FAILED: ${M??"?"}`),n({kind:"action",actionId:A.actionId,actionType:A.action.type,ok:I,...M?{error:M}:{}})}finally{p.delete(A.actionId)}}),m.on("close",(S,x)=>{let v=x?.toString("utf-8")??"";if(r.info(`[ws] closed code=${S}${v?` reason=${v}`:""}`),k.stop(),w.stop(),E?.stop(),P(),v==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:S}),!c&&setTimeout(()=>{g=f()},2e3)}),m.on("error",S=>r.warn(`[ws] error: ${S.message}`)),m}return{stop(){c=!0,g.close()}}}async function is(t,e,r){try{let n=await J(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=rn(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 Hy(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?gn(e.root,o):xe(t.projectId,r.name);if(Zu(gn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await Fy().clone(sn(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 Ky(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?gn(e.root,o):xe(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Zu(gn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Gy(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 Wy(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=gn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await il(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 qy(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 lt(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 kl(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 Qu(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}me();re();ct();as();st();mo();async function dd(t={profile:void 0}){let{cfg:e,profile:r}=Yn(t.profile),n=U(e.projectId);n&&zr(n),an(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),cn(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),ln(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=hn(cs(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Jn("CLI_LOG",i,o);if(s.enabled){let u=new or(s);Xn(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=Wn(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=hn(cs(),".codepipe",r?hn("profiles",r,"context"):"context");if(await ts(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await ld(()=>Po({cfg:e,secrets:n,contextDir:u,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),{log:{warn:g=>console.warn(g)}}),a||await ts(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let g=hn(cs(),".codepipe",r?hn("profiles",r,"context-config"):"context-config");oo(a.contextDir,g,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=Io(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 p(u){d||(d=!0,console.log(`
|
|
757
|
+
[${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Ir();ve();me();async function kp(t={profile:void 0}){let e=Ee(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=vo(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 p=JSON.parse(d);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.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 J(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=he(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}Sn();import{readFileSync as Db}from"node:fs";W();ve();ct();Do();Kt();kt();Gt();me();re();function ie(t){throw new Error(t)}function pe(t,e){return(typeof t!="string"||t.trim().length===0)&&ie(`config: '${e}' must be a non-empty string`),t.trim()}function In(t,e){if(t==null)return;typeof t!="string"&&ie(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Ub(t){(!t||typeof t!="object")&&ie("config: expected a JSON object");let e=t,r=pe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ie("config: 'hubUrl' must start with http(s)://");let n=pe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ie("config: 'project' is required");let i=o,s=pe(i.id,"project.id");Dt.test(s)||ie("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=pe(i.name,"project.name"),c=pe(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ie("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ie("config: 'project.repos' must be an array");let d=l.map((w,b)=>{(!w||typeof w!="object")&&ie(`config: project.repos[${b}] must be an object`);let R=w,G=pe(R.host,`project.repos[${b}].host`);G!=="github"&&G!=="bitbucket"&&G!=="gitlab"&&ie(`config: project.repos[${b}].host must be 'github', 'bitbucket' or 'gitlab'`);let P={name:pe(R.name,`project.repos[${b}].name`),host:G,owner:pe(R.owner,`project.repos[${b}].owner`),repoName:pe(R.repoName,`project.repos[${b}].repoName`)},N=In(R.defaultBranch,`project.repos[${b}].defaultBranch`);N&&(P.defaultBranch=N);let F=In(R.mountAs,`project.repos[${b}].mountAs`);return F&&(P.mountAs=F),P}),p=i.contextRepo;(!p||typeof p!="object")&&ie("config: 'project.contextRepo' is required");let u=p,g=In(u.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&ie("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:g,owner:pe(u.owner,"project.contextRepo.owner"),name:In(u.name,"project.contextRepo.name")??it(s)},m={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:d,contextRepo:f}},y=In(i.youtrackProjectKey,"project.youtrackProjectKey");if(y&&(m.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&ie("config: 'project.index' must be a boolean"),m.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ie("config: 'project.youtrackWrites' must be a boolean"),m.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let w=pe(i.llmProvider,"project.llmProvider");w==="codex"&&ie(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),w!=="claude"&&ie("config: 'project.llmProvider' must be 'claude'"),m.project.llmProvider=w}let k=e.secrets;if(k!==void 0){(typeof k!="object"||k===null)&&ie("config: 'secrets' must be an object");let w=k,b={};if(w.github){let R=w.github;b.github={token:pe(R.token,"secrets.github.token")}}if(w.bitbucket){let R=w.bitbucket;b.bitbucket={email:pe(R.email,"secrets.bitbucket.email"),apiToken:pe(R.apiToken,"secrets.bitbucket.apiToken")}}if(w.gitlab){let R=w.gitlab;b.gitlab={token:pe(R.token,"secrets.gitlab.token")}}if(w.youtrack){let R=w.youtrack;b.youtrack={url:pe(R.url,"secrets.youtrack.url").replace(/\/$/,""),token:pe(R.token,"secrets.youtrack.token")}}if(w.contextWrite){let R=w.contextWrite;b.contextWrite={token:pe(R.token,"secrets.contextWrite.token")}}m.secrets=b}return m}async function Bb(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Mb(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await ht(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.repos.find(i=>i.host==="bitbucket"),n=r?.owner??(t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:void 0),o=await yt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Zn(e.bitbucket.email,e.bitbucket.apiToken,r.owner,r.repoName);if(i)throw new Error(`Bitbucket: ${i}`)}console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await wt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await $t({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function mf(t){let e=!t.configPath||t.configPath==="-"?await Bb():Db(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){ie(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let n=Ub(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 Mb(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 Pr(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??nr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){ie(`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 Tt(o,i,a)}catch(u){if(u instanceof O&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),d=await J(o,i,s.id);else if(u instanceof O)ie(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${d.projectId} ready (${d.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(z(p),at({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Xe(s.id)}`),Ht(s.id,Ze(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??ze),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await mn(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${u}); runs once a SANDBOX claims it.`)}catch(u){console.warn(`could not enqueue index job: ${u instanceof Error?u.message:String(u)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}ve();re();import{cancel as gf,intro as hf,isCancel as yf,log as Ps,outro as Gb,password as wf}from"@clack/prompts";async function Fb(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function kf(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Fb(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){hf("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ps.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await wf({message:"Claude OAuth token"});yf(i)&&(gf("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),dc({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${zn()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ee(t.profile);if(!e){hf(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ps.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await wf({message:"Claude OAuth token"});yf(i)&&(gf("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},z(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Ps.success("Claude OAuth token saved."),Gb("It will be sealed into job bundles when a SANDBOX (re)connects."))}W();ve();ct();Do();Kt();Uo();me();re();import{cancel as Hb,confirm as Kb,intro as Wb,isCancel as bf,log as we,outro as qb,select as $f,text as _t}from"@clack/prompts";function vf(t){Hb(t),process.exit(1)}function Or(t){return bf(t)&&vf("aborted"),t}function Cn(t){return bf(t)&&vf("aborted"),typeof t=="string"?t:""}async function Yb(t,e){let r=Or(await $f({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=Cn(await _t({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=Cn(await _t({message:"Context Repo name",placeholder:it(t),initialValue:it(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function xf(t={profile:void 0}){let e=Ee(t.profile);Wb(`codepipe project add \u2192 ${e.hubUrl}`);let r=Or(await _t({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=Or(await _t({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),o=Or(await $f({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=Or(await _t({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Or(await Kb({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=Cn(await _t({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:k=>!k||!k.trim()||_e(k)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!u)break;let g=_e(u);we.message(`${g.host}: ${g.owner}/${g.repoName}`);let f=Cn(await _t({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:k=>k.trim().length>0?void 0:"required"})).trim(),m=Cn(await _t({message:"default branch (optional)",placeholder:"main"})).trim(),y={name:f,host:g.host,owner:g.owner,repoName:g.repoName};m&&(y.defaultBranch=m),a.push(y)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Yb(r,a),d=U(e.projectId);we.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Pr(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??nr(),youtrackWrites:s,trackerUrl:d?.youtrack?.url,log:{info:u=>we.message(u),warn:u=>we.warn(u)}})}catch(u){we.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=p,we.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await Tt(e.hubUrl,e.cliToken,c);we.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Ht(r,Ze(c,s,d?.youtrack?.url),{info:g=>we.message(g),warn:g=>we.warn(g)}),u.contextRepo&&(we.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),we.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&we.error(` error: ${u.provisioningError}`),qb("done")}catch(u){u instanceof O?(we.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&we.message(JSON.stringify(u.payload,null,2))):we.error(u instanceof Error?u.message:String(u)),process.exit(1)}}Ir();ve();me();re();st();Sn();import{existsSync as Vb,rmSync as zb}from"node:fs";import{confirm as Jb,intro as Xb,isCancel as Qb,log as Nt,outro as Zb,spinner as e$}from"@clack/prompts";function tt(t){Nt.error(t),process.exit(1)}var Sf=t=>t.trim().replace(/\/+$/,"");async function Rf(t){Xb("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Pe()?.spec.projectId??void 0;e||tt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Ue(e);r||tt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Sf(r.hubUrl),o=r.projectId,i=Sf(t.hub);i.startsWith("http")||tt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&tt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let k=e$();k.start(`reading project ${o} from ${n}\u2026`);try{l=await J(n,r.cliToken,o),k.stop(`read project ${o} (${l.name})`)}catch(w){throw k.stop("could not read the source project",1),w instanceof O&&tt(`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||tt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let d=U(o),p=(t.account??r.accountEmail??await _r()).trim().toLowerCase();if(Nt.message(`move project '${o}'
|
|
758
758
|
from : ${n} (profile ${e})
|
|
759
|
-
to : ${i} (profile ${s}, project ${a}, account ${
|
|
759
|
+
to : ${i} (profile ${s}, project ${a}, account ${p})
|
|
760
760
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
761
761
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
762
|
-
`+(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
|
|
763
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let
|
|
764
|
-
`)}async function
|
|
765
|
-
${
|
|
766
|
-
or: /abort ${r} --reason "..."`}}function
|
|
762
|
+
`+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let k=await Jb({message:"Continue?",initialValue:!0});(Qb(k)||!k)&&tt("aborted")}!c&&a===o&&Nt.warn(`source and destination share the same project id, so they share one secrets file (${Xe(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:u,accountEmail:g}=await Nr(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:g,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Nt.step(`registering project on ${i}\u2026`);let m;try{m=await Tt(i,u,f)}catch(k){if(k instanceof O&&k.status===409){Nt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{m=await J(i,u,a)}catch(w){throw w instanceof O&&tt(`target HUB \u2192 ${w.status} ${w.message}`),w}}else if(k instanceof O&&k.status===403)tt(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(k instanceof O)tt(`target HUB \u2192 ${k.status} ${k.message}`);else throw k}Nt.success(`project ${m.projectId} ready on ${i} (${m.provisioningStatus})`),at({hubUrl:i,cliToken:u,projectId:a,accountEmail:g},s);let y={...d??{},hubUrl:i,cliToken:u,projectId:a};if(delete y.sandboxPins,z(y),Nt.success(`profile '${s}' \u2192 ${Xe(a)}`),c){let k=Fe(s);Vb(k)&&(zb(k),Nt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}Zb(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}ve();import{existsSync as Es,rmSync as t$,statSync as r$}from"node:fs";import{join as Wo,relative as n$,resolve as o$}from"node:path";import{cancel as i$,intro as If,isCancel as s$,log as ae,outro as Cf,text as Vt}from"@clack/prompts";import{simpleGit as Pf}from"simple-git";Uo();me();re();st();function Se(t){i$(t),process.exit(1)}function zt(t){return s$(t)&&Se("aborted"),typeof t=="string"?t:""}async function Tf(t){try{let e=await Pf(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function a$(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function c$(t,e){let r=U(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(a$(r,e)){ae.message(`reusing existing ${e} credentials`);return}if(ae.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=zt(await Vt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=zt(await Vt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=zt(await Vt({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}}z(r),ae.success(`saved ${e} credentials`)}async function Ef(t){let e=Ee(t.profile);If(`codepipe repo add \u2192 project ${e.projectId}`);let r=Pe()??void 0,n;try{n=(await J(e.hubUrl,e.cliToken,e.projectId)).repos}catch(w){Se(`could not read project from HUB: ${w instanceof Error?w.message:String(w)}`)}let o=t.target?.trim();if(!o){let w=await Tf(process.cwd());w?(o=process.cwd(),ae.message(`using the current directory (${w})`)):o=zt(await Vt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:b=>b.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Es(o)&&r$(o).isDirectory()){i=o$(o);let w=await Tf(i);w||Se(`${i} is not a git repository (no origin remote)`);let b=_e(w);b||Se(`origin ${w} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=b,s=w,ae.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let w=_e(o);w||Se(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=w,s=o,ae.message(`${a}: ${c}/${l}`)}let d=zt(await Vt({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)&&Se(`a repo named "${d}" is already registered`);let p=zt(await Vt({message:"default branch (optional)",placeholder:"main"})).trim(),u=d;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let w=n$(r.root,i);u=w===""?".":w}let g=zt(await Vt({message:"mount_as (directory relative to the workspace root)",placeholder:u,initialValue:u})).trim()||u;n.some(w=>(w.mountAs??w.name)===g)&&Se(`mount_as "${g}" is already used by another repo`),await c$(e,a);let f={name:d,host:a,owner:c,repoName:l,mountAs:g,...p?{defaultBranch:p}:{}};if(!i){let w=r?Wo(r.root,g):xe(e.projectId,d);if(Es(Wo(w,".git")))ae.message(`already cloned at ${w}`);else{ae.info(`cloning ${s} \u2192 ${w} \u2026`);try{await Pf().clone(s,w),ae.success(`cloned into ${w}`)}catch(b){Se(`clone failed: ${b instanceof Error?b.message.trim():String(b)}
|
|
763
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let m;try{m=await _u(e.hubUrl,e.cliToken,e.projectId,f)}catch(w){w instanceof O&&Se(`HUB \u2192 ${w.status} ${w.message}`),Se(w instanceof Error?w.message:String(w))}let{updated:y,errors:k}=rn(e.projectId,m.repos,r?.contextDir);for(let w of y)ae.message(`updated ${w}`);for(let w of k)ae.warn(`could not update ${w.path}: ${w.error}`);ae.success(`added "${d}" \u2014 project now has ${m.repos.length} repo(s)`),Cf("done")}async function Af(t){let e=Ee(t.profile);If(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Pe()??void 0,n;try{let c=(await J(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await Nu(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof O&&(a.status===404&&Se(`no repo named "${t.name}" in this project`),Se(`HUB \u2192 ${a.status} ${a.message}`)),Se(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=rn(e.projectId,o.repos,r?.contextDir);for(let a of i)ae.message(`updated ${a}`);for(let a of s)ae.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ae.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Wo(r.root,n):xe(e.projectId,t.name);if(Es(Wo(a,".git")))try{t$(a,{recursive:!0,force:!0}),ae.message(`deleted local clone ${a}`)}catch(c){ae.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ae.message(`no local clone found to purge (${a})`)}ae.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Cf("done")}async function jf(t){let e=Ee(t.profile),r;try{r=(await J(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}Mo();xs();import{existsSync as Kf,mkdirSync as f$,readFileSync as m$,writeFileSync as g$}from"node:fs";import{homedir as h$}from"node:os";import{dirname as y$,join as Wf}from"node:path";import*as Dr from"node:readline";me();re();st();Mo();me();import{existsSync as _s,readFileSync as l$,writeFileSync as u$}from"node:fs";import{join as En}from"node:path";import{simpleGit as js}from"simple-git";var _f=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],d$="apply-queue.json";function Nf(t){return En(t,d$)}function Lr(t){let e=Nf(t);if(!_s(e))return{};try{return JSON.parse(l$(e,"utf-8"))}catch{return{}}}function Of(t,e){u$(Nf(t),JSON.stringify(e,null,2)+`
|
|
764
|
+
`)}async function Lf(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 g=t.spec.repos.find(k=>k.name===u.repoName);if(!g)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let f=En(t.root,g.mountAs);if(!_s(En(f,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await js(f).status()).isClean())return{ok:!1,message:`${g.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:u,spec:g,dir:f})}let a=[];for(let u of s){let g=js(u.dir),f=await p$(g),m=u.claimRepo;try{await g.fetch()}catch(w){return await As(a,o),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${Pn(w)}`}}let y=`origin/${m.baseRef}`,k;try{k=await po(g,{contextRepoCloneUrl:m.contextRepoCloneUrl,deliveryRef:m.deliveryRef,deliverySha:m.deliverySha,baseSha:m.baseSha,commitMessage:m.commitMessage})}catch(w){return await As(a,o),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${Pn(w)}`}}a.push({git:g,dir:u.dir,mountAs:u.spec.mountAs,originalRef:f,branch:m.branchName,baseSha:y,deliveryCommit:k,startPoint:y})}let c=[];for(let u of a)try{if(n==="apply"){await u.git.checkout(["-B",u.branch,u.startPoint]),await u.git.raw([..._f,"cherry-pick",u.deliveryCommit]);let g=(await u.git.revparse(["HEAD"])).trim();c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha,appliedSha:g})}else await u.git.checkout(["--detach",u.startPoint]),await u.git.raw([..._f,"cherry-pick","--no-commit",u.deliveryCommit]),await u.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha})}catch(g){return await u.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await As(a,o),{ok:!1,message:`apply failed in ${u.mountAs}: ${Pn(g)} (rolled back all repos)`}}let l=Lr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Of(t.contextDir,l);let d=c.map(u=>u.mountAs).join(", "),p=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}
|
|
765
|
+
${p}
|
|
766
|
+
or: /abort ${r} --reason "..."`}}function Ns(t,e){let r=Lr(t);r[e]&&(delete r[e],Of(t,r))}async function As(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}: ${Pn(n)} \u2014 check manually`)}}async function Df(t,e,r){let o=Lr(t.contextDir)[e];if(o){for(let i of o.repos){let s=En(t.root,i.mountAs);if(!_s(En(s,".git")))continue;let a=js(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}: ${Pn(d)} \u2014 check manually`)}}Ns(t.contextDir,e)}}async function p$(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Pn(t){return t instanceof Error?t.message.trim():String(t)}var qo=Wf(h$(),".codepipe","history"),Uf=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],qf=500,Bf=40;async function Yf(){let t=Pe();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=U(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),zr(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=Lr(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
|
|
767
767
|
\u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
|
|
768
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=
|
|
769
|
-
`))}async function
|
|
770
|
-
`)}`:" (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}
|
|
771
|
-
`),t.unread+=1,
|
|
772
|
-
bye.`),setTimeout(()=>process.exit(0),150))}function
|
|
768
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=Dr.createInterface({input:process.stdin,output:process.stdout,completer:w$,history:U$(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};Dl(s=>Jt(i,s)),i.daemon=Io({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>Jt(i,s),warn:s=>Jt(i,s)},onEvent:s=>j$(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Ls(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await k$(i,a)){Hf(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Ls(i),o.prompt()}),o.on("close",()=>{Hf(i)})}function w$(t){let e=Uf.filter(r=>r.startsWith(t));return[e.length?e:Uf,t]}async function k$(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return b$(),!1;case"/status":return await $$(t),!1;case"/tasks":return await v$(t,n),!1;case"/task":return await x$(t,n),!1;case"/sync":return await S$(t),!1;case"/logs":return _$(t,n),!1;case"/monitor":return N$(t),!1;case"/apply":return await Mf(t,n,"apply"),!1;case"/unstash":return await Mf(t,n,"unstash"),!1;case"/applied":return await R$(t,n),!1;case"/abort":return await T$(t,n),!1;case"/approve":return await Gf(t,n,"approve"),!1;case"/merge":return await Gf(t,n,"merge"),!1;case"/login":return C$(t,n),!1;case"/secret":return P$(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function b$(){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(`
|
|
769
|
+
`))}async function $$(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=Kf(Wf(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function v$(t,e){let r=O$(e,"--phase");try{let n=await Iu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){jn(n)}}async function x$(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Cu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${n.task.phase} \u2014 ${n.task.title}`),n.artifacts.length>0){console.log(" artifacts:");for(let o of n.artifacts)console.log(` ${o.path}`)}}catch(n){jn(n)}}async function S$(t){let e=await xn(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 Mf(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await Lf(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function R$(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=Lr(t.ws.contextDir)[r],i=L$(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,p;if(l>0?(d=c.slice(0,l),p=c.slice(l+1)):(p=c,d=o?.repos.length===1?I$(t,o.repos[0].mountAs):s.length===1?s[0]:""),!d){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${p}`);return}let u=p.match(/(?:pull|pull-requests)\/(\d+)/);if(!u){console.log(` cannot parse PR number from ${p}`);return}a.push({repoName:d,url:p,number:Number(u[1])})}try{let c=await Eu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Ns(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){jn(c)}}async function Gf(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await ju(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){jn(o)}}async function T$(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=D$(e,"--reason")||"local apply aborted";await Df(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await Au(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){jn(o)}}function I$(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function C$(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},z(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 P$(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(`
|
|
770
|
+
`)}`:" (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}E$(t.secrets,n,i),z(t.secrets),zr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}A$(t.secrets,n),z(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function E$(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 A$(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 j$(t,e){switch(e.kind){case"connected":t.connection="connecting",Jt(t,"[hub] connected");break;case"registered":t.connection="registered",Jt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",An(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Jt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",An(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":An(t,`[hub] HUB v${e.hubVersion??"?"} (protocol ${e.hubProtocol??"?"}) is incompatible with this CLI \u2014 WriteActions are refused. Update: ${e.updateCommand}`);break;case"action":e.ok?Jt(t,`[hub] action ${e.actionType} done`):An(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Jt(t,e){t.logBuffer.push(e),t.logBuffer.length>qf&&t.logBuffer.shift(),t.follow&&An(t,e)}function _$(t,e){let r=e[0];if(r==="follow"||r==="on"){Os(t,!0);return}if(r==="off"){Os(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(qf,Number(r)||Bf)):Bf,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 N$(t){Os(t,!t.follow)}function Os(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function An(t,e){Dr.cursorTo(process.stdout,0),Dr.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
771
|
+
`),t.unread+=1,Ls(t),t.rl.prompt(!0)}function Ls(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Ff=!1;function Hf(t){Ff||(Ff=!0,B$(t.rl),t.daemon.stop(),console.log(`
|
|
772
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function O$(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function L$(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 D$(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function jn(t){t instanceof O?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function U$(){if(!Kf(qo))return[];try{return m$(qo,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function B$(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{f$(y$(qo),{recursive:!0}),g$(qo,r.slice().reverse().join(`
|
|
773
773
|
`)+`
|
|
774
|
-
`)}catch{}}Rr();W();Pe();Rr();$e();fe();Sn();import{hostname as L$}from"node:os";import{cancel as D$,confirm as Kf,intro as U$,isCancel as Yf,log as Lr,multiselect as B$,outro as Wf,password as M$,select as Ns,text as Os}from"@clack/prompts";function _n(t){D$(t),process.exit(1)}function Dr(t){return Yf(t)&&_n("aborted"),t}function Wo(t){return Yf(t)&&_n("aborted"),typeof t=="string"?t:""}function Ls(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function qf(t,e){try{let{secret:r}=await vo(t,e);return r}catch(r){throw r instanceof N&&r.status===404&&_n("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 G$(t,e){if(Dr(await Ns({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 Wi(t,e);if(o.length>0)return Dr(await B$({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}));Lr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Lr.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Wo(await Os({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 Ds(t){U$("codepipe worker \u2014 set up this machine as a runner");let e=ge(t.profile);e&&(Lr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Dr(await Kf({message:"re-register this worker?",initialValue:!1}))||_n("keeping the existing registration"));let r=Ue(t.profile)??Ue(),n=Wo(await Os({message:"HUB URL",placeholder:qe,initialValue:M("HUB_URL")??r?.hubUrl??qe,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 Ns({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 qf(n,a),Lr.success("account-issued registration token minted");else if(i==="login"){let u=await Ar();a=(await jr(n,u)).cliToken,s=await qf(n,a),Lr.success("account-issued registration token minted")}else s=Wo(await M$({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||_n("a registration token is required");let c=await G$(n,a),l=Wo(await Os({message:"worker name",initialValue:L$(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),d=Dr(await Ns({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}:{}}),Lr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Dr(await Kf({message:"start the claim-loop now?",initialValue:!0}))){Wf("registered. start later with `codepipe worker`.");return}Wf("starting the claim-loop\u2026"),await bn(t.profile?{profile:t.profile}:{})}function H$(){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=H$();Ya(ae);Ja();var Se=new F$;Se.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ie).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await Hf()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});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 uf({configPath:t.config,skipVerify:t.skipVerify===!0}):await Zp({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 lc({...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 ef({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 rd({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 Kp({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 gf({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 up({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 ks({profile:ae,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Vf=Se.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Vf.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??qe,r=t.token??M("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ls()){await Ds({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 Ht({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)}});Vf.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ge(ae)&&Ls()){await Ds({profile:ae});return}await bn(ae?{profile:ae}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var zf=Se.command("project").description("Manage CodePipe projects");zf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await kf({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});zf.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 $f({...t,cliProfile:ae})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Us=Se.command("repo").description("Manage the project's git repositories");Us.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 Tf({profile:ae,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Us.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 If({profile:ae,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Us.command("list").description("List the project's repos").action(async()=>{try{await Cf({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Se.parseAsync();
|
|
774
|
+
`)}catch{}}Ir();W();ke();Ir();ve();me();Sn();import{hostname as M$}from"node:os";import{cancel as G$,confirm as Vf,intro as F$,isCancel as Xf,log as Ur,multiselect as H$,outro as zf,password as K$,select as Ds,text as Us}from"@clack/prompts";function _n(t){G$(t),process.exit(1)}function Br(t){return Xf(t)&&_n("aborted"),t}function Yo(t){return Xf(t)&&_n("aborted"),typeof t=="string"?t:""}function Bs(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Jf(t,e){try{let{secret:r}=await So(t,e);return r}catch(r){throw r instanceof O&&r.status===404&&_n("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 W$(t,e){if(Br(await Ds({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 es(t,e);if(o.length>0)return Br(await H$({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}));Ur.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Ur.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Yo(await Us({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 Ms(t){F$("codepipe worker \u2014 set up this machine as a runner");let e=he(t.profile);e&&(Ur.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Br(await Vf({message:"re-register this worker?",initialValue:!1}))||_n("keeping the existing registration"));let r=Ue(t.profile)??Ue(),n=Yo(await Us({message:"HUB URL",placeholder:qe,initialValue:B("HUB_URL")??r?.hubUrl??qe,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Br(await Ds({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 Jf(n,a),Ur.success("account-issued registration token minted");else if(i==="login"){let u=await _r();a=(await Nr(n,u)).cliToken,s=await Jf(n,a),Ur.success("account-issued registration token minted")}else s=Yo(await K$({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||_n("a registration token is required");let c=await W$(n,a),l=Yo(await Us({message:"worker name",initialValue:M$(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),d=Br(await Ds({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await Wt({hub:n,token:s,name:l,projects:c,...d?{llm:d}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Ur.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Br(await Vf({message:"start the claim-loop now?",initialValue:!0}))){zf("registered. start later with `codepipe worker`.");return}zf("starting the claim-loop\u2026"),await $n(t.profile?{profile:t.profile}:{})}function Y$(){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 B("PROFILE")}var ce=Y$();Ja(ce);Za();var Re=new q$;Re.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ie).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 Yf()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Re.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await mf({configPath:t.config,skipVerify:t.skipVerify===!0}):await nf({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await pc({...t,profile:ce})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await of({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Re.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await dd({profile:ce})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Re.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await Vp({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await kf({profile:ce,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Re.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await kp({profile:ce})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Re.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await vs({profile:ce,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Qf=Re.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Qf.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??B("HUB_URL")??Ue(ce)?.hubUrl??qe,r=t.token??B("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Bs()){await Ms({profile:ce});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=B("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??B("WORKER_NAME"),i=t.llm??B("WORKER_LLM");await Wt({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ce?{profile:ce}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Qf.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!he(ce)&&Bs()){await Ms({profile:ce});return}await $n(ce?{profile:ce}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Zf=Re.command("project").description("Manage CodePipe projects");Zf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await xf({profile:ce})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Zf.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:ce})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Gs=Re.command("repo").description("Manage the project's git repositories");Gs.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 Ef({profile:ce,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Gs.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 Af({profile:ce,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Gs.command("list").description("List the project's repos").action(async()=>{try{await jf({profile:ce})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Re.parseAsync();
|