@code-partner/codepipe 0.8.2-dev.195.g3b11952 → 0.8.2-dev.196.gb3f64cd
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 +162 -159
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,55 +1,55 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var ak=Object.defineProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var Rn=(t,e)=>{for(var r in e)ak(t,r,{get:e[r],enumerable:!0})};var Le,nt,ps=b(()=>{"use strict";Le="0.8.2-dev.196.gb3f64cd",nt="https://hub.dev.codepipe.dev"});function $o(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=ck&&t<=ot}var ot,ck,Xc=b(()=>{"use strict";ps();ot=4,ck=4});var Jc=b(()=>{"use strict";ps()});function vo(t=4){return`# CodePipe Context Repo format version.
|
|
3
3
|
# Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
|
|
4
4
|
template_version: ${t}
|
|
5
|
-
`}function
|
|
5
|
+
`}function Zc(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 el(t,e=Qc){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 tl(t,e=Qc){return e.filter(r=>r.version>t)}var it,En,Qc,rl=b(()=>{"use strict";it=".codepipe-context.yaml",En=".devpipe-context.yaml",Qc=[{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",it]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[it]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]}]});function xo(t){return`model/facts/identity/${t}.yaml`}function Rr(t){return`model/facts/events/${t}.yaml`}function nl(t){return`model/facts/annotations/${t}.md`}function ol(t){return`model/derived/correlates/${t}.yaml`}function lk(t){return t===""?"root":t.replace(/\//g,"-")}function il(t,e){return`model/derived/structure/${t}/${lk(e)}.yaml`}function hs(t){return typeof t=="string"&&dk.test(t)}function Q(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!uk.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!pk.includes(n)||i===""?null:{level:n,repo:o,path:i}}function ve(t){return`task::${t}`}function pe(t,e,r){return`${t}:${e}:${r}`}function So(t){let e=[];return st(t)?(Ro(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),typeof t.repo!="string"&&e.push("repo: missing (empty string = cross-repo)"),typeof t.builtFromCommit!="string"&&e.push("builtFromCommit: missing"),Array.isArray(t.edges)?t.edges.forEach((r,n)=>{if(!st(r)){e.push(`edges[${n}]: not an object`);return}sl.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),Q(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),Q(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function fk(t){return{...t,edges:Sr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function To(t){return Cr(fk(t))}function st(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ro(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function Ye(t){return typeof t=="string"&&t.length>0}function Ir(t){let e=[];if(!st(t))return{ok:!1,errors:["shard: not an object"]};Ro(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ye(t.repo)||e.push("repo: missing or empty"),Ye(t.builtFromCommit)||e.push("builtFromCommit: missing or empty");let r=typeof t.repo=="string"?t.repo:"",n=new Set;return Array.isArray(t.nodes)?t.nodes.forEach((o,i)=>{if(!st(o)){e.push(`nodes[${i}]: not an object`);return}let s=Q(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!hs(o.entityId)&&e.push(`nodes[${i}].entityId: malformed (${JSON.stringify(o.entityId)})`)}):e.push("nodes: not an array"),Array.isArray(t.edges)?t.edges.forEach((o,i)=>{if(!st(o)){e.push(`edges[${i}]: not an object`);return}sl.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!Ye(o.to)||!Q(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!Ye(o.from)||!n.has(o.from))&&e.push(`edges[${i}].from: "${String(o.from)}" is not a node of this shard`),o.weight!==void 0&&!(typeof o.weight=="number"&&Number.isFinite(o.weight))&&e.push(`edges[${i}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Eo(t){let e=[];if(!st(t))return{ok:!1,errors:["identity: not an object"]};if(Ro(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ye(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!Ye(t.builtFromCommit)&&e.push("builtFromCommit: not a non-empty string"),!Array.isArray(t.entities))e.push("entities: not an array");else{let r=new Set;t.entities.forEach((n,o)=>{if(!st(n)){e.push(`entities[${o}]: not an object`);return}hs(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),Q(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),Ye(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),Ye(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!st(i)||!Q(i.key)||!Ye(i.until))&&e.push(`entities[${o}].aliases[${s}]: malformed`)}):e.push(`entities[${o}].aliases: not an array`))})}return e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Et(t){let e=[];return st(t)?(Ro(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ye(t.taskKey)||e.push("taskKey: missing or empty"),t.origin!=="bootstrap"&&t.origin!=="pipeline"&&e.push("origin: expected bootstrap|pipeline"),t.date!==void 0&&!(typeof t.date=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t.date))&&e.push("date: expected YYYY-MM-DD"),(!Array.isArray(t.commits)||t.commits.some(r=>!Ye(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!st(r)||!Q(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!hs(r.entityId)&&e.push(`files[${n}].entityId: malformed`),r.churn!==void 0&&!(typeof r.churn=="number"&&r.churn>=0)&&e.push(`files[${n}].churn: not a non-negative number`)}):e.push("files: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["event: not an object"]}}function Sr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function mk(t){return{...t,nodes:Sr(t.nodes,e=>e.key),edges:Sr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function gk(t){return{...t,entities:Sr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Sr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function hk(t){let e=t.links?{...t.links,...t.links.adr?{adr:[...t.links.adr].sort()}:{},...t.links.tasks?{tasks:[...t.links.tasks].sort()}:{}}:void 0;return{...t,commits:[...t.commits].sort(),files:Sr(t.files,r=>r.key),...e?{links:e}:{}}}function In(t){return yk.test(t)?t:JSON.stringify(t)}function dl(t){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`model yaml: non-finite number ${t}`);return JSON.stringify(t)}if(typeof t=="string")return JSON.stringify(t);throw new Error(`model yaml: unsupported scalar ${typeof t}`)}function pl(t){return t===null||["boolean","number","string"].includes(typeof t)}function fs(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function fl(t,e,r){if(Array.isArray(t)){for(let n of t)if(pl(n))r.push(`${e}- ${dl(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=fs(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;ms(i,s,c,`${e} `,r)})}}return}for(let[n,o]of fs(t))ms(n,o,e,e,r)}function ms(t,e,r,n,o){if(pl(e))o.push(`${r}${In(t)}: ${dl(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${In(t)}: []`):(o.push(`${r}${In(t)}:`),fl(e,`${n} `,o));else{let i=fs(e);if(i.length===0)o.push(`${r}${In(t)}: {}`);else{o.push(`${r}${In(t)}:`);for(let[s,a]of i)ms(s,a,`${n} `,`${n} `,o)}}}function Cr(t){let e=[];return fl(t,"",e),e.join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`}function rl(t){return Cr(Qy(t))}function nl(t){return Cr(Zy(t))}function Sn(t){return Cr(ek(t))}var ss,xr,Vy,zc,zy,Jy,We,Jc,Xc,Qc,Tr,tk,cs=b(()=>{"use strict";ss="model/derived/INDEX.yaml",xr="model/derived/relates.yaml";Vy=["system","container","component","code","task","adr"],zc=["contains","touched_by","correlates","relates","references","depends_on"],zy=/^e_[0-9a-f]{8}$/;Jy=["system","task","adr"];We={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Jc=2,Xc=5,Qc={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},Tr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};tk=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var ol=b(()=>{"use strict"});var rk,cC,il=b(()=>{"use strict";rk=[{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","AWAITING_CLUSTER"]}],cC=rk.flatMap(t=>t.phases)});function Jt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var sl,ls=b(()=>{"use strict";sl=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function al(t,e){return e.toLowerCase().includes(t.toLowerCase())}function ul(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||ok.every(o=>e.some(i=>al(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 nk){let i=n.find(s=>al(o,s.id));if(i)return i.id}return n[0].id}var ot,cl,Ye,Tn,ll,us,ds,nk,ok,ps=b(()=>{"use strict";ot="claude",cl=[ot],Ye="opus",Tn="sonnet",ll="haiku",us=[Ye,Tn,ll],ds={analyze:Ye,implement:Ye,"resolve-conflict":Ye,rework:Ye,estimate:Tn,build:Tn,"code-review":Ye,draft:Tn,index:Ye,backfill:Ye,analysis:Ye,chat:Ye},nk=[Ye,Tn,ll],ok=Array.from(new Set(Object.values(ds)))});function Tt(t){return ik.has(t)?!0:sk.some(e=>t.startsWith(e))}function xo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Xt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function fs(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function gl(t,e){let r=xo(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Xt(r.id,"id")??n;if(!dl.test(o))throw new Error(`id must match ${dl} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Xt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=xo(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!De.test(d))throw new Error(`env name "${d}" must match ${De}`);if(typeof f!="string"&&typeof f!="number"&&typeof f!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(f)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>pl)throw new Error(`too many params (max ${pl})`);let p=new Set;a=c.map((d,f)=>ak(d,f,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>fl)throw new Error(`too many steps (max ${fl})`);let u=l.map((p,d)=>{let f=xo(p,`steps[${d}]`),m=Xt(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=Xt(f.name,`steps[${d}].name`),k=fs(f.timeout_sec,`steps[${d}].timeout_sec`);if(k!==void 0&&(!Number.isInteger(k)||k<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...g?{name:g}:{},...k!==void 0?{timeout_sec:k}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function ak(t,e,r){let n=xo(t,`params[${e}]`),o=Xt(n.name,`params[${e}].name`);if(!o||!De.test(o))throw new Error(`params[${e}].name must match ${De}`);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 f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=Xt(n.label,`params[${e}].label`),c=Xt(n.help,`params[${e}].help`),l=n.required===!0,u=fs(n.min,`params[${e}].min`),p=fs(n.max,`params[${e}].max`),d=n.default;if(d!=null&&typeof d!="string"&&typeof d!="number"&&typeof d!="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}:{},...u!==void 0?{min:u}:{},...p!==void 0?{max:p}:{},...d!=null?{default:d}:{}}}function hl(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 De,ik,sk,ml,dl,pl,fl,ms=b(()=>{"use strict";De=/^[A-Z][A-Z0-9_]*$/,ik=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),sk=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];ml=600,dl=/^[a-z0-9-]+$/,pl=32,fl=64});function bl(t=ck){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...bl(r.groups));return e}function lk(t,e){let r=JSON.stringify(e);return bl().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function $l(t){let e=lk(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>yl)return{ok:!1,error:`${e.id} must have \u2264 ${yl} entries`};let s={};for(let[a,c]of i){if(!De.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${De}`};if(Tt(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>kl)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${kl} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var yl,kl,wl,ck,vl=b(()=>{"use strict";ms();ls();ps();cs();yl=64,kl=2e3,wl=2e3,ck=[{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:[...cl],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:[...us],help:"Overrides the recommended defaults for every role not listed below."},...sl.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...us],help:`recommended: ${ds[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:wl,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:wl,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."}]},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${We.windowCommits}.`},{id:"context.model.cochange.commit_file_cap",file:"regimen.yaml",path:["context","model","cochange","commit_file_cap"],type:"number",label:"Commit size cap (files)",nullable:!0,min:2,max:500,help:`Commits touching more files are ignored as noise. Default ${We.commitFileCap}.`},{id:"context.model.cochange.support_min",file:"regimen.yaml",path:["context","model","cochange","support_min"],type:"number",label:"Minimum co-occurrences",nullable:!0,min:1,max:100,help:`A pair of files must change together at least this many times. Default ${We.supportMin}.`},{id:"context.model.cochange.jaccard_min_pct",file:"regimen.yaml",path:["context","model","cochange","jaccard_min_pct"],type:"number",label:"Minimum Jaccard (%)",nullable:!0,min:0,max:100,help:`Overlap threshold: |A\u2229B| / |A\u222AB| of the files' commit sets, in percent. Default ${We.jaccardMinPct}.`},{id:"context.model.cochange.half_life_days",file:"regimen.yaml",path:["context","model","cochange","half_life_days"],type:"number",label:"Time-decay half-life (days)",nullable:!0,min:1,max:3650,help:`A commit this old counts half as much. Default ${We.halfLifeDays} (~9 months).`},{id:"context.model.cochange.top_k",file:"regimen.yaml",path:["context","model","cochange","top_k"],type:"number",label:"Edges per file (top-k)",nullable:!0,min:1,max:64,help:`Only the k strongest co-change edges of a file survive \u2014 bounds graph density whatever the thresholds. Default ${We.topK}.`}]},{id:"implementation",label:"Implementation",help:"How a dependency cluster is serialized into branches and PRs.",fields:[{id:"implementation.mode",file:"regimen.yaml",path:["implementation","mode"],type:"enum",label:"Implementation mode",nullable:!0,suggestions:["cluster-pr","sequential","parallel"],help:"cluster-pr (default for new projects) \u2014 one shared branch and a single PR per dependency cluster; a lone task is a cluster of one. sequential / parallel are an explicit opt-out of that. Clearing removes the key from regimen.yaml but keeps the mode already stored for the project (it is not reset to the default)."}]}]});var xl=b(()=>{"use strict"});var Sl=b(()=>{"use strict"});var Tl=b(()=>{"use strict"});function Rl(t){return`codepipe-host-${t}`}var Cl=b(()=>{"use strict"});function El(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 ht(t){return`${t}${uk}`}var Qt,uk,Il=b(()=>{"use strict";Qt=/^[a-z][a-z0-9-]{1,30}$/,uk="-codepipe-ctx"});var Al=b(()=>{"use strict"});var Pl=b(()=>{"use strict"});function Er(t){for(let e of dk){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var dk,_l=b(()=>{"use strict";dk=[{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 jl=b(()=>{"use strict"});var Nl=b(()=>{"use strict"});var Ol=b(()=>{"use strict"});function Dl(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Ml(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Dl(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Ir.test(r))return r;let n=Dl(t);return Ir.test(n)?n:gs}function Ul(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 Cn(t){return`tasks/${t}/issue.yaml`}var Ll,So,gs,Ir,hs,SC,To,Rn,Bl=b(()=>{"use strict";Ll=["bug","feature","epic"],So="feature",gs="TASK",Ir=/^[A-Z][A-Z0-9]{1,9}$/;hs={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},SC=hs.backlog,To="tracker/config.yaml",Rn="tracker/counter"});var Fl=b(()=>{"use strict"});function Ar(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 Ro(t){switch(t){case En.gitlab:return"oauth2";case En.bitbucket:return"x-token-auth";default:return"x-access-token"}}var En,Zt,Kl=b(()=>{"use strict";En={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Zt="x-bitbucket-api-token-auth"});var Gl=b(()=>{"use strict"});var Hl=b(()=>{"use strict";Fl();Kl();Gl()});var Wl,F=b(()=>{"use strict";Uc();Bc();Wc();cs();ol();il();ls();ps();vl();ms();xl();Sl();Tl();Cl();Il();Al();Pl();_l();jl();Nl();Ol();Bl();Hl();Wl=20});function W(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ce=b(()=>{"use strict"});import{existsSync as Yl,renameSync as pk}from"node:fs";function er(t,e,r=n=>console.error(n)){if(Yl(e)||!Yl(t))return!1;try{return pk(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 Co=b(()=>{"use strict"});import{existsSync as Eo,readFileSync as ql,readdirSync as fk,writeFileSync as mk}from"node:fs";import{dirname as gk,join as Rt}from"node:path";import{parse as hk}from"yaml";function yk(t=process.cwd()){let e=t;for(;;){if(Eo(Rt(e,it,"project.yaml")))return e;if(Eo(Rt(e,ys,"project.yaml")))return er(Rt(e,ys),Rt(e,it))&&wk(e),e;let r=gk(e);if(r===e)return null;e=r}}function kk(t){let e=Rt(t,it);return Eo(e)?e:Rt(t,ys)}function wk(t){let e=Rt(t,".gitignore");if(!Eo(e))return;let r=ql(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(`
|
|
8
|
-
`);n!==r&&
|
|
9
|
-
`,{mode:384})}function
|
|
10
|
-
`,{mode:384})}function
|
|
11
|
-
`,{mode:384})}function
|
|
7
|
+
`}function ml(t){return Cr(mk(t))}function gl(t){return Cr(gk(t))}function Cn(t){return Cr(hk(t))}var gs,Tr,uk,sl,dk,pk,qe,al,cl,ll,ys,ul,Er,yk,ks=b(()=>{"use strict";gs="model/derived/INDEX.yaml",Tr="model/derived/relates.yaml";uk=["system","container","component","code","task","adr"],sl=["contains","touched_by","correlates","relates","references","depends_on"],dk=/^e_[0-9a-f]{8}$/;pk=["system","task","adr"];qe={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};al=2,cl=5,ll=50,ys=2e3,ul={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},Er={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};yk=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var hl=b(()=>{"use strict"});var kk,RE,yl=b(()=>{"use strict";kk=[{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","AWAITING_CLUSTER"]}],RE=kk.flatMap(t=>t.phases)});function er(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var kl,ws=b(()=>{"use strict";kl=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function wl(t,e){return e.toLowerCase().includes(t.toLowerCase())}function vl(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||bk.every(o=>e.some(i=>wl(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 wk){let i=n.find(s=>wl(o,s.id));if(i)return i.id}return n[0].id}var at,bl,Ve,An,$l,bs,$s,wk,bk,vs=b(()=>{"use strict";at="claude",bl=[at],Ve="opus",An="sonnet",$l="haiku",bs=[Ve,An,$l],$s={analyze:Ve,implement:Ve,"resolve-conflict":Ve,rework:Ve,estimate:An,build:An,"code-review":Ve,draft:An,index:Ve,backfill:Ve,analysis:Ve,chat:Ve},wk=[Ve,An,$l],bk=Array.from(new Set(Object.values($s)))});function It(t){return $k.has(t)?!0:vk.some(e=>t.startsWith(e))}function Io(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function tr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function xs(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function El(t,e){let r=Io(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=tr(r.id,"id")??n;if(!xl.test(o))throw new Error(`id must match ${xl} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=tr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=Io(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!Me.test(d))throw new Error(`env name "${d}" must match ${Me}`);if(typeof f!="string"&&typeof f!="number"&&typeof f!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(f)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Sl)throw new Error(`too many params (max ${Sl})`);let p=new Set;a=c.map((d,f)=>xk(d,f,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>Tl)throw new Error(`too many steps (max ${Tl})`);let u=l.map((p,d)=>{let f=Io(p,`steps[${d}]`),m=tr(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=tr(f.name,`steps[${d}].name`),k=xs(f.timeout_sec,`steps[${d}].timeout_sec`);if(k!==void 0&&(!Number.isInteger(k)||k<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...g?{name:g}:{},...k!==void 0?{timeout_sec:k}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function xk(t,e,r){let n=Io(t,`params[${e}]`),o=tr(n.name,`params[${e}].name`);if(!o||!Me.test(o))throw new Error(`params[${e}].name must match ${Me}`);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 f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=tr(n.label,`params[${e}].label`),c=tr(n.help,`params[${e}].help`),l=n.required===!0,u=xs(n.min,`params[${e}].min`),p=xs(n.max,`params[${e}].max`),d=n.default;if(d!=null&&typeof d!="string"&&typeof d!="number"&&typeof d!="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}:{},...u!==void 0?{min:u}:{},...p!==void 0?{max:p}:{},...d!=null?{default:d}:{}}}function Il(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 Me,$k,vk,Rl,xl,Sl,Tl,Ss=b(()=>{"use strict";Me=/^[A-Z][A-Z0-9_]*$/,$k=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),vk=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Rl=600,xl=/^[a-z0-9-]+$/,Sl=32,Tl=64});function _l(t=Sk){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(..._l(r.groups));return e}function Tk(t,e){let r=JSON.stringify(e);return _l().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function jl(t){let e=Tk(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>Cl)return{ok:!1,error:`${e.id} must have \u2264 ${Cl} entries`};let s={};for(let[a,c]of i){if(!Me.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Me}`};if(It(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>Al)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Al} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Cl,Al,Pl,Sk,Nl=b(()=>{"use strict";Ss();ws();vs();ks();Cl=64,Al=2e3,Pl=2e3,Sk=[{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:[...bl],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:[...bs],help:"Overrides the recommended defaults for every role not listed below."},...kl.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...bs],help:`recommended: ${$s[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:Pl,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:Pl,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."}]},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${qe.windowCommits}.`},{id:"context.model.cochange.commit_file_cap",file:"regimen.yaml",path:["context","model","cochange","commit_file_cap"],type:"number",label:"Commit size cap (files)",nullable:!0,min:2,max:500,help:`Commits touching more files are ignored as noise. Default ${qe.commitFileCap}.`},{id:"context.model.cochange.support_min",file:"regimen.yaml",path:["context","model","cochange","support_min"],type:"number",label:"Minimum co-occurrences",nullable:!0,min:1,max:100,help:`A pair of files must change together at least this many times. Default ${qe.supportMin}.`},{id:"context.model.cochange.jaccard_min_pct",file:"regimen.yaml",path:["context","model","cochange","jaccard_min_pct"],type:"number",label:"Minimum Jaccard (%)",nullable:!0,min:0,max:100,help:`Overlap threshold: |A\u2229B| / |A\u222AB| of the files' commit sets, in percent. Default ${qe.jaccardMinPct}.`},{id:"context.model.cochange.half_life_days",file:"regimen.yaml",path:["context","model","cochange","half_life_days"],type:"number",label:"Time-decay half-life (days)",nullable:!0,min:1,max:3650,help:`A commit this old counts half as much. Default ${qe.halfLifeDays} (~9 months).`},{id:"context.model.cochange.top_k",file:"regimen.yaml",path:["context","model","cochange","top_k"],type:"number",label:"Edges per file (top-k)",nullable:!0,min:1,max:64,help:`Only the k strongest co-change edges of a file survive \u2014 bounds graph density whatever the thresholds. Default ${qe.topK}.`}]},{id:"implementation",label:"Implementation",help:"How a dependency cluster is serialized into branches and PRs.",fields:[{id:"implementation.mode",file:"regimen.yaml",path:["implementation","mode"],type:"enum",label:"Implementation mode",nullable:!0,suggestions:["cluster-pr","sequential","parallel"],help:"cluster-pr (default for new projects) \u2014 one shared branch and a single PR per dependency cluster; a lone task is a cluster of one. sequential / parallel are an explicit opt-out of that. Clearing removes the key from regimen.yaml but keeps the mode already stored for the project (it is not reset to the default)."}]}]});var Ol=b(()=>{"use strict"});var Dl=b(()=>{"use strict"});var Ll=b(()=>{"use strict"});function Ml(t){return`codepipe-host-${t}`}var Ul=b(()=>{"use strict"});function Bl(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 kt(t){return`${t}${Rk}`}var rr,Rk,Fl=b(()=>{"use strict";rr=/^[a-z][a-z0-9-]{1,30}$/,Rk="-codepipe-ctx"});var Kl=b(()=>{"use strict"});var Gl=b(()=>{"use strict"});function Ar(t){for(let e of Ek){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Ek,Hl=b(()=>{"use strict";Ek=[{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 Wl=b(()=>{"use strict"});var Yl=b(()=>{"use strict"});var ql=b(()=>{"use strict"});function Vl(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Xl(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Vl(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Pr.test(r))return r;let n=Vl(t);return Pr.test(n)?n:Ts}function Jl(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 _n(t){return`tasks/${t}/issue.yaml`}var zl,Co,Ts,Pr,Rs,KE,Ao,Pn,Ql=b(()=>{"use strict";zl=["bug","feature","epic"],Co="feature",Ts="TASK",Pr=/^[A-Z][A-Z0-9]{1,9}$/;Rs={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},KE=Rs.backlog,Ao="tracker/config.yaml",Pn="tracker/counter"});var Zl=b(()=>{"use strict"});function _r(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 Po(t){switch(t){case jn.gitlab:return"oauth2";case jn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var jn,nr,eu=b(()=>{"use strict";jn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};nr="x-bitbucket-api-token-auth"});var tu=b(()=>{"use strict"});var ru=b(()=>{"use strict";Zl();eu();tu()});var nu,K=b(()=>{"use strict";Xc();Jc();rl();ks();hl();yl();ws();vs();Nl();Ss();Ol();Dl();Ll();Ul();Fl();Kl();Gl();Hl();Wl();Yl();ql();Ql();ru();nu=20});function q(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ae=b(()=>{"use strict"});import{existsSync as ou,renameSync as Ik}from"node:fs";function or(t,e,r=n=>console.error(n)){if(ou(e)||!ou(t))return!1;try{return Ik(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 _o=b(()=>{"use strict"});import{existsSync as jo,readFileSync as iu,readdirSync as Ck,writeFileSync as Ak}from"node:fs";import{dirname as Pk,join as Ct}from"node:path";import{parse as _k}from"yaml";function jk(t=process.cwd()){let e=t;for(;;){if(jo(Ct(e,ct,"project.yaml")))return e;if(jo(Ct(e,Es,"project.yaml")))return or(Ct(e,Es),Ct(e,ct))&&Ok(e),e;let r=Pk(e);if(r===e)return null;e=r}}function Nk(t){let e=Ct(t,ct);return jo(e)?e:Ct(t,Es)}function Ok(t){let e=Ct(t,".gitignore");if(!jo(e))return;let r=iu(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(`
|
|
8
|
+
`);n!==r&&Ak(e,n)}function $e(t=process.cwd()){let e=jk(t);if(!e)return null;let r=Nk(e),n=Dk(iu(Ct(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function su(t,e,r){return Ck(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 No(t,e=process.cwd()){try{let r=$e(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Dk(t){let e=_k(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 u=a.host,p=u==="bitbucket"?"bitbucket":u==="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 au(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 ct,Es,lt=b(()=>{"use strict";_o();ct=".codepipe",Es=".devpipe"});import{homedir as cu}from"node:os";import{mkdirSync as Lk,readFileSync as Mk,writeFileSync as Uk,existsSync as Is}from"node:fs";import{dirname as uu,join as Oo,resolve as Bk}from"node:path";import{fileURLToPath as Fk}from"node:url";function du(t){let e=Oo(lu,".env");if(Is(e)&&process.loadEnvFile(e),t){let r=Oo(lu,"profiles",t,".env");Is(r)&&process.loadEnvFile(r)}}function jr(t){let e=q("CONFIG");return e||(t?Oo(cu(),".codepipe","profiles",t,"config.json"):Oo(cu(),".codepipe","config.json"))}function ze(t){let e=jr(t);if(!Is(e))return null;let r=Mk(e,"utf-8");return JSON.parse(r)}function wt(t,e){let r=jr(e);Lk(uu(r),{recursive:!0}),Uk(r,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function Do(t){if(t)return{cfg:Ue(t),profile:t};let e;try{e=$e()?.spec.projectId||void 0}catch{}if(e){let r=ze(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:Ue(void 0),profile:void 0}}function Ue(t){let e=ze(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 ${jr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var lu,Ne=b(()=>{"use strict";Ae();lt();lu=Bk(uu(Fk(import.meta.url)),"..")});import{homedir as gu}from"node:os";import{existsSync as hu,mkdirSync as yu,readFileSync as ku,writeFileSync as wu}from"node:fs";import{dirname as bu,join as $u}from"node:path";function vu(t,e,r){let n=Y(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ee(n)}function xu(t,e){let r=Y(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ee(r),!0)}function Su(t){return Object.keys(Y(t)?.secrets??{}).sort()}function Lo(t,e,r){let n=Y(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,ee(n),"pinned")}function Tu(t,e){let r=Y(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ee(r),!0):!1}function ut(t){return $u(gu(),".codepipe","secrets",`${t}.json`)}function Y(t){let e=ut(t);return hu(e)?JSON.parse(ku(e,"utf-8")):null}function ee(t){let e=ut(t.projectId);yu(bu(e),{recursive:!0}),wu(e,JSON.stringify(t,null,2)+`
|
|
10
|
+
`,{mode:384})}function Mo(){return $u(gu(),".codepipe","shared.json")}function Cs(){let t=Mo();return hu(t)?JSON.parse(ku(t,"utf-8")):null}function Ru(t){let e=Mo();yu(bu(e),{recursive:!0}),wu(e,JSON.stringify(t,null,2)+`
|
|
11
|
+
`,{mode:384})}function Nr(t){let e=Y(t)?.claude?.oauthToken;return e||Cs()?.claude?.oauthToken}function Nn(t){let e={GH_TOKEN:t.github?.token,BITBUCKET_EMAIL:t.bitbucket?.email,BITBUCKET_API_TOKEN:t.bitbucket?.apiToken,GITLAB_TOKEN:t.gitlab?.token,YOUTRACK_URL:t.youtrack?.url,YOUTRACK_TOKEN:t.youtrack?.token};for(let r of As){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Or(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var As,ue=b(()=>{"use strict";As=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as Kk,existsSync as Iu,mkdirSync as Gk,renameSync as Cu,statSync as Hk,unlinkSync as Wk}from"node:fs";import{Writable as Yk}from"node:stream";import{join as qk}from"node:path";function Uo(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Vk(process.env[`${t}_MAX_BYTES`]??String(Au.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Au.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Vk(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 Bo(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(zk(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 zk(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Xk(o)).join(" ");return`${r} ${t} ${n}`}function Xk(t){try{return JSON.stringify(t)}catch{return String(t)}}var Au,Dr,Ps=b(()=>{"use strict";Au={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Dr=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Gk(e.dir,{recursive:!0}),this.currentPath=qk(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
|
|
12
12
|
`)?e:e+`
|
|
13
|
-
`;
|
|
14
|
-
`+t.slice(t.length-e)}async function Ct(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Do);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new Me(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(Lo(i.status))throw new Me(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.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(u.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(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function Mo(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Do);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new Me(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(Lo(s.status))throw new Me(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function Et(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=new AbortController,i=setTimeout(()=>o.abort(),Do);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new Me(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(Lo(s.status))throw new Me(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await Fk(s);throw s.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${a})`):s.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${a})`):s.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${a})`):new Error(`Bitbucket \u2192 ${s.status} ${s.statusText}${a}`)}finally{clearTimeout(i)}}async function Fk(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Uo(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=xu.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: ${xu.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function It(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Do);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new Me(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(Lo(n.status))throw new Me(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function Su(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 Kk(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 xs(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 Ve(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Ts(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Ss(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Rs(e)}return new Cs}var tr,Me,Do,xu,Ss,Ts,Rs,Cs,At=b(()=>{"use strict";tr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},Me=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Do=5e3;xu=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Ss=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 tr(`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()}`)}},Ts=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 tr(`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 u=await i.json();for(let p of u.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 u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.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??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let f=(await d.json()).jobs??[];for(let m of f.filter(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${m.id}/logs`,{headers:n});if(!g.ok)continue;let k=await g.text();u.push(`### CI job: ${m.name}
|
|
15
|
-
|
|
16
|
-
${
|
|
17
|
-
|
|
18
|
-
`),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()}`)}},
|
|
19
|
-
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Yk(t,e,r){return new Promise((n,o)=>{let i=Pt.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 Cu(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Es(t,e,r){return new Promise(n=>{let o=Pt.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 qk(t){try{let e=await fetch(t);return e.ok?new Cu(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function _u(t,e=443,r=Iu){let n=`${t}:${e}`,o=Ru.get(n);if(o)return o;let i=Vk(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Ru.set(n,i),i}async function Vk(t,e,r){if(!Eu)return!1;let n=8e3;if(await Es(t,e,n))return!0;let o=await Yk(t,e,n),i=Pt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Wk(o);if(!c)break;let l=await qk(c);if(!l)break;if(s.push(l.toString()),Pt.setDefaultCACertificates([...i,...s]),await Es(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 Es(t,e,n)}var Eu,Tu,Ru,Iu,ju=b(()=>{"use strict";Ce();Eu=typeof Pt.getCACertificates=="function"&&typeof Pt.setDefaultCACertificates=="function",Tu=!1,Ru=new Map,Iu=t=>console.warn(t)});function Lu(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Ue(t,e,r){Au();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(Pu(s)&&await _u(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function zk(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Jk(){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 Is(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Jk(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Ue(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&zk(l.status,u)){await Nu(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Nu(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 Ue(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 Mu(t){try{let e=await Ue(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Xk(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Ou.get(o);if(i)return i;let s=await Ue(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(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return Ou.set(o,l.id),l.id}async function Uu(t,e,r,n=An){let o=await Xk(t,e,r,n);await Is(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 Bu(t,e,r){return await(await Is(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Fu(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Is(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Ku(t,e){let r=Du.get(e);if(r)return r;let n=await Ue(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 Du.set(e,i.id),i.id}async function Gu(t,e,r,n,o,i=An){let s=await Ku(t,e),a=await Ue(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 Hu(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Ue(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 qu(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 Vu(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 zu(t,e){let r=e.stageField??An,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=${Yu}&$top=200`,s=await Ue(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Qu(c,r))}async function Ju(t,e,r=An){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Yu}`,o=await Ue(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Qu(await o.json(),r)}async function Xu(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Zk}&$top=500`,o=await Ue(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=qu(s.attachments);return c&&(a.attachments=c),a})}function ew(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 Qu(t,e=An){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=qu(t.attachments);a&&(s.attachments=a);let c=ew(t.links);return c&&(s.links=c),s}async function Zu(t,e){let r=await tw(t,e);return r.length>0?r:rw(t,e)}async function tw(t,e){let r=await Ku(t,e),n=await Ue(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:ed(s.bundle)});return i}async function rw(t,e){let r=`project: ${e}`,n=await Ue(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:ed(s.projectCustomField?.bundle)});return i}function ed(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Nu,An,Ou,Du,Wu,Qk,Yu,Zk,rr=b(()=>{"use strict";ju();Nu=t=>new Promise(e=>setTimeout(e,t));An="Stage",Ou=new Map;Du=new Map;Wu="attachments(id,name,url,size,mimeType)",Qk="links(direction,linkType(name),issues(idReadable))",Yu=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Wu},${Qk}`,Zk=`id,text,created,author(login),${Wu}`});function ze(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function Or(t){return t instanceof Me}async function td(t,e){let r=H(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:ze(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:ze(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 Ct(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Or(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:ze(c)}),o.push({kind:"github",present:!0,ok:!1,detail:ze(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 Et(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){Or(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:ze(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:ze(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await It(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Or(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:ze(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:ze(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 u of e?.repos??[])if(u.host==="github")try{await Mo(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){Or(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:ze(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Mo(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){Or(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:ze(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Mo(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){Or(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:ze(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=_r(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 jt(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 jt(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 rd(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 Dr=b(()=>{"use strict";ie();At();rr()});import nw from"node:http";import As from"node:crypto";function Bo(){let t=Ps(As.randomBytes(32)),e=Ps(As.createHash("sha256").update(t).digest()),r=Ps(As.randomBytes(32));return{verifier:t,challenge:e,state:r}}function js(t){let e=new URL(ow);return e.search=new URLSearchParams({response_type:"code",client_id:nd,redirect_uri:t.redirectUri,scope:sw,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function cw(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 od(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 lw(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 Ns(t){let e=await fetch(iw,{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:nd,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return lw(await e.json())}async function Os(t){let e=t.timeoutMs??aw,r=nw.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=js({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let f=new URL(p.url??"/",o);if(f.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(cw(f.searchParams,t.state))}catch(m){u(m)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>Ns({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function id(t){let e=await Os(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
|
|
20
|
-
${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var
|
|
21
|
-
${l.trim()}`)}}let i=
|
|
22
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function
|
|
23
|
-
${h.trim()}`)}}let g=(await t.revparse(["HEAD"])).trim(),k=r.push!==!1;if(k){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:g,pushed:k}}async function
|
|
24
|
-
${v.trim()}`)}let w=(await k.revparse(["HEAD"])).trim();return await t.raw(["branch","-f",c,w]),{commit:w,branch:c}}finally{await t.raw(["worktree","remove","--force",g]).catch(()=>{}),
|
|
13
|
+
`;Kk(this.currentPath,r,"utf-8")}asWritable(){return new Yk({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||!Iu(this.currentPath)||Hk(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Iu(n)&&(r>=this.cfg.maxFiles?Wk(n):Cu(n,`${this.currentPath}.${r+1}`))}Cu(this.currentPath,`${this.currentPath}.1`)}}}});import{createHash as Jk}from"node:crypto";import{existsSync as Qk,readFileSync as Zk}from"node:fs";import{homedir as ew,hostname as _s}from"node:os";import{join as tw}from"node:path";function Pu(t){return Jk("sha256").update(t).digest("hex").slice(0,12)}function rw(){let t=q("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=tw(ew(),".claude","credentials.json");if(!Qk(e))return;let r=JSON.parse(Zk(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 _u(t){let e=rw(),r=q("ACCOUNT_ID")?.trim(),n=q("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Nr(t);return o?{accountId:`acct-${Pu(o)}`,label:n||_s(),...e?{email:e}:{}}:{accountId:`acct-${Pu(`host:${_s()}`)}`,label:n||_s(),...e?{email:e}:{}}}var ju=b(()=>{"use strict";Ae();ue()});function Ko(t){return t===429||t>=500}function Nu(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
14
|
+
`+t.slice(t.length-e)}async function At(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Fo);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new Be(`cannot reach api.github.com (${l instanceof Error?l.message:String(l)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(Ko(i.status))throw new Be(`api.github.com \u2192 ${i.status} ${i.statusText}`);if(!i.ok)throw new Error(`GitHub \u2192 ${i.status} ${i.statusText}`);let a=(await i.json()).login??"ok",c=i.headers.get("x-oauth-scopes");if(c!==null&&e&&!c.split(",").map(u=>u.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${c||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let l;try{let u=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});u.ok&&(l=(await u.json()).type)}catch{}if(l==="Organization"){let u=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r,signal:n.signal});if(u.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(u.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(!u.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${u.status} ${u.statusText}`)}}return a}finally{clearTimeout(o)}}async function Go(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Fo);try{let s;try{s=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},signal:o.signal})}catch(c){throw new Be(`cannot reach api.github.com (${c instanceof Error?c.message:String(c)})`)}if(s.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(s.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(Ko(s.status))throw new Be(`api.github.com \u2192 ${s.status} ${s.statusText}`);if(!s.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${s.status} ${s.statusText}`);if((await s.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}finally{clearTimeout(i)}}async function Pt(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=new AbortController,i=setTimeout(()=>o.abort(),Fo);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new Be(`cannot reach api.bitbucket.org (${c instanceof Error?c.message:String(c)})`)}if(s.ok)return t;if(s.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;if(Ko(s.status))throw new Be(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await nw(s);throw s.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${a})`):s.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${a})`):s.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${a})`):new Error(`Bitbucket \u2192 ${s.status} ${s.statusText}${a}`)}finally{clearTimeout(i)}}async function nw(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Ho(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=Ou.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: ${Ou.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function _t(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Fo);try{let n;try{n=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"},signal:e.signal})}catch(i){throw new Be(`cannot reach gitlab.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(Ko(n.status))throw new Be(`gitlab.com \u2192 ${n.status} ${n.statusText}`);if(!n.ok)throw new Error(`GitLab \u2192 ${n.status} ${n.statusText}`);return(await n.json()).username??"ok"}finally{clearTimeout(r)}}async function Du(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 ow(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 js(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 Xe(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Os(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Ns(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Ds(e)}return new Ls}var ir,Be,Fo,Ou,Ns,Os,Ds,Ls,jt=b(()=>{"use strict";ir=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},Be=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Fo=5e3;Ou=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Ns=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 ir(`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()}`)}},Os=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 ir(`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 u=await i.json();for(let p of u.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 u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.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??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let f=(await d.json()).jobs??[];for(let m of f.filter(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${m.id}/logs`,{headers:n});if(!g.ok)continue;let k=await g.text();u.push(`### CI job: ${m.name}
|
|
15
|
+
|
|
16
|
+
${Nu(k,8e3)}`)}}return u.length===0?void 0:Nu(u.join(`
|
|
17
|
+
|
|
18
|
+
`),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()}`)}},Ds=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 ir(`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=ow(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 u=await a.json().catch(()=>null);s=u?.sha??u?.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()}`)}};Ls=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(js(e,r,"merge"))}async closePR(e,r,n){throw new Error(js(e,r,"close"))}async addPRComment(e,r,n){throw new Error(js(e,r,"comment"))}}});import{X509Certificate as Uu}from"node:crypto";import{readFileSync as iw}from"node:fs";import Nt from"node:tls";function sw(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Ku(t=Fu){if(Lu)return;Lu=!0;let e=q("EXTRA_CA_FILE");if(!(!e||!Bu))try{let r=sw(iw(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Nt.setDefaultCACertificates([...Nt.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 Gu(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 aw(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
19
|
+
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function cw(t,e,r){return new Promise((n,o)=>{let i=Nt.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 Uu(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Ms(t,e,r){return new Promise(n=>{let o=Nt.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 lw(t){try{let e=await fetch(t);return e.ok?new Uu(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Hu(t,e=443,r=Fu){let n=`${t}:${e}`,o=Mu.get(n);if(o)return o;let i=uw(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Mu.set(n,i),i}async function uw(t,e,r){if(!Bu)return!1;let n=8e3;if(await Ms(t,e,n))return!0;let o=await cw(t,e,n),i=Nt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=aw(o);if(!c)break;let l=await lw(c);if(!l)break;if(s.push(l.toString()),Nt.setDefaultCACertificates([...i,...s]),await Ms(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 Ms(t,e,n)}var Bu,Lu,Mu,Fu,Wu=b(()=>{"use strict";Ae();Bu=typeof Nt.getCACertificates=="function"&&typeof Nt.setDefaultCACertificates=="function",Lu=!1,Mu=new Map,Fu=t=>console.warn(t)});function zu(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Fe(t,e,r){Ku();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(Gu(s)&&await Hu(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function dw(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function pw(){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 Us(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=pw(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Fe(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&dw(l.status,u)){await Yu(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Yu(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Ot(t){let e;try{e=await Fe(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 Xu(t){try{let e=await Fe(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function fw(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=qu.get(o);if(i)return i;let s=await Fe(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(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return qu.set(o,l.id),l.id}async function Ju(t,e,r,n=On){let o=await fw(t,e,r,n);await Us(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 Qu(t,e,r){return await(await Us(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Zu(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Us(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function ed(t,e){let r=Vu.get(e);if(r)return r;let n=await Fe(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 Vu.set(e,i.id),i.id}async function td(t,e,r,n,o,i=On){let s=await ed(t,e),a=await Fe(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 rd(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Fe(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 id(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 sd(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 ad(t,e){let r=e.stageField??On,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=${od}&$top=200`,s=await Fe(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>ud(c,r))}async function cd(t,e,r=On){let n=`/api/issues/${encodeURIComponent(e)}?fields=${od}`,o=await Fe(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return ud(await o.json(),r)}async function ld(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${gw}&$top=500`,o=await Fe(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=id(s.attachments);return c&&(a.attachments=c),a})}function hw(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 ud(t,e=On){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=id(t.attachments);a&&(s.attachments=a);let c=hw(t.links);return c&&(s.links=c),s}async function dd(t,e){let r=await yw(t,e);return r.length>0?r:kw(t,e)}async function yw(t,e){let r=await ed(t,e),n=await Fe(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:pd(s.bundle)});return i}async function kw(t,e){let r=`project: ${e}`,n=await Fe(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:pd(s.projectCustomField?.bundle)});return i}function pd(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Yu,On,qu,Vu,nd,mw,od,gw,sr=b(()=>{"use strict";Wu();Yu=t=>new Promise(e=>setTimeout(e,t));On="Stage",qu=new Map;Vu=new Map;nd="attachments(id,name,url,size,mimeType)",mw="links(direction,linkType(name),issues(idReadable))",od=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${nd},${mw}`,gw=`id,text,created,author(login),${nd}`});function Je(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function Lr(t){return t instanceof Be}async function fd(t,e){let r=Y(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 Ot({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:Je(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Je(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 At(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Lr(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:Je(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Je(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 Pt(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){Lr(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:Je(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Je(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await _t(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Lr(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:Je(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Je(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 u of e?.repos??[])if(u.host==="github")try{await Go(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){Lr(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:Je(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Go(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){Lr(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:Je(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Go(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){Lr(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:Je(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=Nr(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 Dt(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 Dt(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 md(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 Mr=b(()=>{"use strict";ue();jt();sr()});import ww from"node:http";import Bs from"node:crypto";function Wo(){let t=Fs(Bs.randomBytes(32)),e=Fs(Bs.createHash("sha256").update(t).digest()),r=Fs(Bs.randomBytes(32));return{verifier:t,challenge:e,state:r}}function Gs(t){let e=new URL(bw);return e.search=new URLSearchParams({response_type:"code",client_id:gd,redirect_uri:t.redirectUri,scope:vw,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function Sw(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 hd(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 Tw(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 Hs(t){let e=await fetch($w,{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:gd,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return Tw(await e.json())}async function Ws(t){let e=t.timeoutMs??xw,r=ww.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=Gs({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let f=new URL(p.url??"/",o);if(f.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(Sw(f.searchParams,t.state))}catch(m){u(m)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>Hs({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function yd(t){let e=await Ws(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
|
|
20
|
+
${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var gd,bw,$w,Ks,vw,xw,Fs,Ys=b(()=>{"use strict";gd="9d1c250a-e61b-44d9-88ed-5944d1962f5e",bw="https://platform.claude.com/oauth/authorize",$w="https://platform.claude.com/v1/oauth/token",Ks="https://platform.claude.com/oauth/code/callback",vw="org:create_api_key user:profile user:inference",xw=12e4,Fs=t=>Buffer.from(t).toString("base64url")});async function kd(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(q("ORIGIN")==="farm"||q("CLAUDE_AUTOLOGIN")==="0"){s("autologin_disabled");return}let a;try{a=await Ws(Wo())}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 Dt(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 u=Y(t.projectId);if(!u){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}u.claude={oauthToken:c.oauthToken},ee(u),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()}}var wd=b(()=>{"use strict";Ae();Mr();ue();Ys()});function bd(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?q("ORIGIN")==="farm"||q("CLAUDE_AUTOLOGIN")==="0"||e?"none":"open":r?.ok===!0?"rearm":"none"}function $d(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}var vd=b(()=>{"use strict";Ae()});import{spawn as Rw}from"node:child_process";function ar(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Rw(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var Yo=b(()=>{"use strict"});import{setTimeout as Ew}from"node:timers/promises";import Iw from"ws";function qo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Iw(r)}async function Lt(t,e,r){return Qe(t,e,"/projects",r)}async function xd(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new G(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Vo(t,e,r,n){return Qe(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Sd(t,e,r,n){return Qe(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Td(t,e,r,n){return Qe(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Rd(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 G(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function zo(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new G(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function qs(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new G(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Ed(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await qs(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 Ew(r.delayMs??1500)}throw o}async function Id(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 Dn(e)}if(!r.ok)throw new G(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Cd(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new G(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Ad(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new G(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Pd(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 G(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Vs(t,e,r,n){return Qe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function _d(t,e,r,n,o){return Qe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function jd(t,e,r,n,o){return Qe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function Nd(t,e,r,n,o){return Qe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Ln(t,e,r,n){return Qe(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function zs(t,e,r,n){await Qe(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Od(t,e,r,n){return Qe(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Dd(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 G(o.status,s,a)}return s}async function te(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new G(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function Qe(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 G(o.status,s,a)}return s}var G,Dn,xe=b(()=>{"use strict";G=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};Dn=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});function Md(t){Ld=t}function cr(t,e="info"){Ld(t,e)}var Ld,Xo=b(()=>{"use strict";Ld=t=>console.log(t)});import{homedir as Cw,tmpdir as Aw}from"node:os";import{existsSync as Pw,mkdirSync as _w,mkdtempSync as jw,rmSync as Nw}from"node:fs";import{join as Mn}from"node:path";import{simpleGit as Jo}from"simple-git";function Re(t,e,r){let n=r??Mn(Cw(),".codepipe","repos");return Mn(n,t,e)}async function ur(t,e,r={}){let n=Re(t,e.name,r.baseDir),o=r.cloneUrlOverride??Bn(e);if(!Pw(Mn(n,".git"))){_w(n,{recursive:!0});let a=Jo();cr(`[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}
|
|
21
|
+
${l.trim()}`)}}let i=Jo(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
|
|
22
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function lr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function dr(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&&cr(`[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 lr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await lr(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([...Qo,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Un(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await lr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await lr(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 Ud(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:p}=r,d=await Un(t,i,()=>dr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let f=`origin/${c}`;if(await lr(t,f)||(f=`origin/${u??c}`),(await t.revparse([f])).trim()===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{await t.checkout(["-B",a,f]);try{await t.raw([...Qo,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let h=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
23
|
+
${h.trim()}`)}}let g=(await t.revparse(["HEAD"])).trim(),k=r.push!==!1;if(k){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:g,pushed:k}}async function Bd(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 Fd(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await Un(t,i,()=>dr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function Kd(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,baseRef:a,branchName:c,commitMessage:l,defaultBranch:u}=r,p=await Un(t,i,()=>dr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));await t.fetch().catch(()=>{});let d=`origin/${a}`;if(await lr(t,d)||(d=`origin/${u??a}`),(await t.revparse([d])).trim()===s)return await t.raw(["branch","-f",c,p]),{commit:p,branch:c};let m=jw(Mn(Aw(),"codepipe-apply-")),g=Mn(m,"wt");try{await t.raw(["worktree","add","--detach",g,d]);let k=Jo(g);try{await k.raw([...Qo,"cherry-pick",p])}catch(h){await k.raw(["cherry-pick","--abort"]).catch(()=>{});let v=h instanceof Error?h.message:String(h);throw new Error(`cherry-pick of ${i.slice(0,10)} onto ${a} hit conflicts
|
|
24
|
+
${v.trim()}`)}let w=(await k.revparse(["HEAD"])).trim();return await t.raw(["branch","-f",c,w]),{commit:w,branch:c}}finally{await t.raw(["worktree","remove","--force",g]).catch(()=>{}),Nw(m,{recursive:!0,force:!0}),await t.raw(["worktree","prune"]).catch(()=>{})}}async function Gd(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await lr(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
|
|
25
25
|
`).map(f=>f.trim()).filter(f=>f.length>0),l=new Set(o.map(f=>f.toUpperCase())),u=[],p=0;for(let f of c)(await t.raw(["show","-s","--format=%(trailers:key=CodePipe-Task,valueonly)",f])).split(`
|
|
26
|
-
`).map(k=>k.trim().toUpperCase()).filter(k=>k.length>0).some(k=>l.has(k))?p++:u.push(f);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let f of u)try{await t.raw([...
|
|
27
|
-
${g.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function
|
|
28
|
-
`).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
|
|
29
|
-
`)}async function
|
|
26
|
+
`).map(k=>k.trim().toUpperCase()).filter(k=>k.length>0).some(k=>l.has(k))?p++:u.push(f);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let f of u)try{await t.raw([...Qo,"cherry-pick","--allow-empty","--keep-redundant-commits",f])}catch(m){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let g=m instanceof Error?m.message:String(m);throw new Error(`rewrite_cluster_branch: replaying ${f.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
|
|
27
|
+
${g.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function Hd(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 Bn(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 Wd(t){return(await Jo().listRemote(["--heads",t])).split(`
|
|
28
|
+
`).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 Yd(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var Qo,Ur=b(()=>{"use strict";Xo();Qo=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{existsSync as ei,readFileSync as Ow,writeFileSync as Dw}from"node:fs";import{join as fr}from"node:path";import{simpleGit as Zo}from"simple-git";function Vd(t){return fr(t,Lw)}function mr(t){let e=Vd(t);if(!ei(e))return{};try{return JSON.parse(Ow(e,"utf-8"))}catch{return{}}}function Js(t,e){Dw(Vd(t),JSON.stringify(e,null,2)+`
|
|
29
|
+
`)}async function zd(t,e,r,n,o){let i;try{i=await Vs(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(d){return{ok:!1,message:`claim failed: ${d instanceof Error?d.message:String(d)}`}}let s=[];for(let d of i.repos){let f=t.spec.repos.find(w=>w.name===d.repoName);if(!f)return{ok:!1,message:`repo "${d.repoName}" not in project.yaml \u2014 run /sync`};let m=fr(t.root,f.mountAs);if(!ei(fr(m,".git")))return{ok:!1,message:`${f.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Zo(m).status()).isClean())return{ok:!1,message:`${f.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:d,spec:f,dir:m})}let a=[];for(let d of s){let f=Zo(d.dir),m=await Mw(f),g=d.claimRepo;try{await f.fetch()}catch(h){return await Xs(a,o),{ok:!1,message:`fetch failed in ${d.spec.mountAs}: ${pr(h)}`}}let k=`origin/${g.baseRef}`,w;try{w=await dr(f,{contextRepoCloneUrl:g.contextRepoCloneUrl,deliveryRef:g.deliveryRef,deliverySha:g.deliverySha,baseSha:g.baseSha,commitMessage:g.commitMessage})}catch(h){return await Xs(a,o),{ok:!1,message:`fetch delivery failed in ${d.spec.mountAs}: ${pr(h)}`}}a.push({git:f,dir:d.dir,mountAs:d.spec.mountAs,originalRef:m,branch:g.branchName,baseSha:k,deliveryCommit:w,startPoint:k})}let c=[];for(let d of a)try{if(n==="apply"){await d.git.checkout(["-B",d.branch,d.startPoint]),await d.git.raw([...qd,"cherry-pick",d.deliveryCommit]);let f=(await d.git.revparse(["HEAD"])).trim();c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha,appliedSha:f})}else await d.git.checkout(["--detach",d.startPoint]),await d.git.raw([...qd,"cherry-pick","--no-commit",d.deliveryCommit]),await d.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha})}catch(f){return await d.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Xs(a,o),{ok:!1,message:`apply failed in ${d.mountAs}: ${pr(f)} (rolled back all repos)`}}let l=mr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Js(t.contextDir,l);let u=c.map(d=>d.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 ${u}
|
|
30
30
|
${p}
|
|
31
|
-
or: /abort ${r} --reason "..."`}}async function
|
|
31
|
+
or: /abort ${r} --reason "..."`}}async function Xd(t,e,r){let n=[];for(let c of e.repos){let l=t.repos.find(p=>p.name===c.repoName);if(!l)return{ok:!1,message:`repo "${c.repoName}" not in project.yaml \u2014 run /sync`};let u=fr(t.root,l.mountAs);if(!ei(fr(u,".git")))return{ok:!1,message:`${l.mountAs}/ not cloned \u2014 run /sync first`};n.push({git:Zo(u),dir:u,spec:l,cr:c})}let o=[],i=[];for(let c of n)try{let{commit:l}=await Kd(c.git,c.dir,{contextRepoCloneUrl:c.cr.contextRepoCloneUrl,deliveryRef:c.cr.deliveryRef,deliverySha:c.cr.deliverySha,baseSha:c.cr.baseSha,baseRef:c.cr.baseRef,branchName:c.cr.branchName,commitMessage:c.cr.commitMessage,defaultBranch:c.spec.defaultBranch});r.info(`[apply] ${e.taskKey}: ${c.cr.branchName} \u2192 ${c.spec.mountAs} (${l.slice(0,10)})`),o.push({git:c.git,branch:c.cr.branchName}),i.push({mountAs:c.spec.mountAs,branch:c.cr.branchName,baseSha:`origin/${c.cr.baseRef}`,appliedSha:l})}catch(l){for(let u of o)await u.git.raw(["branch","-D",u.branch]).catch(()=>{});return{ok:!1,message:`auto-apply failed in ${c.spec.mountAs}: ${pr(l)}`}}try{await Vs(t.hubUrl,t.cliToken,t.projectId,e.taskKey)}catch(c){return{ok:!1,message:`branch created but claim failed: ${pr(c)} \u2014 retried on the next reconnect`,branches:o.map(l=>l.branch)}}let s=mr(t.contextDir);s[e.taskKey]={mode:"apply",claimedAt:new Date().toISOString(),repos:i},Js(t.contextDir,s);let a=i.map(c=>`${c.branch} (${c.mountAs})`).join(", ");return{ok:!0,branches:i.map(c=>c.branch),message:`branch created locally without touching your checkout: ${a}
|
|
32
32
|
review, push, then: /applied ${e.taskKey} --pr <url>
|
|
33
|
-
or: /abort ${e.taskKey} --reason "..."`}}function
|
|
33
|
+
or: /abort ${e.taskKey} --reason "..."`}}function Qs(t,e){let r=mr(t);r[e]&&(delete r[e],Js(t,r))}async function Xs(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}: ${pr(n)} \u2014 check manually`)}}async function Jd(t,e,r){let o=mr(t.contextDir)[e];if(o){for(let i of o.repos){let s=fr(t.root,i.mountAs);if(!ei(fr(s,".git")))continue;let a=Zo(s),c=t.spec.repos.find(u=>u.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(u){r.warn(`rollback failed in ${i.mountAs}: ${pr(u)} \u2014 check manually`)}}Qs(t.contextDir,e)}}async function Mw(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function pr(t){return t instanceof Error?t.message.trim():String(t)}var qd,Lw,Zs=b(()=>{"use strict";xe();Ur();qd=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Lw="apply-queue.json"});import{existsSync as Uw}from"node:fs";import{join as Bw}from"node:path";import{simpleGit as Fw}from"simple-git";async function Qd(t,e){if(!Uw(Bw(t,".git")))return{status:"skipped"};let r=Fw(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Kw(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 Kw(t){return t instanceof Error?t.message.trim():String(t)}var Zd=b(()=>{"use strict"});import{existsSync as ep,readFileSync as tp,readdirSync as Gw,statSync as Hw}from"node:fs";import{join as ea}from"node:path";import{parse as rp}from"yaml";function ti(t){let e=ea(t,"actions"),r=[],n=[];if(!ep(e))return{defs:r,errors:n};let o;try{o=Gw(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=ea(e,s);try{if(!Hw(a).isFile())continue;let c=El(s,rp(tp(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 np(t){let e={},r=ea(t,"project.yaml");if(!ep(r))return e;let n;try{n=rp(tp(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))!Me.test(i)||It(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var ta=b(()=>{"use strict";K()});import{existsSync as ra,readFileSync as op,readdirSync as Ww,watch as Yw}from"node:fs";import{join as Fn}from"node:path";var ri,ip=b(()=>{"use strict";ta();ri=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,Fn(this.contextDir,"prompts"),Fn(this.contextDir,"actions")];for(let n of r)if(ra(n))try{let o=Yw(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=ti(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=Fn(this.contextDir,e);if(!ra(r))return null;try{return op(r,"utf-8")}catch{return null}}readPrompts(){let e=Fn(this.contextDir,"prompts"),r={};if(!ra(e))return r;let n;try{n=Ww(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=op(Fn(e,o),"utf-8")}catch{}}return r}}});import{existsSync as Mt,mkdirSync as sp,readFileSync as na,writeFileSync as Br}from"node:fs";import{homedir as qw}from"node:os";import{join as dt}from"node:path";import{simpleGit as Vw}from"simple-git";function Kn(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=dt(t,o);Mt(s)||(Br(s,i),r.push(o))}return r}function gr(t,e,r){let n=dt(qw(),".codepipe","profiles",t,"context-config");return sp(n,{recursive:!0}),Br(dt(n,"project.yaml"),e.projectYaml),Br(dt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function ni(t,e,r){if(Mt(e))for(let n of Fr){let o=dt(e,n),i=dt(t,n);if(!(!Mt(o)||Mt(i)))try{Br(i,na(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 Kr(t){let e=dt(t,".gitignore"),r=Mt(e)?na(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Fr.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
34
34
|
`)?"":`
|
|
35
|
-
`;return
|
|
35
|
+
`;return Br(e,r+i+zw.join(`
|
|
36
36
|
`)+`
|
|
37
|
-
`),!0}async function
|
|
38
|
-
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;
|
|
39
|
-
`)){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);
|
|
37
|
+
`),!0}async function ap(t,e){try{if(!Mt(dt(t,".git")))return;let r=Vw(t),n=(await r.raw(["ls-files","--",...Fr])).split(`
|
|
38
|
+
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;Kr(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 sa(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 oa(t){let e=new Map;for(let r of Fr){let n=dt(t,r);Mt(n)&&e.set(r,na(n))}return e}function ia(t,e){sp(t,{recursive:!0});for(let[r,n]of e){let o=dt(t,r);Mt(o)||Br(o,n)}}var Fr,zw,bt=b(()=>{"use strict";Ze();Fr=["project.yaml","regimen.yaml"];zw=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Xw,mkdirSync as Jw,rmSync as Qw,writeFileSync as aa}from"node:fs";import{dirname as Zw,isAbsolute as eb,join as up,normalize as si}from"node:path";import{simpleGit as dp}from"simple-git";async function ca(t,e){let r=si(t),o=(ii.get(r)??Promise.resolve()).catch(()=>{}).then(e);ii.set(r,o);try{return await o}finally{ii.get(r)===o&&ii.delete(r)}}async function Se(t,e,r){return ca(t,()=>la(t,e,r))}async function la(t,e,r){if(!Xw(up(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=we(t,a.path);if(a.deleted){Qw(c,{force:!0});continue}Jw(Zw(c),{recursive:!0}),a.encoding==="base64"?aa(c,Buffer.from(a.content,"base64")):aa(c,a.content)}let n=dp(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+=oi)await n.raw(["add","-A","-f","--",...o.slice(a,a+oi)]);for(let a=0;a<i.length;a+=oi)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+oi)]);await n.raw(["reset","-q","--",...Fr]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await sa(t))}async function sa(t){let e=dp(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=cp;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 ob(e);if(i.length>0&&i.every(a=>tb.has(a)||lp.test(a)||rb.test(a))){for(let a of i)lp.test(a)?await nb(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 ${cp} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function nb(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(`
|
|
39
|
+
`)){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);aa(we(e,r),i.join(`
|
|
40
40
|
`)+(i.length>0?`
|
|
41
|
-
`:""))}async function
|
|
42
|
-
`).map(r=>r.trim()).filter(Boolean)}function
|
|
43
|
-
`),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
|
|
41
|
+
`:""))}async function ob(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
42
|
+
`).map(r=>r.trim()).filter(Boolean)}function we(t,e){if(eb(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=si(up(t,e)),n=si(t+"/");if(r!==si(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var cp,tb,rb,lp,oi,ii,Ze=b(()=>{"use strict";bt();cp=3,tb=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),rb=/^model\/derived\//,lp=/^tasks\/[^/]+\/comments\.jsonl$/,oi=500,ii=new Map});import{existsSync as ua,readFileSync as pp,readdirSync as ib}from"node:fs";import{join as fp}from"node:path";import{simpleGit as sb}from"simple-git";function lb(t){let e=t.split(`
|
|
43
|
+
`),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 ub(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
44
44
|
`),a=s.findIndex(w=>w.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,f=a>=0?a+1:0;for(let w=f;w<s.length;w++){let h=(s[w]??"").trim();if(h===""){f=w+1;continue}let v=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(h);if(!v)break;let T=(v[1]??"").trim().toLowerCase(),R=(v[2]??"").trim(),x=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(h);x&&(d=parseInt(x[1]??"",10)),T==="tasks"&&(p=R),l.has(T)||u.push(h),f=w+1}let m=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(f).join(`
|
|
45
45
|
`).replace(/^\n+/,""),k=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${m}`,...u,"",g].join(`
|
|
46
46
|
`);return{content:k.endsWith(`
|
|
47
47
|
`)?k:k+`
|
|
48
|
-
`,supersedes:d}}function
|
|
48
|
+
`,supersedes:d}}function db(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
|
|
49
49
|
|
|
50
|
-
- **Status:** superseded by ADR-${r}`):n}function
|
|
50
|
+
- **Status:** superseded by ADR-${r}`):n}function pb(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(`
|
|
51
51
|
`)+`
|
|
52
|
-
`}async function
|
|
52
|
+
`}async function mp(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await sb(t).pull(void 0,void 0,["--rebase"])}catch{}let i=k=>o==="staging"?`adr/DRAFT-${k}.md`:`tasks/${e}/adr/DRAFT-${k}.md`,s=[],a=[];for(let k of r){let w=we(t,i(k));if(!ua(w)){a.push(k);continue}s.push({slug:k,content:pp(w,"utf-8")})}let c=fp(t,"adr"),l=new Map;if(ua(c))for(let k of ib(c)){let w=ab.exec(k);!w||k===cb||l.set(k,{num:parseInt(w[1]??"",10),slug:w[2]??"",content:pp(fp(c,k),"utf-8")})}let u=Math.max(0,...[...l.values()].map(k=>k.num))+1,p=new Map,d=[],f=[];for(let k of s){if([...l.entries()].find(([,x])=>x.slug===k.slug&&x.content.includes(e))){f.push(k.slug);continue}let h=u++,v=`${String(h).padStart(4,"0")}-${k.slug}.md`,{content:T,supersedes:R}=ub(k.content,h,k.slug,e,n);if(p.set(v,T),l.set(v,{num:h,slug:k.slug,content:T}),d.push(`adr/${v}`),R!==null){let x=[...l.keys()].find($=>$.startsWith(`${String(R).padStart(4,"0")}-`));if(x&&x!==v){let $=db(p.get(x)??l.get(x).content,h);p.set(x,$),l.set(x,{...l.get(x),content:$})}}}let m=[];if(o==="staging")for(let k of s)ua(we(t,`adr/DRAFT-${k.slug}.md`))&&m.push({path:`adr/DRAFT-${k.slug}.md`,content:"",deleted:!0});if(d.length===0&&m.length===0)return{promoted:d,skipped:f,missing:a};if(d.length>0){let k=[...l.entries()].map(([w,h])=>({num:h.num,file:w,header:lb(h.content)}));p.set("INDEX.md",pb(k))}for(let[k,w]of p.entries())m.push({path:`adr/${k}`,content:w});let g=d.length>0?`adr(${e}): promote ${s.map(k=>k.slug).join(", ")}`:`adr(${e}): drop stale staged ${f.join(", ")}`;return await Se(t,m,g),{promoted:d,skipped:f,missing:a}}var ab,cb,gp=b(()=>{"use strict";Ze();ab=/^(\d{4})-(.+)\.md$/,cb="0000-template.md"});import{existsSync as hp,readFileSync as mb}from"node:fs";import{join as yp}from"node:path";function gb(t){for(let e of[it,En]){let r=yp(t,e);if(hp(r))try{return Zc(mb(r,"utf-8"))}catch{return 0}}return 0}function hb(t,e,r,n=4){let o=e<n,i=o?el(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function ai(t,e){return hb(e,gb(t),r=>hp(yp(t,r)))}var da=b(()=>{"use strict";K()});import{existsSync as Ut,readFileSync as Gr,readdirSync as wp}from"node:fs";import{join as pa}from"node:path";import{simpleGit as bp}from"simple-git";import{parse as $p}from"yaml";function vp(t){try{let e=we(t,Ao);if(!Ut(e))return null;let r=$p(Gr(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Pr.test(n)?null:{prefix:n}}catch{return null}}function xp(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
53
53
|
# The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
|
|
54
54
|
# later would orphan existing tasks/<KEY>/ directories.
|
|
55
55
|
prefix: ${t}
|
|
@@ -57,15 +57,15 @@ prefix: ${t}
|
|
|
57
57
|
# Statuses are the built-in default set for now:
|
|
58
58
|
# Backlog | To Do | In Progress | Review | Done | Rejected
|
|
59
59
|
# A configurable status set / pipeline mapping is a planned extension.
|
|
60
|
-
`}function
|
|
61
|
-
`}function
|
|
60
|
+
`}function fa(t=0){return`${t}
|
|
61
|
+
`}function yb(t){return t==="depends_on"||t==="subtask"}function kb(t){let e;try{e=$p(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=zl.includes(r.type)?r.type:Co,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;yb(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 ma(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(`
|
|
62
62
|
`)+`
|
|
63
|
-
`}function
|
|
63
|
+
`}function Hn(t,e){let r=we(t,_n(e));return Ut(r)?kb(Gr(r,"utf-8")):null}function Sp(t){let e=pa(t,"tasks");if(!Ut(e))return[];let r=[];for(let n of wp(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Hn(t,n.name);o&&r.push(o)}return r}function wb(t,e){let r=we(t,`tasks/${e}/task.md`);if(!Ut(r))return;let n=Gr(r,"utf-8").split(`
|
|
64
64
|
`),o=n.indexOf("---");if(o<0)return;let i=n.slice(o+1),s=i.lastIndexOf("## Attachments");s>=0&&i.slice(s+1).every(u=>u.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(u.trim()))&&(i=i.slice(0,s));let a=i.join(`
|
|
65
|
-
`).trim();if(!(!a||a==="_(no description)_"))return a}function
|
|
65
|
+
`).trim();if(!(!a||a==="_(no description)_"))return a}function Wn(t,e,r={}){let n=r.withDescription?wb(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:bb(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function bb(t){return t.charAt(0).toUpperCase()+t.slice(1)}function $b(t){let e=we(t,Pn);if(!Ut(e))return 0;let r=Number.parseInt(Gr(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function vb(t,e){let r=pa(t,"tasks");if(!Ut(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of wp(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 xb(t,e){return Math.max($b(t),vb(t,e))+1}async function Tp(t,e,r,n){return ca(t,()=>Sb(t,e,r,n))}async function Sb(t,e,r,n){if(!Ut(pa(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Gn(t);let o=null;for(let i=0;i<kp;i++){let s=xb(t,e),a=`${e}-${s}`,c=[...r(a),{path:Pn,content:fa(s)}];try{return await la(t,c,n(a)),a}catch(l){if(o=l,await Rb(t,n(a)),await Gn(t),Tb(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${kp} attempts: ${o instanceof Error?o.message:String(o)}`)}function Tb(t,e){for(let r of e){let n=we(t,r.path);if(!Ut(n)||(r.encoding==="base64"?Gr(n).toString("base64"):Gr(n,"utf-8"))!==r.content)return!1}return!0}async function Gn(t){let e=bp(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 Rb(t,e){let r=bp(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
|
|
66
66
|
`)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
|
|
67
67
|
`).some(i=>i.trim()===e.split(`
|
|
68
|
-
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var
|
|
68
|
+
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var kp,ci=b(()=>{"use strict";K();Ze();kp=5});function Hr(t,e,r,n){return[{path:"README.md",content:Mb(t,e)},{path:".gitignore",content:_b()},{path:"CLAUDE.md",content:Nb(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:jb()},{path:"knowledge/README.md",content:Ob()},{path:"knowledge/build.yaml",content:Lb()},{path:"actions/README.md",content:Db()},{path:"model/README.md",content:Eb()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Pb()},{path:"adr/README.md",content:Ib()},{path:"adr/0000-template.md",content:Cb()},{path:"adr/INDEX.md",content:Ab()},{path:it,content:vo()},...t.trackerProvider==="internal"?[{path:Ao,content:xp(t.youtrackProjectKey??Ts)},{path:Pn,content:fa()}]:[]]}function Eb(){return`# model/ \u2014 the project map
|
|
69
69
|
|
|
70
70
|
A graph of the project built from **git history and task artifacts**: files
|
|
71
71
|
and directories connected by the fact of changing together and the fact of
|
|
@@ -92,7 +92,7 @@ asset \u2014 treat it like \`knowledge/\`.
|
|
|
92
92
|
|
|
93
93
|
Every YAML file carries \`modelFormatVersion\`; a reader that meets a
|
|
94
94
|
different version treats it as "rebuild needed", not as an error.
|
|
95
|
-
`}function
|
|
95
|
+
`}function Ib(){return`# ADR \u2014 architecture decision records
|
|
96
96
|
|
|
97
97
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
98
98
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -120,7 +120,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
120
120
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
121
121
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
122
122
|
open a PR to this repository.
|
|
123
|
-
`}function
|
|
123
|
+
`}function Cb(){return`# ADR-NNNN: <title>
|
|
124
124
|
|
|
125
125
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
126
126
|
- **Date:** YYYY-MM-DD
|
|
@@ -142,12 +142,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
142
142
|
## Alternatives considered
|
|
143
143
|
|
|
144
144
|
- **<alternative>** \u2014 why it was rejected.
|
|
145
|
-
`}function
|
|
145
|
+
`}function Ab(){return`# ADR index
|
|
146
146
|
|
|
147
147
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
148
148
|
|
|
149
149
|
(no accepted ADRs yet)
|
|
150
|
-
`}function
|
|
150
|
+
`}function Pb(){return`# Audit
|
|
151
151
|
|
|
152
152
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
153
153
|
project appends only to its own file \u2014
|
|
@@ -156,14 +156,14 @@ project appends only to its own file \u2014
|
|
|
156
156
|
|
|
157
157
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
158
158
|
shared aggregate here.
|
|
159
|
-
`}function
|
|
159
|
+
`}function pt(t,e,r,n,o="auto",i=at,s){let a=t.trackerProvider==="internal";return{projectYaml:a?Ub(t,o):Bb(t,r,n,o),regimenYaml:Fb(t.automationLevel,a?!0:e,a,i,s)}}function _b(){return`# codepipe project config is local to each member's workspace
|
|
160
160
|
project.yaml
|
|
161
161
|
regimen.yaml
|
|
162
162
|
|
|
163
163
|
# codepipe runtime
|
|
164
164
|
session.log
|
|
165
165
|
apply-queue.json
|
|
166
|
-
`}function
|
|
166
|
+
`}function jb(){return`# Index prompt
|
|
167
167
|
|
|
168
168
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
169
169
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -220,7 +220,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
220
220
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
221
221
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
222
222
|
empty or unavailable, say so briefly rather than inventing content.
|
|
223
|
-
`}function
|
|
223
|
+
`}function Nb(t){return`# Project context for the CodePipe agent
|
|
224
224
|
|
|
225
225
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
226
226
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -248,7 +248,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
248
248
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
249
249
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
250
250
|
only after the analysis is approved.
|
|
251
|
-
`}function
|
|
251
|
+
`}function Ob(){return`# Knowledge
|
|
252
252
|
|
|
253
253
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
254
254
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -265,7 +265,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
265
265
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
266
266
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
267
267
|
any merge conflict in it as noise (either side converges on the next run).
|
|
268
|
-
`}function
|
|
268
|
+
`}function Db(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
|
|
269
269
|
|
|
270
270
|
One \`<id>.yml\` per action. Every file here appears as a button on the
|
|
271
271
|
project's **RUN** tab; an action with \`params\` opens a small wizard first.
|
|
@@ -304,7 +304,7 @@ steps:
|
|
|
304
304
|
Parameter values are passed to the commands **only as env vars** \u2014 reference
|
|
305
305
|
them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
|
|
306
306
|
command text itself.
|
|
307
|
-
`}function
|
|
307
|
+
`}function Lb(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
308
308
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
309
309
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
310
310
|
#
|
|
@@ -320,7 +320,7 @@ command text itself.
|
|
|
320
320
|
# - name: test
|
|
321
321
|
# run: npm test
|
|
322
322
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
323
|
-
`}function
|
|
323
|
+
`}function Mb(t,e){return`# ${e.name}
|
|
324
324
|
|
|
325
325
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
326
326
|
|
|
@@ -346,7 +346,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
346
346
|
pipeline \u2014 don't edit them by hand.
|
|
347
347
|
|
|
348
348
|
Automation level: **${t.automationLevel}**.
|
|
349
|
-
`}function
|
|
349
|
+
`}function Ub(t,e="auto"){return`# Project description for CodePipe.
|
|
350
350
|
id: ${t.projectId}
|
|
351
351
|
name: ${t.name}
|
|
352
352
|
|
|
@@ -369,15 +369,15 @@ branch:
|
|
|
369
369
|
pattern: codepipe/<TASK_ID>
|
|
370
370
|
|
|
371
371
|
repos:
|
|
372
|
-
${
|
|
373
|
-
`}function
|
|
372
|
+
${Rp(t)}
|
|
373
|
+
`}function Rp(t){return t.repos.length===0?` [] # add repos here
|
|
374
374
|
`:t.repos.map(e=>` - name: ${e.name}
|
|
375
375
|
host: ${e.host}
|
|
376
376
|
owner: ${e.owner}
|
|
377
377
|
repo: ${e.repoName}
|
|
378
378
|
mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
|
|
379
379
|
default_branch: ${e.defaultBranch}`:"")).join(`
|
|
380
|
-
`)}function
|
|
380
|
+
`)}function Bb(t,e,r,n="auto"){let o=e?`
|
|
381
381
|
tracker_url: ${e}`:`
|
|
382
382
|
# tracker_url: https://your.youtrack.cloud`,i=r?`require_assignee: true
|
|
383
383
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -425,7 +425,7 @@ ${mp(t)}
|
|
|
425
425
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
426
426
|
${i}`:` # project_key: \u2026
|
|
427
427
|
# tracker_url: https://your.youtrack.cloud
|
|
428
|
-
poll_interval_sec: 60`,a=
|
|
428
|
+
poll_interval_sec: 60`,a=Rp(t);return`# Project description for CodePipe.
|
|
429
429
|
id: ${t.projectId}
|
|
430
430
|
name: ${t.name}
|
|
431
431
|
|
|
@@ -456,7 +456,7 @@ branch:
|
|
|
456
456
|
|
|
457
457
|
repos:
|
|
458
458
|
${a}
|
|
459
|
-
`}function
|
|
459
|
+
`}function Fb(t,e,r=!1,n=at,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
|
|
460
460
|
# model in the recommended per-role split, so CodePipe set a single default
|
|
461
461
|
# your subscription can serve for all roles. Tune per role later from the
|
|
462
462
|
# dashboard (Project Settings \u2192 llm.models) or by editing this file.
|
|
@@ -607,11 +607,11 @@ ${a}
|
|
|
607
607
|
# # While this key stays commented out, the project keeps its current mode \u2014
|
|
608
608
|
# # only new projects start on cluster-pr. Uncomment and set a value to switch.
|
|
609
609
|
# mode: cluster-pr
|
|
610
|
-
`}var
|
|
611
|
-
`)}async function kp(t,e,r,n){let o=ia(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=ri(t,e);if(!i.outdated)return i;let s=Ab(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 _b(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=Ve(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.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:Pb(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 _b(t,e,r,n,o,i,s){let a=ia(t),c=Cb(oi(Eb(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(Kr(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===rt)continue;let k=p.get(g);if(k==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let w=oi(c,g);gp(w)||(Rb(Ib(w),{recursive:!0}),yp(w,k),d++)}yp(oi(c,rt),ho(n.currentVersion)),d++;let f=oi(c,vn);gp(f)&&(hp(f,{force:!0}),d++);let m=ia(c);await m.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await m.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await m.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),hp(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var wp=b(()=>{"use strict";F();At();ta();pr()});import{existsSync as jb,readFileSync as Nb,writeFileSync as Ob}from"node:fs";import{homedir as Db}from"node:os";import{join as bp}from"node:path";import{parseDocument as Lb}from"yaml";function Mb(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 Ub(t,e){let r=Lb(t);return r.set("repos",e.map(Mb)),r.toString()}function Bb(t,e){let r=[bp(Db(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(bp(e,"project.yaml")),r}function Fn(t,e,r){let n=[],o=[];for(let i of Bb(t,r))if(jb(i))try{let s=Nb(i,"utf-8"),a=Ub(s,e);a!==s&&(Ob(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}var sa=b(()=>{"use strict"});import{createCipheriv as Fb,createDecipheriv as Kb,createHash as Gb,createPrivateKey as Hb,createPublicKey as aa,diffieHellman as $p,generateKeyPairSync as vp,hkdfSync as xp,randomBytes as Wb}from"node:crypto";function ii(){let{publicKey:t,privateKey:e}=vp("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Ee(t){let e=Buffer.from(t,"base64");return(Gb("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function wt(t,e){let r=aa({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=vp("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=$p({privateKey:o,publicKey:r}),c=Buffer.from(xp("sha256",a,Buffer.concat([i,s]),Sp,32)),l=Wb(12),u=Fb("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),f=u.getAuthTag(),m={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:f.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(m),"utf-8").toString("base64")}function Gr(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=Hb({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=aa({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=aa(n).export({type:"spki",format:"der"}),a=$p({privateKey:n,publicKey:o}),c=Buffer.from(xp("sha256",a,Buffer.concat([i,s]),Sp,32)),l=Kb("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 Sp,Be=b(()=>{"use strict";Sp=Buffer.from("devpipe-sealedbox-v1","utf-8")});function Yb(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 Tp(t,e,r,n){let o=Yb(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=_o(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=wt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}var Rp=b(()=>{"use strict";Be();ie()});function Kn(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 Gn(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 Hn(t,e=process.env){if(!t)return!1;let r=`https://${Zt}:${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 ca(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 Cp(t,e=process.env){return ca(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Kn(t,e),e)}function Ep(t,e=process.env){return ca(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Gn(t,e),e)}function Ip(t,e=process.env){return ca(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Zt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Hn(t,e),e)}var si=b(()=>{"use strict";F()});function Ap(t){let e=H(t);if(!e)return null;if(!e.sealKey){let r=ii();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},X(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Ee(e.sealKey.publicKey)}}async function Pp(t,e,r,n){let o;try{o=JSON.parse(Gr(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=H(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 Ct(o.token);return i.github={token:o.token},Hr(i,()=>{process.env.GH_TOKEN=o.token,Cp(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await It(o.token);return i.gitlab={token:o.token},Hr(i,()=>{process.env.GITLAB_TOKEN=o.token,Ep(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 Et(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Hr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Ip(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},Hr(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 jt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Hr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Hr(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 Hr(t,e){X(t),e()}var _p=b(()=>{"use strict";Be();ie();At();rr();Dr();si()});import{spawn as qb}from"node:child_process";function zb(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Tt(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 Op(t){let{def:e,onEvent:r}=t,n=zb(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
612
|
-
`,o.length>
|
|
613
|
-
`))!==-1;)o(f,m.slice(0,k).replace(/\r$/,"")),m=m.slice(k+1)},flush:()=>{m.length>0&&o(f,m.replace(/\r$/,"")),m=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",f=>{clearTimeout(l),o("stderr",`spawn failed: ${f.message}`),i(127)}),s.on("close",(f,m)=>{clearTimeout(l),p.flush(),d.flush(),i(a?
|
|
614
|
-
`)){let a=/^(\w+):\s*(.+)$/.exec(s.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let i=r[2].trim();return!n||!o||!i||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:i,source:t}}function
|
|
610
|
+
`}var hr=b(()=>{"use strict";K();ci()});import{existsSync as Ep,mkdirSync as Kb,mkdtempSync as Gb,rmSync as Ip,writeFileSync as Cp}from"node:fs";import{tmpdir as Hb}from"node:os";import{dirname as Wb,join as li}from"node:path";import{simpleGit as ga}from"simple-git";function Yb(t){return`codepipe/context-migration-v${t}`}function qb(t){let e=tl(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 \`${it}\` stamp (renamed from \`${En}\``,"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(`
|
|
611
|
+
`)}async function Ap(t,e,r,n){let o=ga(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=ai(t,e);if(!i.outdated)return i;let s=Yb(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 Vb(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=Xe(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.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:qb(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 Vb(t,e,r,n,o,i,s){let a=ga(t),c=Gb(li(Hb(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},p=new Map(Hr(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===it)continue;let k=p.get(g);if(k==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let w=li(c,g);Ep(w)||(Kb(Wb(w),{recursive:!0}),Cp(w,k),d++)}Cp(li(c,it),vo(n.currentVersion)),d++;let f=li(c,En);Ep(f)&&(Ip(f,{force:!0}),d++);let m=ga(c);await m.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await m.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await m.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Ip(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var Pp=b(()=>{"use strict";K();jt();da();hr()});import{existsSync as zb,readFileSync as Xb,writeFileSync as Jb}from"node:fs";import{homedir as Qb}from"node:os";import{join as _p}from"node:path";import{parseDocument as Zb}from"yaml";function e$(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 t$(t,e){let r=Zb(t);return r.set("repos",e.map(e$)),r.toString()}function r$(t,e){let r=[_p(Qb(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(_p(e,"project.yaml")),r}function Yn(t,e,r){let n=[],o=[];for(let i of r$(t,r))if(zb(i))try{let s=Xb(i,"utf-8"),a=t$(s,e);a!==s&&(Jb(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}var ha=b(()=>{"use strict"});import{createCipheriv as n$,createDecipheriv as o$,createHash as i$,createPrivateKey as s$,createPublicKey as ya,diffieHellman as jp,generateKeyPairSync as Np,hkdfSync as Op,randomBytes as a$}from"node:crypto";function ui(){let{publicKey:t,privateKey:e}=Np("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Pe(t){let e=Buffer.from(t,"base64");return(i$("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function $t(t,e){let r=ya({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Np("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=jp({privateKey:o,publicKey:r}),c=Buffer.from(Op("sha256",a,Buffer.concat([i,s]),Dp,32)),l=a$(12),u=n$("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),f=u.getAuthTag(),m={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:f.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(m),"utf-8").toString("base64")}function Wr(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=s$({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=ya({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=ya(n).export({type:"spki",format:"der"}),a=jp({privateKey:n,publicKey:o}),c=Buffer.from(Op("sha256",a,Buffer.concat([i,s]),Dp,32)),l=o$("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 Dp,Ke=b(()=>{"use strict";Dp=Buffer.from("devpipe-sealedbox-v1","utf-8")});function c$(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 Lp(t,e,r,n){let o=c$(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=Lo(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=$t(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}var Mp=b(()=>{"use strict";Ke();ue()});function qn(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 Vn(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 zn(t,e=process.env){if(!t)return!1;let r=`https://${nr}:${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 ka(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 Up(t,e=process.env){return ka(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>qn(t,e),e)}function Bp(t,e=process.env){return ka(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Vn(t,e),e)}function Fp(t,e=process.env){return ka(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${nr}:${encodeURIComponent(t)}@bitbucket.org/`,()=>zn(t,e),e)}var di=b(()=>{"use strict";K()});function Kp(t){let e=Y(t);if(!e)return null;if(!e.sealKey){let r=ui();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ee(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Pe(e.sealKey.publicKey)}}async function Gp(t,e,r,n){let o;try{o=JSON.parse(Wr(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=Y(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 At(o.token);return i.github={token:o.token},Yr(i,()=>{process.env.GH_TOKEN=o.token,Up(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await _t(o.token);return i.gitlab={token:o.token},Yr(i,()=>{process.env.GITLAB_TOKEN=o.token,Bp(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 Pt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Yr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Fp(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 Ot({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Yr(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 Dt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Yr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Yr(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 Yr(t,e){ee(t),e()}var Hp=b(()=>{"use strict";Ke();ue();jt();sr();Mr();di()});import{spawn as l$}from"node:child_process";function d$(t,e,r,n,o,i){let s={...t},a=(c,l)=>{It(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 qp(t){let{def:e,onEvent:r}=t,n=d$(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
612
|
+
`,o.length>Wp&&(o=o.slice(o.length-Wp))},s=(a,c)=>{let l=c.length>Yp?c.slice(0,Yp)+"\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 u=await p$(c.run,c.timeout_sec,t.cwd,n,s);if(u!==0)return i(`[${l}] exited with code ${u}`),r({ts:Date.now(),kind:"result",status:"failed",exitCode:u,failedStep:l}),{status:"failed",exitCode:u,failedStep:l,logTail:o}}return r({ts:Date.now(),kind:"result",status:"succeeded",exitCode:0}),{status:"succeeded",exitCode:0,logTail:o}}function p$(t,e,r,n,o){return new Promise(i=>{let s=l$("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Rl)*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 u=f=>{let m="";return{data:g=>{m+=g.toString("utf-8");let k;for(;(k=m.indexOf(`
|
|
613
|
+
`))!==-1;)o(f,m.slice(0,k).replace(/\r$/,"")),m=m.slice(k+1)},flush:()=>{m.length>0&&o(f,m.replace(/\r$/,"")),m=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",f=>{clearTimeout(l),o("stderr",`spawn failed: ${f.message}`),i(127)}),s.on("close",(f,m)=>{clearTimeout(l),p.flush(),d.flush(),i(a?u$:f??(m?1:0))})})}var u$,Wp,Yp,Vp=b(()=>{"use strict";K();u$=124,Wp=16*1024,Yp=4e3});import{existsSync as f$,readFileSync as m$,statSync as zp}from"node:fs";function g$(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Jp(t,e){let r=we(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!f$(r)||!zp(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=zp(r);if(n>Xp)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Xp})`);let o=m$(r);return g$(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}var Xp,Qp=b(()=>{"use strict";Ze();Xp=2*1024*1024});import{existsSync as h$,readFileSync as y$,writeFileSync as k$}from"node:fs";import{join as w$}from"node:path";import{parseDocument as b$}from"yaml";async function Zp(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=jl(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=w$(t,o);if(!h$(s))throw new Error(`${o} not found in context repo (${t})`);let a=b$(y$(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);k$(s,a.toString()),n.push(o)}return{files:n}}var ef=b(()=>{"use strict";K()});import{existsSync as $$,readFileSync as v$,writeFileSync as x$}from"node:fs";import{join as S$}from"node:path";import{isMap as tf,parseDocument as T$}from"yaml";async function rf(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||!Bl(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=S$(t,"project.yaml");if(!$$(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=T$(v$(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>tf(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!tf(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),x$(o,i.toString()),{repoName:r,defaultBranch:n}}var nf=b(()=>{"use strict";K()});import{existsSync as wa,readFileSync as ba,writeFileSync as R$}from"node:fs";import{join as pi}from"node:path";import{parseDocument as $a}from"yaml";async function of(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=pi(t,"project.yaml");if(!wa(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=$a(ba(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=pi(t,"regimen.yaml");if(!wa(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=$a(ba(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)R$(pi(t,i.path),i.content);return{files:r.map(i=>i.path)}}function fi(t){if(!t)return"Stage";try{let e=pi(t,"project.yaml");if(!wa(e))return"Stage";let n=$a(ba(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var va=b(()=>{"use strict"});import{existsSync as sf,readFileSync as af,readdirSync as E$}from"node:fs";import{join as xa}from"node:path";import{simpleGit as I$}from"simple-git";function C$(t,e){let r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(e);if(!r)return null;let n="",o="";for(let s of r[1].split(`
|
|
614
|
+
`)){let a=/^(\w+):\s*(.+)$/.exec(s.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let i=r[2].trim();return!n||!o||!i||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:i,source:t}}function A$(t,e){let r=xa(t,`tasks/${e}/annotations`);if(!sf(r))return[];let n=[];for(let o of E$(r).sort())if(o.endsWith(".md")){try{let i=C$(o,af(xa(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=cl)break}return n}async function cf(t){let{contextDir:e,taskKey:r,repoName:n,repoDir:o,commitSha:i,date:s,touchedKeys:a,identity:c}=t;if(!c)return[];let l=new Map(c.entities.filter(d=>d.status==="active").map(d=>[d.currentKey,d.entityId])),u=I$(o),p=[];for(let d of A$(e,r)){if(d.repo!==n)continue;let f=pe("code",n,d.path);if(!a.has(f))continue;let m=l.get(f);if(!m)continue;let g=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,P$),k=nl(m),w=xa(e,k),h=p.find(C=>C.path===k),v=h?.content??(sf(w)?af(w,"utf-8"):null),T=`<!-- ${r}${g?`:${g}`:""} -->`;if(v?.includes(T))continue;let R=v??`---
|
|
615
615
|
entityId: ${m}
|
|
616
616
|
---
|
|
617
617
|
|
|
@@ -619,32 +619,35 @@ entityId: ${m}
|
|
|
619
619
|
|
|
620
620
|
Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
|
|
621
621
|
`,x=["",`## ${s} \u2014 ${r}`,T,"",d.body,""].join(`
|
|
622
|
-
`),$=R+x;h?h.content=$:p.push({path:k,content:$})}return p}var
|
|
623
|
-
`))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),f=l.slice(2),m=
|
|
624
|
-
`)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:
|
|
625
|
-
`))if(a.startsWith("@@@ ")){let[c,l]=a.slice(4).trim().split(/\s+/);s={sha:c??"",timeSec:Number(l??0),files:[]},i.push(s)}else a.trim()&&s&&s.files.push(a.trim());return i}function
|
|
626
|
-
`).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${s}^`,s]).catch(()=>"")).split("\0");for(let l=0;l+2<c.length;){if(!(c[l]??"").startsWith("R")){l+=1;continue}let p=c[l+1]??"",d=c[l+2]??"";p&&d&&i.push({fromPath:p,toPath:d,commit:s}),l+=3}}return i}function pf(t){let e=new Map,r=new Map;for(let n of t){let o=r.get(n.fromPath)??n.fromPath;r.delete(n.fromPath),r.set(n.toPath,o),e.set(o,{finalPath:n.toPath,commit:n.commit})}for(let[n,o]of e)o.finalPath===n&&e.delete(n);return e}var ff=b(()=>{"use strict"});function pi(t){return le("container",t,T$)}function mf(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function gf(t,e,r,n){let o=[],i=u=>{let p=le("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:mf(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,R$)}},s=(u,p)=>{let d=le("component",t,u),f=n.get(d);return{key:d,level:"component",label:mf(u),...f?{entityId:f}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let f=r.filesByDir.get(d)??[],m=r.childDirs.get(d)??[],g=[p,...f.map(i)],k=[...f.map(w=>({kind:"contains",from:p.key,to:le("code",t,w.path)})),...m.map(w=>({kind:"contains",from:p.key,to:le("component",t,w)}))];c(u,g,k)},c=(u,p,d)=>{let f={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},m=$o(f);if(!m.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${m.errors.join("; ")}`);o.push({path:Vc(t,u),content:rl(f)})},l={key:pi(t),level:"container",label:t,...n.get(pi(t))?{entityId:n.get(pi(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[s(u,!0)],[]):a(u,s(u,!1),u);return o.sort((u,p)=>u.path<p.path?-1:u.path>p.path?1:0),{files:o,counts:r.counts}}function hf(t,e){let r=[pi(t)];for(let n of e.components)r.push(le("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(le("code",t,o.path));return r.sort()}var T$,R$,yf=b(()=>{"use strict";F();T$=".";R$=12});import{simpleGit as wf}from"simple-git";function fr(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function $f(t,e="HEAD"){let r=wf(t),n=(await r.revparse([e])).trim(),[o,i]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(i??0),files:await ba(t,n)}}async function ba(t,e){let n=await wf(t).raw(["ls-tree","-r","-z",e]),o=[];for(let i of n.split("\0")){if(!i)continue;let s=i.indexOf(" ");if(s<0)continue;let[,a,c]=i.slice(0,s).split(/\s+/);a!=="blob"||!c||o.push({path:i.slice(s+1),blobHash:c})}return o.sort((i,s)=>i.path<s.path?-1:i.path>s.path?1:0),o}function kf(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function vf(t,e){let r=[...t].sort((m,g)=>m.path<g.path?-1:m.path>g.path?1:0),n=new Map,o=new Map;for(let m of r){let g=kf(m.path);n.has(g)||n.set(g,[]),n.get(g).push(m);let k=g;for(;k!=="";){let w=kf(k);o.has(w)||o.set(w,new Set),o.get(w).add(k),k=w}}let i=m=>[...o.get(m)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let m=l.shift(),g=(n.get(m)??[]).length+i(m).length;if(g<=s)s-=g,c.add(m),l.push(...i(m));else{if(m==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(m)}}let u=[],p=new Map,d=new Map,f=0;for(let m of[...c].sort()){let g=n.get(m)??[];p.set(m,g),d.set(m,i(m)),f+=g.length,m!==""&&u.push(m)}for(let m of a)u.push(m);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:f}}}var bf,fi=b(()=>{"use strict";bf=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as xf,readFileSync as Sf}from"node:fs";import{join as Tf}from"node:path";import{simpleGit as C$}from"simple-git";import{parse as Rf}from"yaml";function Wn(t){let e={ignore:bf,containerNodeCap:E$,cochange:{...We},issueKeyPattern:null},r=Tf(t,"regimen.yaml");if(!xf(r))return e;let n;try{n=Rf(Sf(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(f=>typeof f=="string"&&f.trim().length>0):e.ignore,c=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>0?f:m,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d}}function $a(t,e){let r=Tf(t,yo(e));if(!xf(r))return null;let n=Rf(Sf(r,"utf-8")),o=vo(n);if(!o.ok)throw new Error(`model: ${yo(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Cf(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await $f(r),s=fr(o.ignore),a=i.files.filter(h=>!s(h.path)),c=vf(a,o.containerNodeCap),l=$a(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await C$(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=pf(await df(r,l.builtFromCommit,i.commit)),p=new Map((await ba(r,l.builtFromCommit)).map(T=>[T.path,T.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(h=>[h.path,h.blobHash])));let d=new Map(a.map(h=>[h.path,h.blobHash])),f=lf({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:hf(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),m=gf(e,i.commit,c,f.byKey),g=fr([...o.ignore,...Wr]),k=cf({repo:e,headTimeSec:i.commitTimeSec,filesets:await af(r,i.commit,o.cochange.windowCommits),pathToCurrent:ui(f.table),currentPaths:new Set(a.map(h=>h.path)),ignored:g,settings:o.cochange}),w=[{path:yo(e),content:nl(f.table)},...m.files.map(h=>({path:h.path,content:h.content})),{path:qc(e),content:wo({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:k})}];return{repo:e,headCommit:i.commit,files:w,emittedShardPaths:new Set(m.files.map(h=>h.path)),counts:{...m.counts,correlates:k.length},identityTable:f.table,entityByKey:f.byKey}}var E$,va=b(()=>{"use strict";F();di();uf();ff();yf();fi();E$=1500});import{existsSync as If,readFileSync as Af,readdirSync as I$}from"node:fs";import{join as xa}from"node:path";import{parse as Pf}from"yaml";function A$(t,e){if(!t||!e)return null;let r=Date.parse(`${t}T00:00:00Z`),n=Date.parse(`${e}T00:00:00Z`);return!Number.isFinite(r)||!Number.isFinite(n)?null:Math.abs(r-n)/864e5}function _f(t,e,r){let n=new Set(t.files.map(d=>d.key)),o=new Set(e.files.map(d=>d.key)),i=0;for(let d of n)o.has(d)&&i++;if(i<Jc)return null;let s=i/Math.min(n.size,o.size),a=A$(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*Ef)/Ef;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[ke(t.taskKey),ke(e.taskKey)]:[ke(e.taskKey),ke(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function jf(t,e){let r=new Map(t.map(s=>[s.taskKey,s])),n=new Map;for(let s of t)for(let a of s.files)n.has(a.key)||n.set(a.key,[]),n.get(a.key).push(s.taskKey);let o=new Set,i=[];for(let s of n.values())if(!(s.length<2))for(let a=0;a<s.length;a++)for(let c=a+1;c<s.length;c++){let[l,u]=s[a]<s[c]?[s[a],s[c]]:[s[c],s[a]],p=`${l}\0${u}`;if(o.has(p))continue;o.add(p);let d=_f(r.get(l),r.get(u),e);d&&i.push(d)}return i.sort((s,a)=>s.from<a.from?-1:s.from>a.from?1:s.to<a.to?-1:1)}function Nf(t,e,r,n){let o=ke(r),i=t.filter(a=>a.from!==o&&a.to!==o),s=e.find(a=>a.taskKey===r);if(s){let a=new Set(s.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=_f(s,c,n);l&&i.push(l)}}return i.sort((a,c)=>a.from<c.from?-1:a.from>c.from?1:a.to<c.to?-1:1)}function mi(t){let e=xa(t,"model/facts/events");if(!If(e))return[];let r=[];for(let n of I$(e).sort())if(n.endsWith(".yaml"))try{let o=Rr(Pf(Af(xa(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Of(t){let e=xa(t,xr);if(!If(e))return[];try{let r=ko(Pf(Af(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function gi(t){return wo({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Ef,Sa=b(()=>{"use strict";F();Ef=1e4});var Lf={};mo(Lf,{attachPrToBranchTasks:()=>Ca,attachPrToEvent:()=>Df,recordPipelineEvent:()=>Ra});import{existsSync as P$,readFileSync as _$}from"node:fs";import{join as j$}from"node:path";import{simpleGit as Ta}from"simple-git";async function N$(t,e){let n=await Ta(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
|
|
627
|
-
`)){
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
`)){let s=
|
|
622
|
+
`),$=R+x;h?h.content=$:p.push({path:k,content:$})}return p}var P$,lf=b(()=>{"use strict";K();P$=12});import{existsSync as Sa,readFileSync as Ta}from"node:fs";import{join as Ra}from"node:path";import{simpleGit as df}from"simple-git";import{parse as Ea}from"yaml";function ff(t,e){if(t)try{return new RegExp(t,"g")}catch{}if(e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b${r}-\\d+\\b`,"g")}return new RegExp(_$.source,"g")}function mf(t){let e=Ra(t,"project.yaml");if(Sa(e))try{let o=Ea(Ta(e,"utf-8"))?.youtrack,i=o&&typeof o=="object"?o.project_key:null;if(typeof i=="string"&&i.trim())return i.trim()}catch{}let r=Ra(t,"tracker","config.yaml");if(Sa(r))try{let o=Ea(Ta(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function gf(t){if(t.includes("=>")){let r=t.replace(/\{([^{}]*) => ([^{}]*)\}/g,(o,i,s)=>s).replace(/\/\//g,"/");if(!r.includes("=>"))return r;let n=r.split("=>");return(n[n.length-1]??r).trim()}return t}async function j$(t,e,r){let o=await df(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
|
|
623
|
+
`))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),f=l.slice(2),m=Ia.exec(u)??pf.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:m?Number(m[1]):null,isMerge:f.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:gf(c[3]),churn:l+u})}return i}async function N$(t,e){let n=await df(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
|
|
624
|
+
`)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:gf(s[3]),churn:a+c})}return o}function O$(t){let{repo:e,issueKeyRe:r,commits:n,pathToCurrent:o,entityByKey:i,ignored:s}=t,a=new Map;for(let c of[...n].reverse()){let l=[...new Set(c.subject.match(r)??[])],u,p,d=l.slice(1);if(l.length>0)u=l[0],p=c.subject.replace(new RegExp(`^\\s*${u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[:\u2014-]\\s*`),"").replace(Ia,"").trim();else if(c.prNumber!==null)u=`PR-${c.prNumber}`,p=c.subject.replace(Ia,"").replace(pf,"").replace(/^from\s+/,"").trim()||c.subject;else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let f=new Map;for(let k of c.files){let w=o.get(k.path)??k.path;s(w)||f.set(w,(f.get(w)??0)+k.churn)}if(f.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[k,w]of f){let h=pe("code",e,k),v=g.files.find(T=>T.key===h);if(v)v.churn=(v.churn??0)+w;else{let T=i.get(h);g.files.push({key:h,...T?{entityId:T}:{},churn:w})}}if(d.length>0){let k=new Set([...g.links?.tasks??[],...d]);k.delete(u),g.links={...g.links??{},tasks:[...k].sort()}}a.set(u,g)}return a}function uf(t,e){if(!t)return e;if(t.origin==="pipeline")return null;let r=[...new Set([...t.commits,...e.commits])],n=new Map(t.files.map(i=>[i.key,i]));for(let i of e.files)n.has(i.key)||n.set(i.key,i);let o=[...new Set([...t.links?.tasks??[],...e.links?.tasks??[]])].sort();return{...t,commits:r,files:[...n.values()],...o.length>0?{links:{...t.links??{},tasks:o}}:{}}}async function hf(t){let e=await j$(t.repoDir,t.headCommit,t.windowCommits);for(let r of e){let n=(r.subject.match(t.issueKeyRe)??[]).length>0;t.issueKeyRe.lastIndex=0,r.isMerge&&r.prNumber!==null&&!n&&r.files.length===0&&(r.files=await N$(t.repoDir,r.sha))}return O$({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored})}function yf(t,e){let r=new Map;for(let i of e)for(let[s,a]of i){let c=r.get(s);r.set(s,c?uf(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=uf(mi(t,i),s);if(!a){o++;continue}n.push({path:Rr(i),content:Cn(a)})}return{files:n,skippedPipeline:o}}function mi(t,e){let r=Ra(t,Rr(e));if(!Sa(r))return null;try{let n=Et(Ea(Ta(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var _$,Ia,pf,Ca=b(()=>{"use strict";K();_$=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Ia=/\(#(\d+)\)\s*$/,pf=/^Merge pull request #(\d+)\b/});import{simpleGit as D$}from"simple-git";async function wf(t,e,r){let o=await D$(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
|
|
625
|
+
`))if(a.startsWith("@@@ ")){let[c,l]=a.slice(4).trim().split(/\s+/);s={sha:c??"",timeSec:Number(l??0),files:[]},i.push(s)}else a.trim()&&s&&s.files.push(a.trim());return i}function gi(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=Q(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=Q(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function bf(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let h=new Set;for(let x of w.files){let $=o.get(x)??x;!i.has($)||s($)||h.add($)}if(h.size<2||h.size>a.commitFileCap)continue;let v=Math.max(0,r-w.timeSec),T=Math.pow(.5,v/c),R=[...h].sort();for(let x of R)l.set(x,(l.get(x)??0)+T);for(let x=0;x<R.length;x++)for(let $=x+1;$<R.length;$++){let C=`${R[x]}\0${R[$]}`;u.set(C,(u.get(C)??0)+T),p.set(C,(p.get(C)??0)+1)}}let d=[],f=a.jaccardMinPct/100;for(let[w,h]of u){if((p.get(w)??0)<a.supportMin)continue;let[v,T]=w.split("\0"),R=(l.get(v)??0)+(l.get(T)??0)-h,x=R>0?h/R:0;x<f||d.push({a:v,b:T,weight:Math.round(x*kf)/kf})}let m=new Map;for(let w of d)for(let h of[w.a,w.b])m.has(h)||m.set(h,[]),m.get(h).push(w);let g=new Map;for(let[,w]of m)w.sort((h,v)=>v.weight-h.weight||(h.a<v.a?-1:h.a>v.a?1:h.b<v.b?-1:1)).slice(0,a.topK).forEach(h=>g.set(h,(g.get(h)??0)+1));return[...g.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:pe("code",e,w.a),to:pe("code",e,w.b),weight:w.weight})).sort((w,h)=>w.from<h.from?-1:w.from>h.from?1:w.to<h.to?-1:1)}var qr,kf,hi=b(()=>{"use strict";K();qr=["package-lock.json","pnpm-lock.yaml","yarn.lock"];kf=1e4});import{createHash as L$}from"node:crypto";function U$(t,e,r,n){for(let o=0;;o++){let s=`e_${L$("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function $f(t){let{repo:e,headCommit:r,headDate:n,prev:o,renameChains:i,prevBlobByPath:s,headBlobByPath:a}=t,c=[...t.currentKeys].sort(),l=new Set(c),u=o?.entities??[],p=new Set(u.map($=>$.entityId)),d=new Set,f=[],m=new Map,g=($,C)=>{d.add(C),m.set(C,$.entityId),f.push($)},k=[];for(let $ of u)l.has($.currentKey)&&!d.has($.currentKey)?g({...$,status:"active",lastSeen:r},$.currentKey):k.push($);let w=[],h=[];for(let $ of k){let C=Q($.currentKey),U=C?i.get(C.path):void 0;if(C&&U){let H=pe(C.level,e,U.finalPath);if(l.has(H)&&!d.has(H)){w.push({entity:$,newKey:H,untilCommit:U.commit}),d.add(H);continue}}h.push($)}let v=[];if(s){let $=new Map;for(let U of c){if(d.has(U))continue;let H=Q(U);if(H?.level!=="code")continue;let I=a.get(H.path);I&&$.set(I,$.has(I)?null:U)}let C=new Map;for(let U of h){let H=Q(U.currentKey);if(H?.level!=="code")continue;let I=s.get(H.path);I&&C.set(I,C.has(I)?null:U)}for(let U of h){let H=Q(U.currentKey),I=H?.level==="code"?s.get(H.path):void 0,y=I?$.get(I):void 0;I&&y&&C.get(I)===U&&!d.has(y)?(w.push({entity:U,newKey:y,untilCommit:r}),d.add(y)):v.push(U)}}else v.push(...h);let T=new Map;for(let $ of w){let C=Q($.entity.currentKey),U=Q($.newKey);if(C?.level!=="code"||!U)continue;let H=C.path,I=U.path;for(let y=H.lastIndexOf("/");y>0;y=H.lastIndexOf("/",y-1)){let L=H.slice(0,y),N=H.slice(y+1);if(!I.endsWith(`/${N}`))continue;let F=I.slice(0,I.length-N.length-1);if(F===L)continue;let A=`${L}\0${F}`,_=T.get(A);T.set(A,{count:(_?.count??0)+1,commit:_&&_.commit>$.untilCommit?_.commit:$.untilCommit})}}let R=[...T.entries()].filter(([,$])=>$.count>=M$).map(([$,C])=>{let[U,H]=$.split("\0");return{from:U,to:H,commit:C.commit}}).sort(($,C)=>C.from.length-$.from.length||($.from<C.from?-1:1)),x=[];for(let $ of v){let C=Q($.currentKey),U=!1;if(C?.level==="component")for(let H of R){let I=null;if(C.path===H.from?I=H.to:C.path.startsWith(`${H.from}/`)&&(I=H.to+C.path.slice(H.from.length)),I===null)continue;let y=pe("component",e,I);l.has(y)&&!d.has(y)&&(w.push({entity:$,newKey:y,untilCommit:H.commit}),d.add(y),U=!0);break}U||x.push($)}for(let $ of w.sort((C,U)=>C.newKey<U.newKey?-1:1))g({...$.entity,currentKey:$.newKey,aliases:[...$.entity.aliases??[],{key:$.entity.currentKey,until:$.untilCommit}],status:"active",lastSeen:r},$.newKey);for(let $ of x)f.push({...$,status:"orphaned"});for(let $ of c){if(d.has($))continue;let C=U$(e,$,r,p);p.add(C),g({entityId:C,currentKey:$,firstSeen:n,lastSeen:r,status:"active"},$)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:f},byKey:m}}var M$,vf=b(()=>{"use strict";K();M$=5});import{simpleGit as B$}from"simple-git";async function xf(t,e,r){let n=B$(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
|
|
626
|
+
`).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${s}^`,s]).catch(()=>"")).split("\0");for(let l=0;l+2<c.length;){if(!(c[l]??"").startsWith("R")){l+=1;continue}let p=c[l+1]??"",d=c[l+2]??"";p&&d&&i.push({fromPath:p,toPath:d,commit:s}),l+=3}}return i}function Sf(t){let e=new Map,r=new Map;for(let n of t){let o=r.get(n.fromPath)??n.fromPath;r.delete(n.fromPath),r.set(n.toPath,o),e.set(o,{finalPath:n.toPath,commit:n.commit})}for(let[n,o]of e)o.finalPath===n&&e.delete(n);return e}var Tf=b(()=>{"use strict"});function yi(t){return pe("container",t,F$)}function Rf(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function Ef(t,e,r,n){let o=[],i=u=>{let p=pe("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:Rf(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,K$)}},s=(u,p)=>{let d=pe("component",t,u),f=n.get(d);return{key:d,level:"component",label:Rf(u),...f?{entityId:f}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let f=r.filesByDir.get(d)??[],m=r.childDirs.get(d)??[],g=[p,...f.map(i)],k=[...f.map(w=>({kind:"contains",from:p.key,to:pe("code",t,w.path)})),...m.map(w=>({kind:"contains",from:p.key,to:pe("component",t,w)}))];c(u,g,k)},c=(u,p,d)=>{let f={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},m=Ir(f);if(!m.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${m.errors.join("; ")}`);o.push({path:il(t,u),content:ml(f)})},l={key:yi(t),level:"container",label:t,...n.get(yi(t))?{entityId:n.get(yi(t))}:{}};a("",l,"");for(let u of r.components)r.collapsed.has(u)?c(u,[s(u,!0)],[]):a(u,s(u,!1),u);return o.sort((u,p)=>u.path<p.path?-1:u.path>p.path?1:0),{files:o,counts:r.counts}}function If(t,e){let r=[yi(t)];for(let n of e.components)r.push(pe("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(pe("code",t,o.path));return r.sort()}var F$,K$,Cf=b(()=>{"use strict";K();F$=".";K$=12});import{simpleGit as Pf}from"simple-git";function yr(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function jf(t,e="HEAD"){let r=Pf(t),n=(await r.revparse([e])).trim(),[o,i]=(await r.raw(["show","-s","--format=%cs %ct",n])).trim().split(/\s+/);return{commit:n,commitDate:o??"",commitTimeSec:Number(i??0),files:await Aa(t,n)}}async function Aa(t,e){let n=await Pf(t).raw(["ls-tree","-r","-z",e]),o=[];for(let i of n.split("\0")){if(!i)continue;let s=i.indexOf(" ");if(s<0)continue;let[,a,c]=i.slice(0,s).split(/\s+/);a!=="blob"||!c||o.push({path:i.slice(s+1),blobHash:c})}return o.sort((i,s)=>i.path<s.path?-1:i.path>s.path?1:0),o}function Af(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Nf(t,e){let r=[...t].sort((m,g)=>m.path<g.path?-1:m.path>g.path?1:0),n=new Map,o=new Map;for(let m of r){let g=Af(m.path);n.has(g)||n.set(g,[]),n.get(g).push(m);let k=g;for(;k!=="";){let w=Af(k);o.has(w)||o.set(w,new Set),o.get(w).add(k),k=w}}let i=m=>[...o.get(m)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let m=l.shift(),g=(n.get(m)??[]).length+i(m).length;if(g<=s)s-=g,c.add(m),l.push(...i(m));else{if(m==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(m)}}let u=[],p=new Map,d=new Map,f=0;for(let m of[...c].sort()){let g=n.get(m)??[];p.set(m,g),d.set(m,i(m)),f+=g.length,m!==""&&u.push(m)}for(let m of a)u.push(m);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:f}}}var _f,ki=b(()=>{"use strict";_f=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Of,readFileSync as Df}from"node:fs";import{join as Lf}from"node:path";import{simpleGit as G$}from"simple-git";import{parse as Mf}from"yaml";function Xn(t){let e={ignore:_f,containerNodeCap:H$,cochange:{...qe},issueKeyPattern:null},r=Lf(t,"regimen.yaml");if(!Of(r))return e;let n;try{n=Mf(Df(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(f=>typeof f=="string"&&f.trim().length>0):e.ignore,c=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>0?f:m,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d}}function Pa(t,e){let r=Lf(t,xo(e));if(!Of(r))return null;let n=Mf(Df(r,"utf-8")),o=Eo(n);if(!o.ok)throw new Error(`model: ${xo(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Uf(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await jf(r),s=yr(o.ignore),a=i.files.filter(h=>!s(h.path)),c=Nf(a,o.containerNodeCap),l=Pa(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await G$(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=Sf(await xf(r,l.builtFromCommit,i.commit)),p=new Map((await Aa(r,l.builtFromCommit)).map(T=>[T.path,T.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(h=>[h.path,h.blobHash])));let d=new Map(a.map(h=>[h.path,h.blobHash])),f=$f({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:If(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),m=Ef(e,i.commit,c,f.byKey),g=yr([...o.ignore,...qr]),k=bf({repo:e,headTimeSec:i.commitTimeSec,filesets:await wf(r,i.commit,o.cochange.windowCommits),pathToCurrent:gi(f.table),currentPaths:new Set(a.map(h=>h.path)),ignored:g,settings:o.cochange}),w=[{path:xo(e),content:gl(f.table)},...m.files.map(h=>({path:h.path,content:h.content})),{path:ol(e),content:To({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:k})}];return{repo:e,headCommit:i.commit,files:w,emittedShardPaths:new Set(m.files.map(h=>h.path)),counts:{...m.counts,correlates:k.length},identityTable:f.table,entityByKey:f.byKey}}var H$,_a=b(()=>{"use strict";K();hi();vf();Tf();Cf();ki();H$=1500});import{existsSync as Ff,readFileSync as Kf,readdirSync as W$}from"node:fs";import{join as ja}from"node:path";import{parse as Gf}from"yaml";function Y$(t,e){if(!t||!e)return null;let r=Date.parse(`${t}T00:00:00Z`),n=Date.parse(`${e}T00:00:00Z`);return!Number.isFinite(r)||!Number.isFinite(n)?null:Math.abs(r-n)/864e5}function Hf(t,e,r){let n=new Set(t.files.map(d=>d.key)),o=new Set(e.files.map(d=>d.key)),i=0;for(let d of n)o.has(d)&&i++;if(i<al)return null;let s=i/Math.min(n.size,o.size),a=Y$(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*Bf)/Bf;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[ve(t.taskKey),ve(e.taskKey)]:[ve(e.taskKey),ve(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Wf(t,e){let r=new Map(t.map(s=>[s.taskKey,s])),n=new Map;for(let s of t)for(let a of s.files)n.has(a.key)||n.set(a.key,[]),n.get(a.key).push(s.taskKey);let o=new Set,i=[];for(let s of n.values())if(!(s.length<2))for(let a=0;a<s.length;a++)for(let c=a+1;c<s.length;c++){let[l,u]=s[a]<s[c]?[s[a],s[c]]:[s[c],s[a]],p=`${l}\0${u}`;if(o.has(p))continue;o.add(p);let d=Hf(r.get(l),r.get(u),e);d&&i.push(d)}return i.sort((s,a)=>s.from<a.from?-1:s.from>a.from?1:s.to<a.to?-1:1)}function Yf(t,e,r,n){let o=ve(r),i=t.filter(a=>a.from!==o&&a.to!==o),s=e.find(a=>a.taskKey===r);if(s){let a=new Set(s.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=Hf(s,c,n);l&&i.push(l)}}return i.sort((a,c)=>a.from<c.from?-1:a.from>c.from?1:a.to<c.to?-1:1)}function wi(t){let e=ja(t,"model/facts/events");if(!Ff(e))return[];let r=[];for(let n of W$(e).sort())if(n.endsWith(".yaml"))try{let o=Et(Gf(Kf(ja(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function qf(t){let e=ja(t,Tr);if(!Ff(e))return[];try{let r=So(Gf(Kf(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function bi(t){return To({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Bf,Na=b(()=>{"use strict";K();Bf=1e4});var Jn={};Rn(Jn,{collectSearchRows:()=>zf,readContextIndexHub:()=>q$,rebuildSearchIndex:()=>Xf,searchIndexPath:()=>Si,searchModelIndex:()=>V$,toFtsQuery:()=>Jf});import{existsSync as zr,readFileSync as Vr,readdirSync as vi}from"node:fs";import{join as et}from"node:path";import{parse as xi}from"yaml";function Si(t){return et(t,".git","codepipe-model-index.sqlite")}function q$(t){let e=et(t,"regimen.yaml");if(!zr(e))return"off";try{let n=xi(Vr(e,"utf-8"))?.context,o=n&&typeof n=="object"?n.index:null;return(o&&typeof o=="object"?o.hub:null)==="metadata"?"metadata":"off"}catch{return"off"}}async function Vf(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function $i(t){return t.length>ys?t.slice(0,ys):t}function Oa(t){if(!zr(t))return[];let e=[];for(let r of vi(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=et(t,r.name);r.isDirectory()?e.push(...Oa(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function zf(t){let e=[];for(let i of Oa(et(t,"model/derived/structure"))){let s;try{s=xi(Vr(i,"utf-8"))}catch{continue}let a=Ir(s);if(a.ok)for(let c of a.value.nodes){let l=Q(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:$i(`${l.path} ${c.label??""}`.trim())})}}let r=et(t,"model/facts/events");if(zr(r)){for(let i of vi(r).sort())if(i.endsWith(".yaml"))try{let s=Et(xi(Vr(et(r,i),"utf-8")));if(!s.ok)continue;let a=s.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:$i(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=et(t,"model/facts/annotations");if(zr(n)){let i=new Map;for(let s of Oa(et(t,"model/facts/identity")))try{let a=xi(Vr(s,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&i.set(c.entityId,c.currentKey)}catch{}for(let s of vi(n).sort())if(s.endsWith(".md"))try{let a=Vr(et(n,s),"utf-8"),c=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(a);if(!c)continue;e.push({nodeId:i.get(c[1])??c[1],kind:"annotation",text:$i(c[2].trim())})}catch{}}let o=et(t,"adr");if(zr(o))for(let i of vi(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=Vr(et(o,i),"utf-8").split(`
|
|
627
|
+
`).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:$i(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function Xf(t){let e=zf(t),r=await Vf();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(Si(t));try{n.exec("DROP TABLE IF EXISTS model_fts"),n.exec("CREATE VIRTUAL TABLE model_fts USING fts5(node_id UNINDEXED, kind UNINDEXED, text)");let o=n.prepare("INSERT INTO model_fts (node_id, kind, text) VALUES (?, ?, ?)");for(let i of e)o.run(i.nodeId,i.kind,i.text)}finally{n.close()}return{rows:e,indexed:!0}}function Jf(t){let e=t.match(/[\p{L}\p{N}_./-]+/gu)??[];return e.length===0?null:e.map((r,n)=>`"${r.replace(/"/g,"")}"${n===e.length-1?"*":""}`).join(" ")}async function V$(t,e,r){let n=await Vf();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");zr(Si(t))||await Xf(t);let o=Jf(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),ll),s=new n.DatabaseSync(Si(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
|
|
628
|
+
bm25(model_fts) AS rank
|
|
629
|
+
FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,i).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{s.close()}}var Qn=b(()=>{"use strict";K()});var Zf={};Rn(Zf,{attachPrToBranchTasks:()=>Ma,attachPrToEvent:()=>Qf,recordPipelineEvent:()=>La});import{existsSync as z$,readFileSync as X$}from"node:fs";import{join as J$}from"node:path";import{simpleGit as Da}from"simple-git";async function Q$(t,e){let n=await Da(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
|
|
630
|
+
`)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:s[3],churn:a+c})}return o}function Z$(t,e){let r=`tasks/${e}/SOLUTION.md`,n=J$(t,r);if(!z$(n))return{};try{let o=X$(n,"utf-8"),i=[...new Set(o.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:r,...i.length>0?{adr:i}:{}}}catch{return{solution:r}}}async function La(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Xn(e),a=yr([...s.ignore,...qr]),c=await Q$(r,i),l=(await Da(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Pa(e,n),u&&(p=new Map(u.entities.filter(R=>R.status==="active").map(R=>[R.currentKey,R.entityId])))}catch{}let d=[];for(let R of c){if(a(R.path))continue;let x=pe("code",n,R.path),$=p.get(x);d.push({key:x,...$?{entityId:$}:{},churn:R.churn})}if(d.length===0)return{recorded:!1};let f=Z$(e,o),m=mi(e,o),g=m?.origin==="pipeline"?m.files.filter(R=>Q(R.key)?.repo!==n):[],k=m?.origin==="pipeline"?m.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...m?.title?{title:m.title}:{},...l?{date:l}:{},commits:[...new Set([...k,i])],files:[...g,...d],links:{...m?.origin==="pipeline"?m.links:{},...f}};w.links&&Object.keys(w.links).length===0&&delete w.links;let h=[...wi(e).filter(R=>R.taskKey!==o),w],v=Yf(qf(e),h,o,s.cochange.halfLifeDays),T=await cf({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(R=>R.key)),identity:u}).catch(()=>[]);await Se(e,[{path:Rr(o),content:Cn(w)},{path:Tr,content:bi(v)},...T],`model: task event ${o}`);{let{rebuildSearchIndex:R}=await Promise.resolve().then(()=>(Qn(),Jn));await R(e).catch(()=>{})}return{recorded:!0}}async function Ma(t){let e=new Set([t.fallbackTaskKey]);try{let r=Da(t.repoDir),n=(await r.raw(["rev-parse","--verify",`origin/${t.baseBranch}`]).catch(()=>r.raw(["rev-parse","--verify",t.baseBranch]))).trim(),o=await r.raw(["log","--format=%(trailers:key=CodePipe-Task,valueonly)",`${n}..${t.branchName}`]);for(let i of o.split(`
|
|
631
|
+
`)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await Qf(t.contextDir,r,t.prUrl)}async function Qf(t,e,r){let n=mi(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Se(t,[{path:Rr(e),content:Cn(o)}],`model: pr link for ${e}`)}var Ua=b(()=>{"use strict";K();Ze();lf();Ca();_a();hi();Na();ki()});var Zn,Ba=b(()=>{"use strict";va();sr();Zn=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return ad(this.cfg,e)}getIssue(e,r){return cd(this.cfg,e,r??fi(this.contextDir))}listComments(e,r){return ld(this.cfg,e,r)}downloadAttachment(e){return sd(this.cfg,e)}updateStatus(e,r){return Ju(this.cfg,e,r,fi(this.contextDir))}addComment(e,r,n){return Qu(this.cfg,e,r)}createIssue(e){return td(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,fi(this.contextDir))}editIssue(e,r){return Zu(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return rd(this.cfg,e,r,n)}fetchStateFields(e){return dd(this.cfg,e)}}});import{existsSync as em,readFileSync as ev,readdirSync as tv}from"node:fs";function Ti(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=iv(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:rv(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:ov(nv(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 Ri(t,e,r){if(r.length===0)return;let n=Ti(t,e,r),o=r.map(i=>i.issue.key);await Se(t,n,`sync(${o.join(", ")}): task data`)}function rv(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(`
|
|
632
|
+
`)}function nv(t,e,r){let n=new Map,o=we(t,`tasks/${e}/comments.jsonl`);if(em(o))for(let i of ev(o,"utf-8").split(`
|
|
633
|
+
`)){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=Ar(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function ov(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
631
634
|
`)+(t.length>0?`
|
|
632
|
-
`:"")}function
|
|
633
|
-
`)){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}var
|
|
635
|
+
`:"")}function iv(t,e,r){let n=[],o=we(t,`tasks/${e}/attachments`);if(em(o))for(let i of tv(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var Ei=b(()=>{"use strict";K();Ze()});import{existsSync as sv,readFileSync as av}from"node:fs";import{randomBytes as cv}from"node:crypto";function tm(t,e){let r=we(t,`tasks/${e}/comments.jsonl`);if(!sv(r))return[];let n=[];for(let o of av(r,"utf-8").split(`
|
|
636
|
+
`)){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}var eo,Fa=b(()=>{"use strict";K();Ze();Ei();ci();eo=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Gn(this.contextDir);let r=e.columns??[];return Sp(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Wn(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Hn(this.contextDir,e);return r?Wn(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return tm(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 Gn(this.contextDir),!Hn(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${cv(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Ar(r);s&&(i.parsedCommand=s);let c=[...tm(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
|
|
634
637
|
`)+`
|
|
635
|
-
`;return await be(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 fp(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:hs.statusColumns}]}async mutateRecord(e,r,n){let o=Un(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Bn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Cn(e),content:oa(i)},...hi(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await be(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:So,status:r.targetStatus,links:[],created:n,updated:n},i=Bn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Cn(e),content:oa(o)},...hi(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}}});import{existsSync as Bf,readFileSync as Ff}from"node:fs";import{join as Kf}from"node:path";import{parseDocument as Gf}from"yaml";function Pa(t){if(!t)return"youtrack";try{let e=Kf(t,"project.yaml");return Bf(e)&&Gf(Ff(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function ut(t){let e=Pa(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=up(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=W$(n);return i?{ok:!0,kind:e,provider:new qn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Lu();return r?{ok:!0,kind:e,provider:new Yn(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function W$(t){try{let e=Kf(t,"project.yaml");if(!Bf(e))return null;let r=Gf(Ff(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var wi=b(()=>{"use strict";rr();Ia();Aa();ni();Ia();Aa()});async function Yr(t,e){let n=(bi.get(t)??Promise.resolve()).catch(()=>{}).then(e);bi.set(t,n);try{return await n}finally{bi.get(t)===n&&bi.delete(t)}}async function Hf(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;or(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Yr(`${i}/${r.name}`,async()=>{let s=await sr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await Cd(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});if(t.contextDir){let u=e.taskId.split(":")[1]??"";u&&await Ra({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:u,commitSha:c}).catch(p=>{or(`[model] task event for ${u} failed: ${p instanceof Error?p.message:String(p)}`)})}return se({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 Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Yr(`${i}/${r.name}`,async()=>{let s=await sr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir);return await Ed(s,a,{branchName:e.branchName,force:e.force}),se({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Yr(`${i}/${r.name}`,async()=>{let s=await sr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await Id(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return se({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return Y("no repo spec");let i=Ve(r),s=await i.createPullRequest(r,e);if(t.contextDir){let a=e.taskId.split(":")[1]??"",c=e.taskId.split(":",2)[0]??"?";a&&await Ca({contextDir:t.contextDir,repoDir:ve(c,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:a,prUrl:s.url}).catch(l=>{or(`[model] pr link for ${a} failed: ${l instanceof Error?l.message:String(l)}`)})}return se({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return Y("no repo spec");let i=Ve(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return se({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return Y("no repo spec");let i=Ve(r);return await i.closePR(r,e.prNumber,e.comment),se({prNumber:e.prNumber,host:i.name})}case"rewrite_cluster_branch":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Yr(`${i}/${r.name}`,async()=>{let s=await sr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,dropped:l}=await Pd(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return se({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Yr(`${i}/${r.name}`,async()=>{let s=await sr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{mergedSha:c}=await _d(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return se({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Y("no repo spec");let i=t.cloneUrlOverride??On(r),a=(await jd(i)).filter(u=>Nd(u,e.issueKey)),c=Ve(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return se({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Y("no repo spec");let i=Ve(r);return await i.addPRComment(r,e.prNumber,e.body),se({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=ut({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),se({issueId:t.trackerIssueId,newStatus:e.newStatus})):Y("no tracker_issue_id provided"):Y(i.error)}case"tracker_comment":{let i=ut({contextDir:t.contextDir});if(!i.ok)return Y(i.error);if(!t.trackerIssueId)return Y("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return se({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=ut({contextDir:t.contextDir});if(!i.ok)return Y(i.error);if(!e.projectKey)return Y("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 se({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=ut({contextDir:t.contextDir});if(!i.ok)return Y(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 Y(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return se({applied:s})}case"set_project_setting":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=await Fp(t.contextDir,e.edits);return se({files:i.files})}case"tracker_edit":{let i=ut({contextDir:t.contextDir});if(!i.ok)return Y(i.error);if(!t.contextDir)return Y("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 yi(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),se({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=await Yp(t.contextDir,e);return se({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=await Hp(t.contextDir,e);return se({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),se({reported:!0})):Y("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return Y("no context repo clone on this CLI");let i=await t.refreshContextStatus();return se({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return Y("no project workspace on this CLI");if(!r)return Y("no repo spec");if(!t.onRunActivity)return Y("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Jo(t.contextDir),c=s.find(f=>f.id===e.actionId);if(!c){let f=a.find(m=>m.file===`actions/${e.actionId}.yml`);return Y(f?`action "${e.actionId}" failed to parse: ${f.error}`:`unknown action "${e.actionId}"`)}let l=hl(c,e.input);if(!l.ok)return Y(l.error);let u=Wd(t.contextDir),p=H(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),Yr(`${e.projectId}/${r.name}`,async()=>{await sr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let f=ve(e.projectId,r.name,t.baseDir),m=await Op({cwd:f,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return se({runId:e.runId,status:m.status,exitCode:m.exitCode,...m.failedStep?{failedStep:m.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=Up(t.contextDir,e.path);return se({path:e.path,...i})}case"local_apply":return Y("local_apply requires a local workspace (handled by the daemon)");default:return Y(`unsupported action type: ${e.type}`)}}catch(i){return Y(i instanceof Error?i.message:String(i))}}function se(t){return{status:"done",result:t}}function Y(t){return{status:"failed",error:t}}var bi,Wf=b(()=>{"use strict";F();Ws();Dp();Bp();ie();Kp();Wp();pa();At();Wo();Lr();Ea();wi();ki();bi=new Map});import{existsSync as Y$,mkdtempSync as q$,rmSync as V$}from"node:fs";import{tmpdir as z$}from"node:os";import{join as _a}from"node:path";import{simpleGit as Yf}from"simple-git";async function qf(t,e,r){let n=[];for(let a of e){let c=t.repos.find(u=>u.name===a.repoName);if(!c)return{ok:!1,error:`repo "${a.repoName}" not in project.yaml \u2014 run /sync`};let l=_a(t.root,c.mountAs);if(!Y$(_a(l,".git")))return{ok:!1,error:`${c.mountAs}/ not cloned \u2014 run /sync first`};n.push({payload:a,dir:l,mountAs:c.mountAs,defaultBranch:c.defaultBranch})}let o=[];for(let a of n){let c=Yf(a.dir),l=a.payload;try{await c.fetch()}catch(f){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${Vn(f)}`}}let u=`origin/${l.baseRef}`;await Z$(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(f){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${Vn(f)}`}}let d;try{d=await Nn(c,l.deliverySha,()=>ar(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(f){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${Vn(f)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let i=[],s=[];for(let a of o){let c=await ev(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await X$(a);await a.git.raw(["branch","-f",a.branch,u]),i.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),s.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await Q$(i,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${Vn(l)} (rolled back all repos)`}}}return{ok:!0,repos:s}}async function X$(t){let e=q$(_a(z$(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=Yf(e);try{await r.raw([...J$,"cherry-pick",t.deliveryCommit])}catch(n){throw await r.raw(["cherry-pick","--abort"]).catch(()=>{}),n}return(await r.revparse(["HEAD"])).trim()}finally{await t.git.raw(["worktree","remove","--force",e]).catch(()=>{}),V$(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function Q$(t,e){for(let r of t)try{r.priorSha?await r.git.raw(["branch","-f",r.branch,r.priorSha]):await r.git.raw(["branch","-D",r.branch])}catch(n){e.warn(`[local-apply] rollback of ${r.mountAs}#${r.branch} failed: ${Vn(n)} \u2014 check manually`)}}async function Z$(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function ev(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function Vn(t){return t instanceof Error?t.message.trim():String(t)}var J$,Vf=b(()=>{"use strict";Lr();J$=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as tv}from"node:os";import{existsSync as rv,mkdirSync as nv,readFileSync as ov,writeFileSync as iv}from"node:fs";import{dirname as sv,join as av}from"node:path";function ja(){return W("FARM_PINS")??av(tv(),".codepipe","farm-pins.json")}function zf(){let t=ja();if(!rv(t))return{};try{return JSON.parse(ov(t,"utf-8"))}catch{return{}}}function cv(t){let e=ja();nv(sv(e),{recursive:!0}),iv(e,JSON.stringify(t,null,2)+`
|
|
636
|
-
`,{mode:384})}function
|
|
637
|
-
`,{mode:384})}function kv(t){return tm()[t]}function Da(t,e){let r=tm();r[t]=e,yv(r)}function rm(t,e){let r=Ee(e),n=kv(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 ${Oa()}.`);return r}var nm=b(()=>{"use strict";Ce();Be()});async function om(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:im(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}async function am(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(Ee(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");rm(e.runnerId,e.runnerPublicKey);let i=H(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??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function cm(t,e,r,n=sm){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await am(t,e,n);if(!await n.api.repoHasAdmin(i,s.owner,s.repoName))return o(`the GitHub token lacks admin access on ${s.owner}/${s.repoName} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on this repository`);let a={projectId:t.projectId,runners:[{owner:s.owner,repo:s.repoName,regToken:await n.api.mintRegistrationToken(i,s.owner,s.repoName)}],labels:[Rl(e.runnerId)]},c=wt(e.runnerPublicKey,JSON.stringify(a));Da(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function lm(t,e,r,n=sm){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await am(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=wt(e.runnerPublicKey,JSON.stringify(c));Da(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var im,wv,sm,um=b(()=>{"use strict";F();Be();nm();we();ie();im=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});wv={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:im(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)=>om(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>om(t,e,r,"remove-token")},sm={api:wv,fetchProject:Q,provisionOnRunner:pd,teardownOnRunner:fd}});function bv(t){return De.test(t)?Tt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${De}`}function pm(t,e,r,n){let o=bv(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Gr(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>dm)return{ok:!1,detail:`secret value too large (max ${dm} chars)`};try{return uu(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function fm(t,e){try{return du(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)}}}var dm,mm=b(()=>{"use strict";F();Be();ie();dm=16*1024});function $v(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var xi,gm=b(()=>{"use strict";At();xi=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=Ve(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 tr){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=Ve(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=$v(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}}});function hm(t){let{description:e,...r}=t;return r}function vv(t){let{body:e,...r}=t;return r}function xv(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 Sv(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 ym(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 Si,km=b(()=>{"use strict";F();ki();wi();Si=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??(()=>ut({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}:{},T=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},x=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(x){let $=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[_,U]=await Promise.all([$.length>0?r.listIssues({projectKey:e.projectKey,columns:$,...v,...T}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...v})]),G=new Map;for(let P of[..._,...U])G.set(P.id,P);o=[...G.values()]}else{let $=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:$,...v,...T})}}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 T=await ym(r,v.id,e.sinceMs,this.log);T&&i.set(v.id,T)}let c=[];for(let v of e.offBoardIssueIds){if(s.has(v))continue;let T=await ym(r,v,e.sinceMs,this.log);if(T&&T.length>0&&i.set(v,T),e.requireAssignee||T&&T.length>0){let R=await Sv(r,v,e.stageField,this.log);if(R)c.push(R);else if(T&&T.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(v=>!a.has(v.status)),{attachmentsByIssue:u,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 d=[...l,...c].map(v=>({issue:v,comments:i.get(v.id)??[],attachments:u.get(v.id)??[]}));try{await yi(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let v of p)this.shippedAttachments.add(v)}catch(v){let T=v instanceof Error?v.message:String(v);this.abandonTick(`context task sync failed: ${T}`);return}let f=this.options.isSelfComment??(()=>!1),m=[],g=[];for(let[v,T]of i){let R=T.filter($=>!f($.id));if(R.length===0)continue;m.push({issueId:v,comments:R.map(vv)});let x=R.flatMap($=>{let _=Er($.body);return _?[{commentId:$.id,author:$.author,name:_.name,args:_.args,createdAt:$.createdAt}]:[]});x.length>0&&g.push({issueId:v,commands:x})}let k={type:"youtrack_observation",projectId:e.projectId,issues:o.map(hm),commentsBatch:m,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(hm)}:{},observedAtMs:n};this.send(k);let w=m.reduce((v,T)=>v+T.comments.length,0),h=g.reduce((v,T)=>v+T.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${h} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(m){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${m instanceof Error?m.message:String(m)}`);continue}let f=xv(u.name);l.has(f)&&(f=`${u.id}-${f}`),l.add(f),c.push({name:f,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}}});import{existsSync as bm,rmSync as Tv}from"node:fs";import{join as qr}from"node:path";import{simpleGit as Rv}from"simple-git";import"ws";function Ti(t,e={}){let r=e.log??{info:g=>console.log(g),warn:g=>console.warn(g)};r.info(`codepipe-cli v${Oe} (protocol ${tt})`);let n=g=>e.onEvent?.(g),o=e.workspace;o?.contextDir&&zd(o.contextDir,r);let i=wm("CLI_TRACKING_POLL_INTERVAL_SEC"),s=wm("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let g=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(g)&&g>0?g*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=new Set,f=m();function m(){let g=Ko(t.hubUrl,t.cliToken),k=null,w=new xi(i,I=>{g.readyState===g.OPEN&&g.send(JSON.stringify(I))},r),h=new Si(s,I=>{g.readyState===g.OPEN&&g.send(JSON.stringify(I))},r,{contextDir:o?.contextDir??null,isSelfComment:I=>d.has(I)}),v=null,T=async()=>{try{let I={trackerProvider:Pa(o?.contextDir??null)};try{let j=await Q(t.hubUrl,t.cliToken,t.projectId);I={...I,repos:j.repos,contextRepo:j.contextRepo}}catch(j){r.warn(`[readiness] could not fetch project summary for push checks: ${j instanceof Error?j.message:String(j)}`)}let E=await td(t.projectId,I);if(g.readyState!==g.OPEN)return;let C={type:"cli_readiness",projectId:t.projectId,ready:E.ready,checks:E.checks,creds:E.creds,secretNames:pu(t.projectId),checkedAt:E.checkedAt};if(g.send(JSON.stringify(C)),E.ready)r.info("[readiness] ready");else{let j=E.checks.filter(S=>!S.ok).map(S=>`${S.name}(${S.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${j.join(", ")}`)}let O=cd(E.creds,u);if(O==="open"){u=!0;let j=ld(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${j}`),nr(j)}else O==="rearm"&&(u=!1)}catch(I){r.warn(`[readiness] check failed: ${I instanceof Error?I.message:String(I)}`)}},R=()=>{T(),v=setInterval(()=>void T(),a),typeof v.unref=="function"&&v.unref()},x=()=>{v&&(clearInterval(v),v=null)},$=150,_=new Map,U=I=>{let E=_.get(I);if(!E||(E.timer&&clearTimeout(E.timer),_.delete(I),E.events.length===0||g.readyState!==g.OPEN))return;let C={type:"run_activity",projectId:t.projectId,runId:I,events:E.events};g.send(JSON.stringify(C))},G=(I,E)=>{let C=_.get(I);if(C||(C={events:[],timer:null},_.set(I,C)),C.events.push(E),E.kind==="result"){U(I);return}C.timer||(C.timer=setTimeout(()=>U(I),$),C.timer.unref?.())},P=o?.contextDir?new Xo(o.contextDir,t.projectId,I=>{g.readyState===g.OPEN&&g.send(JSON.stringify(I))},r):null,y=async()=>{let I=o?.contextDir;if(!I)throw new Error("no context repo clone on this CLI");let E;try{E=(await Q(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let C=await kp(I,t.projectId,E,r);return g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C};return g.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let I=bu(t.projectId),E=W("ORIGIN")==="farm"?"farm":"local",C=W("FARM_ID"),O=t.accountEmail??I.email,j;try{let A=Ap(t.projectId);A&&(j=A.publicKey,r.info(`[cred-channel] key fingerprint: ${A.fingerprint}`))}catch(A){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${A instanceof Error?A.message:String(A)}`)}let S={type:"register",projectId:t.projectId,platformVersion:Oe,protocolVersion:tt,accountId:I.accountId,accountLabel:I.label,origin:E,inFlightActionIds:[...p],...O?{accountEmail:O}:{},...E==="farm"&&C?{farmId:C}:{},...j?{sealPublicKey:j}:{}};g.send(JSON.stringify(S))}),g.on("message",async I=>{let E=I.toString("utf-8");if(E==="pong"||E==="ping")return;let C;try{C=JSON.parse(E)}catch{return}if(!C||typeof C!="object")return;let O=C.type;if(O==="registered"){let S=C;if(S.ok){if(r.info(`[ws] registered for project ${S.projectId}`),n({kind:"registered",projectId:S.projectId??t.projectId}),w.start(),P?.start(),R(),Ma(t,o,r),o?.contextDir)try{let A=ri(o.contextDir,t.projectId);g.readyState===g.OPEN&&g.send(JSON.stringify(A)),A.outdated&&(r.warn(`[ctx] context format outdated: v${A.templateVersion} \u2192 v${A.currentVersion}`+(A.missingPaths.length>0?` (missing: ${A.missingPaths.join(", ")})`:"")),l||(l=!0,y().catch(()=>{})))}catch(A){r.warn(`[ctx] context-format detect failed (non-fatal): ${A instanceof Error?A.message:String(A)}`)}}else r.warn(`[ws] register rejected: ${S.reason??"unknown"}`),n({kind:"register_rejected",reason:S.reason??"unknown"}),c=!0,g.close();return}if(O==="hello"){let S=C;k=go(S.protocolVersion);let A=k?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${A}`),k||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Oe}, protocol ${tt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${La}`),n({kind:"incompatible",hubVersion:typeof S.platformVersion=="string"?S.platformVersion:null,hubProtocol:typeof S.protocolVersion=="number"?S.protocolVersion:null,updateCommand:La}));return}if(O==="tracking_targets"){w.setTargets(C.targets);return}if(O==="youtrack_sync_request"){h.setRequest(C);return}if(O==="youtrack_force_sync"){h.forceSync();return}if(O==="sync_local"){await Iv(C,o,g,r);return}if(O==="provision_repo"){let S=C;r.info(`[repo] provision_repo: ${S.repo.name} (${S.repo.host}:${S.repo.owner}/${S.repo.repoName})`),await Cv(t,o,S.repo,r),await Ma(t,o,r);return}if(O==="remove_repo"){let S=C;r.info(`[repo] remove_repo: ${S.repoName}${S.purge?" (purge)":""}`),await Ma(t,o,r),S.purge&&Ev(t,o,S.repoName,r);return}if(O==="context_write"){await Av(C,o,g,r);return}if(O==="adr_promote"){await Pv(C,o,g,r);return}if(O==="cred_update"){let S=C,A=H(t.projectId),L=A?.sealKey?await Pp(t.projectId,S.kind,S.sealed,A.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},V={type:"cred_update_result",updateId:S.updateId,projectId:t.projectId,ok:L.ok,...L.detail?{detail:L.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(V)),L.ok?(r.info(`[cred] ${S.kind} replaced${L.detail?` \u2014 ${L.detail}`:""}`),T()):r.warn(`[cred] ${S.kind} replacement rejected: ${L.detail??"unknown"}`);return}if(O==="readiness_check"){r.info("[readiness] on-demand check requested"),T();return}if(O==="agent_login_start"){sd(t,g,C,r,T);return}if(O==="move_to_farm"){let S=C;r.info(`[farm-move] request to move ${t.projectId} onto farm ${S.farmName} (${S.farmId})`);let A=await Zf(t,S,o?.contextDir,r);g.readyState===g.OPEN&&g.send(JSON.stringify(A)),A.ok?r.info(`[farm-move] done \u2014 farm daemon ${A.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${A.error??"unknown error"}`);return}if(O==="gh_runner_setup"){let S=C;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let A=await cm(t,S,r);g.readyState===g.OPEN&&g.send(JSON.stringify(A)),A.ok?r.info(`[ghr] runners connected on ${S.runnerName}`):r.warn(`[ghr] setup failed: ${A.error??"see per-repo statuses"}`);return}if(O==="gh_runner_teardown"){let S=C;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let A=await lm(t,S,r);g.readyState===g.OPEN&&g.send(JSON.stringify(A)),A.ok?r.info(`[ghr] runners disconnected from ${S.runnerName}`):r.warn(`[ghr] teardown failed: ${A.error??"unknown error"}`);return}if(O==="tracker_fields_request"){let S=C,A={type:"tracker_fields_result",requestId:S.requestId,projectId:t.projectId,ok:!1},L=ut({contextDir:o?.contextDir??null});if(!L.ok)A.error=L.error;else try{A.fields=await L.provider.fetchStateFields(S.projectKey),A.ok=!0}catch(V){A.error=V instanceof Error?V.message:String(V)}g.readyState===g.OPEN&&g.send(JSON.stringify(A)),A.ok||r.warn(`[yt-fields] listing failed: ${A.error??"unknown"}`);return}if(O==="project_secret_update"||O==="project_secret_delete"){let S=C,A;if(S.type==="project_secret_update"){let V=H(t.projectId);A=V?.sealKey?pm(t.projectId,S.name,S.sealed,V.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else A=fm(t.projectId,S.name);let L={type:"project_secret_update_result",updateId:S.updateId,projectId:t.projectId,ok:A.ok,...A.detail?{detail:A.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(L)),A.ok?(r.info(`[secret] ${S.name} ${S.type==="project_secret_update"?"saved":"deleted"}`+(A.detail?` \u2014 ${A.detail}`:"")),T()):r.warn(`[secret] ${S.name} rejected: ${A.detail??"unknown"}`);return}if(O==="auto_apply_local"){let S=C;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${S.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let A=await Md({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},S.claim,r).catch(L=>({ok:!1,message:L instanceof Error?L.message:String(L)}));A.ok?r.info(`[apply] ${S.claim.taskKey}: ${A.message}`):r.warn(`[apply] ${S.claim.taskKey}: ${A.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:S.claim.taskKey,ok:A.ok,...A.ok?{branches:A.branches??[]}:{error:A.message}});return}if(O==="sandbox_keys"){let S=H(t.projectId);if(!S){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let A=_r(t.projectId),L=Tp(C,S,A,r);for(let V of L)g.readyState===g.OPEN&&g.send(JSON.stringify(V));return}if(O!=="dispatch_action")return;let j=C;if(k===!1){let S=`refused: HUB protocol incompatible with CLI v${Oe} (protocol ${tt})`;g.send(JSON.stringify({type:"action_result",actionId:j.actionId,status:"failed",error:S})),r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 REFUSED: ${S}`),r.warn(`[exec] update the CLI to clear this: ${La}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:!1,error:S});return}if(j.action.type==="local_apply"){p.add(j.actionId);try{let S;if(!o)S={status:"failed",error:"no local workspace on this CLI"};else{let L=await qf(o,j.action.repos,r);if(S=L.ok?{status:"done",result:{repos:L.repos}}:{status:"failed",error:L.error},L.ok&&o.contextDir){let V=j.action.taskId.split(":")[1]??"";for(let Re of V?L.repos:[]){let wr=o.repos.find(pt=>pt.name===Re.repoName);if(!wr)continue;let{recordPipelineEvent:br}=await Promise.resolve().then(()=>(Ea(),Lf));await br({contextDir:o.contextDir,repoDir:qr(o.root,wr.mountAs),repoName:Re.repoName,taskKey:V,commitSha:Re.commit}).catch(pt=>r.warn(`[model] task event for ${V} failed: ${pt instanceof Error?pt.message:String(pt)}`))}}}g.send(JSON.stringify({type:"action_result",actionId:j.actionId,...S}));let A=S.status!=="failed";A?r.info(`[exec] ${j.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${j.actionId} (local_apply) \u2192 FAILED: ${S.status==="failed"?S.error:"?"}`),n({kind:"action",actionId:j.actionId,actionType:"local_apply",ok:A,...S.status==="failed"?{error:S.error}:{}})}finally{p.delete(j.actionId)}return}p.add(j.actionId);try{let S=await Hf({action:j.action,repo:j.repo,trackerIssueId:j.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:P?()=>P.reportNow():void 0,refreshContextStatus:o?.contextDir?y:void 0,onRunActivity:G}).catch(V=>({status:"failed",error:V instanceof Error?V.message:String(V)}));j.action.type==="tracker_comment"&&S.status==="done"&&"result"in S&&typeof S.result?.commentId=="string"&&d.add(S.result.commentId),g.send(JSON.stringify({type:"action_result",actionId:j.actionId,...S}));let A=S.status!=="failed",L=!A&&"error"in S?S.error:void 0;A?r.info(`[exec] ${j.actionId} (${j.action.type}) \u2192 done`):r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 FAILED: ${L??"?"}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:A,...L?{error:L}:{}})}finally{p.delete(j.actionId)}}),g.on("close",(I,E)=>{let C=E?.toString("utf-8")??"";if(r.info(`[ws] closed code=${I}${C?` reason=${C}`:""}`),w.stop(),h.stop(),P?.stop(),x(),C==="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:I}),!c&&setTimeout(()=>{f=m()},2e3)}),g.on("error",I=>r.warn(`[ws] error: ${I.message}`)),g}return{stop(){c=!0,f.close()}}}async function Ma(t,e,r){try{let n=await Q(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Fn(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 Cv(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?qr(e.root,o):ve(t.projectId,r.name);if(bm(qr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await Rv().clone(On(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 Ev(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?qr(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(!bm(qr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Tv(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 Iv(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=qr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Bd(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 Av(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 be(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 Pv(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 rp(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 wm(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var La,Ua=b(()=>{"use strict";Ce();F();$u();ad();ud();Fo();Gs();Fd();qd();np();Xe();kt();ta();wp();sa();Lr();Rp();_p();Wf();Vf();em();um();we();mm();Dr();ie();gm();km();wi();La="npm i -g @code-partner/codepipe@latest"});import{execFileSync as _v}from"node:child_process";import{mkdtempSync as jv,mkdirSync as Nv,readFileSync as $m,rmSync as Ov,writeFileSync as Dv}from"node:fs";import{tmpdir as Lv}from"node:os";import{dirname as Mv,join as vm}from"node:path";function xm(t="codepipe-context"){let e=jv(vm(Lv(),"codepipe-ssh-")),r=vm(e,"id_ed25519");try{return _v("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:$m(r,"utf-8"),publicKey:$m(`${r}.pub`,"utf-8").trim()}}finally{Ov(e,{recursive:!0,force:!0})}}async function Sm(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 Tm(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 Rm(t,e){Nv(Mv(t),{recursive:!0});let r=e.endsWith(`
|
|
638
|
+
`;return await Se(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 Tp(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:Rs.statusColumns}]}async mutateRecord(e,r,n){let o=Hn(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Wn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:_n(e),content:ma(i)},...Ti(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Se(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Co,status:r.targetStatus,links:[],created:n,updated:n},i=Wn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:_n(e),content:ma(o)},...Ti(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}}});import{existsSync as rm,readFileSync as nm}from"node:fs";import{join as om}from"node:path";import{parseDocument as im}from"yaml";function Ka(t){if(!t)return"youtrack";try{let e=om(t,"project.yaml");return rm(e)&&im(nm(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function ft(t){let e=Ka(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=vp(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=lv(n);return i?{ok:!0,kind:e,provider:new eo(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=zu();return r?{ok:!0,kind:e,provider:new Zn(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function lv(t){try{let e=om(t,"project.yaml");if(!rm(e))return null;let r=im(nm(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Ii=b(()=>{"use strict";sr();Ba();Fa();ci();Ba();Fa()});async function Xr(t,e){let n=(Ci.get(t)??Promise.resolve()).catch(()=>{}).then(e);Ci.set(t,n);try{return await n}finally{Ci.get(t)===n&&Ci.delete(t)}}async function sm(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;cr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return V("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Xr(`${i}/${r.name}`,async()=>{let s=await ur(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Re(i,r.name,t.baseDir),{commit:c,pushed:l}=await Ud(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});if(t.contextDir){let u=e.taskId.split(":")[1]??"";u&&await La({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:u,commitSha:c}).catch(p=>{cr(`[model] task event for ${u} failed: ${p instanceof Error?p.message:String(p)}`)})}return ae({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 V("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Xr(`${i}/${r.name}`,async()=>{let s=await ur(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Re(i,r.name,t.baseDir);return await Bd(s,a,{branchName:e.branchName,force:e.force}),ae({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return V("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Xr(`${i}/${r.name}`,async()=>{let s=await ur(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Re(i,r.name,t.baseDir),{commit:c,pushed:l}=await Fd(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ae({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return V("no repo spec");let i=Xe(r),s=await i.createPullRequest(r,e);if(t.contextDir){let a=e.taskId.split(":")[1]??"",c=e.taskId.split(":",2)[0]??"?";a&&await Ma({contextDir:t.contextDir,repoDir:Re(c,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:a,prUrl:s.url}).catch(l=>{cr(`[model] pr link for ${a} failed: ${l instanceof Error?l.message:String(l)}`)})}return ae({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return V("no repo spec");let i=Xe(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ae({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return V("no repo spec");let i=Xe(r);return await i.closePR(r,e.prNumber,e.comment),ae({prNumber:e.prNumber,host:i.name})}case"rewrite_cluster_branch":{if(!r)return V("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Xr(`${i}/${r.name}`,async()=>{let s=await ur(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Re(i,r.name,t.baseDir),{commit:c,dropped:l}=await Gd(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ae({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return V("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Xr(`${i}/${r.name}`,async()=>{let s=await ur(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Re(i,r.name,t.baseDir),{mergedSha:c}=await Hd(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ae({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return V("no repo spec");let i=t.cloneUrlOverride??Bn(r),a=(await Wd(i)).filter(u=>Yd(u,e.issueKey)),c=Xe(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return ae({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return V("no repo spec");let i=Xe(r);return await i.addPRComment(r,e.prNumber,e.body),ae({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=ft({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ae({issueId:t.trackerIssueId,newStatus:e.newStatus})):V("no tracker_issue_id provided"):V(i.error)}case"tracker_comment":{let i=ft({contextDir:t.contextDir});if(!i.ok)return V(i.error);if(!t.trackerIssueId)return V("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ae({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=ft({contextDir:t.contextDir});if(!i.ok)return V(i.error);if(!e.projectKey)return V("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 ae({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=ft({contextDir:t.contextDir});if(!i.ok)return V(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 V(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ae({applied:s})}case"set_project_setting":{if(!t.contextDir)return V("no context repo clone on this CLI");let i=await Zp(t.contextDir,e.edits);return ae({files:i.files})}case"tracker_edit":{let i=ft({contextDir:t.contextDir});if(!i.ok)return V(i.error);if(!t.contextDir)return V("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 Ri(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ae({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return V("no context repo clone on this CLI");let i=await of(t.contextDir,e);return ae({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return V("no context repo clone on this CLI");let i=await rf(t.contextDir,e);return ae({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ae({reported:!0})):V("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return V("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ae({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return V("no project workspace on this CLI");if(!r)return V("no repo spec");if(!t.onRunActivity)return V("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=ti(t.contextDir),c=s.find(f=>f.id===e.actionId);if(!c){let f=a.find(m=>m.file===`actions/${e.actionId}.yml`);return V(f?`action "${e.actionId}" failed to parse: ${f.error}`:`unknown action "${e.actionId}"`)}let l=Il(c,e.input);if(!l.ok)return V(l.error);let u=np(t.contextDir),p=Y(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),Xr(`${e.projectId}/${r.name}`,async()=>{await ur(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let f=Re(e.projectId,r.name,t.baseDir),m=await qp({cwd:f,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return ae({runId:e.runId,status:m.status,exitCode:m.exitCode,...m.failedStep?{failedStep:m.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return V("no context repo clone on this CLI");let i=Jp(t.contextDir,e.path);return ae({path:e.path,...i})}case"search_model":{if(!t.contextDir)return V("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(Qn(),Jn)),s=await i(t.contextDir,e.q,e.limit);return ae({hits:s})}case"local_apply":return V("local_apply requires a local workspace (handled by the daemon)");default:return V(`unsupported action type: ${e.type}`)}}catch(i){return V(i instanceof Error?i.message:String(i))}}function ae(t){return{status:"done",result:t}}function V(t){return{status:"failed",error:t}}var Ci,am=b(()=>{"use strict";K();ta();Vp();Qp();ue();ef();nf();va();jt();Xo();Ur();Ua();Ii();Ei();Ci=new Map});import{existsSync as uv,mkdtempSync as dv,rmSync as pv}from"node:fs";import{tmpdir as fv}from"node:os";import{join as Ga}from"node:path";import{simpleGit as cm}from"simple-git";async function lm(t,e,r){let n=[];for(let a of e){let c=t.repos.find(u=>u.name===a.repoName);if(!c)return{ok:!1,error:`repo "${a.repoName}" not in project.yaml \u2014 run /sync`};let l=Ga(t.root,c.mountAs);if(!uv(Ga(l,".git")))return{ok:!1,error:`${c.mountAs}/ not cloned \u2014 run /sync first`};n.push({payload:a,dir:l,mountAs:c.mountAs,defaultBranch:c.defaultBranch})}let o=[];for(let a of n){let c=cm(a.dir),l=a.payload;try{await c.fetch()}catch(f){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${to(f)}`}}let u=`origin/${l.baseRef}`;await yv(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(f){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${to(f)}`}}let d;try{d=await Un(c,l.deliverySha,()=>dr(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(f){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${to(f)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let i=[],s=[];for(let a of o){let c=await kv(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await gv(a);await a.git.raw(["branch","-f",a.branch,u]),i.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),s.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await hv(i,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${to(l)} (rolled back all repos)`}}}return{ok:!0,repos:s}}async function gv(t){let e=dv(Ga(fv(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=cm(e);try{await r.raw([...mv,"cherry-pick",t.deliveryCommit])}catch(n){throw await r.raw(["cherry-pick","--abort"]).catch(()=>{}),n}return(await r.revparse(["HEAD"])).trim()}finally{await t.git.raw(["worktree","remove","--force",e]).catch(()=>{}),pv(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function hv(t,e){for(let r of t)try{r.priorSha?await r.git.raw(["branch","-f",r.branch,r.priorSha]):await r.git.raw(["branch","-D",r.branch])}catch(n){e.warn(`[local-apply] rollback of ${r.mountAs}#${r.branch} failed: ${to(n)} \u2014 check manually`)}}async function yv(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function kv(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function to(t){return t instanceof Error?t.message.trim():String(t)}var mv,um=b(()=>{"use strict";Ur();mv=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as wv}from"node:os";import{existsSync as bv,mkdirSync as $v,readFileSync as vv,writeFileSync as xv}from"node:fs";import{dirname as Sv,join as Tv}from"node:path";function Ha(){return q("FARM_PINS")??Tv(wv(),".codepipe","farm-pins.json")}function dm(){let t=Ha();if(!bv(t))return{};try{return JSON.parse(vv(t,"utf-8"))}catch{return{}}}function Rv(t){let e=Ha();$v(Sv(e),{recursive:!0}),xv(e,JSON.stringify(t,null,2)+`
|
|
639
|
+
`,{mode:384})}function Ev(t){return dm()[t]}function Ai(t,e){let r=dm();r[t]=e,Rv(r)}function Pi(t,e){let r=Pe(e),n=Ev(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 ${Ha()}.`);return r}var Wa=b(()=>{"use strict";Ae();Ke()});import{existsSync as pm,readFileSync as fm}from"node:fs";import{join as mm}from"node:path";async function gm(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=Pe(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Pi(e.farmId,e.farmPublicKey);let s=Y(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await te(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=mm(r,"project.yaml"),f=mm(r,"regimen.yaml");pm(d)&&pm(f)?c={projectYaml:fm(d,"utf-8"),regimenYaml:fm(f,"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}:{}},u=$t(e.farmPublicKey,JSON.stringify(l));Ai(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await Vo(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});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))}}var hm=b(()=>{"use strict";Ke();Wa();xe();ue()});import{homedir as Iv}from"node:os";import{existsSync as Cv,mkdirSync as Av,readFileSync as Pv,writeFileSync as _v}from"node:fs";import{dirname as jv,join as Nv}from"node:path";function Ya(){return q("RUNNER_PINS")??Nv(Iv(),".codepipe","runner-pins.json")}function ym(){let t=Ya();if(!Cv(t))return{};try{return JSON.parse(Pv(t,"utf-8"))}catch{return{}}}function Ov(t){let e=Ya();Av(jv(e),{recursive:!0}),_v(e,JSON.stringify(t,null,2)+`
|
|
640
|
+
`,{mode:384})}function Dv(t){return ym()[t]}function qa(t,e){let r=ym();r[t]=e,Ov(r)}function km(t,e){let r=Pe(e),n=Dv(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 ${Ya()}.`);return r}var wm=b(()=>{"use strict";Ae();Ke()});async function bm(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:$m(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}async function xm(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(Pe(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");km(e.runnerId,e.runnerPublicKey);let i=Y(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??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function Sm(t,e,r,n=vm){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await xm(t,e,n);if(!await n.api.repoHasAdmin(i,s.owner,s.repoName))return o(`the GitHub token lacks admin access on ${s.owner}/${s.repoName} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on this repository`);let a={projectId:t.projectId,runners:[{owner:s.owner,repo:s.repoName,regToken:await n.api.mintRegistrationToken(i,s.owner,s.repoName)}],labels:[Ml(e.runnerId)]},c=$t(e.runnerPublicKey,JSON.stringify(a));qa(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function Tm(t,e,r,n=vm){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repo:s}=await xm(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=$t(e.runnerPublicKey,JSON.stringify(c));qa(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var $m,Lv,vm,Rm=b(()=>{"use strict";K();Ke();wm();xe();ue();$m=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});Lv={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:$m(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)=>bm(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>bm(t,e,r,"remove-token")},vm={api:Lv,fetchProject:te,provisionOnRunner:Sd,teardownOnRunner:Td}});function Mv(t){return Me.test(t)?It(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Me}`}function Im(t,e,r,n){let o=Mv(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Wr(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>Em)return{ok:!1,detail:`secret value too large (max ${Em} chars)`};try{return vu(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Cm(t,e){try{return xu(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)}}}var Em,Am=b(()=>{"use strict";K();Ke();ue();Em=16*1024});function Uv(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var _i,Pm=b(()=>{"use strict";jt();_i=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=Xe(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 ir){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=Xe(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=Uv(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}}});function _m(t){let{description:e,...r}=t;return r}function Bv(t){let{body:e,...r}=t;return r}function Fv(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 Kv(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 jm(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 ji,Nm=b(()=>{"use strict";K();Ei();Ii();ji=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??(()=>ft({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}:{},T=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},x=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(x){let $=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[C,U]=await Promise.all([$.length>0?r.listIssues({projectKey:e.projectKey,columns:$,...v,...T}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...v})]),H=new Map;for(let I of[...C,...U])H.set(I.id,I);o=[...H.values()]}else{let $=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:$,...v,...T})}}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 T=await jm(r,v.id,e.sinceMs,this.log);T&&i.set(v.id,T)}let c=[];for(let v of e.offBoardIssueIds){if(s.has(v))continue;let T=await jm(r,v,e.sinceMs,this.log);if(T&&T.length>0&&i.set(v,T),e.requireAssignee||T&&T.length>0){let R=await Kv(r,v,e.stageField,this.log);if(R)c.push(R);else if(T&&T.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(v=>!a.has(v.status)),{attachmentsByIssue:u,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 d=[...l,...c].map(v=>({issue:v,comments:i.get(v.id)??[],attachments:u.get(v.id)??[]}));try{await Ri(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let v of p)this.shippedAttachments.add(v)}catch(v){let T=v instanceof Error?v.message:String(v);this.abandonTick(`context task sync failed: ${T}`);return}let f=this.options.isSelfComment??(()=>!1),m=[],g=[];for(let[v,T]of i){let R=T.filter($=>!f($.id));if(R.length===0)continue;m.push({issueId:v,comments:R.map(Bv)});let x=R.flatMap($=>{let C=Ar($.body);return C?[{commentId:$.id,author:$.author,name:C.name,args:C.args,createdAt:$.createdAt}]:[]});x.length>0&&g.push({issueId:v,commands:x})}let k={type:"youtrack_observation",projectId:e.projectId,issues:o.map(_m),commentsBatch:m,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(_m)}:{},observedAtMs:n};this.send(k);let w=m.reduce((v,T)=>v+T.comments.length,0),h=g.reduce((v,T)=>v+T.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${h} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(m){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${m instanceof Error?m.message:String(m)}`);continue}let f=Fv(u.name);l.has(f)&&(f=`${u.id}-${f}`),l.add(f),c.push({name:f,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}}});import{existsSync as Dm,rmSync as Gv}from"node:fs";import{join as Jr}from"node:path";import{simpleGit as Hv}from"simple-git";import"ws";function Ni(t,e={}){let r=e.log??{info:g=>console.log(g),warn:g=>console.warn(g)};r.info(`codepipe-cli v${Le} (protocol ${ot})`);let n=g=>e.onEvent?.(g),o=e.workspace;o?.contextDir&&ap(o.contextDir,r);let i=Om("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Om("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let g=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(g)&&g>0?g*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=new Set,f=m();function m(){let g=qo(t.hubUrl,t.cliToken),k=null,w=new _i(i,A=>{g.readyState===g.OPEN&&g.send(JSON.stringify(A))},r),h=new ji(s,A=>{g.readyState===g.OPEN&&g.send(JSON.stringify(A))},r,{contextDir:o?.contextDir??null,isSelfComment:A=>d.has(A)}),v=null,T=async()=>{try{let A={trackerProvider:Ka(o?.contextDir??null)};try{let j=await te(t.hubUrl,t.cliToken,t.projectId);A={...A,repos:j.repos,contextRepo:j.contextRepo}}catch(j){r.warn(`[readiness] could not fetch project summary for push checks: ${j instanceof Error?j.message:String(j)}`)}let _=await fd(t.projectId,A);if(g.readyState!==g.OPEN)return;let O={type:"cli_readiness",projectId:t.projectId,ready:_.ready,checks:_.checks,creds:_.creds,secretNames:Su(t.projectId),checkedAt:_.checkedAt};if(g.send(JSON.stringify(O)),_.ready)r.info("[readiness] ready");else{let j=_.checks.filter(S=>!S.ok).map(S=>`${S.name}(${S.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${j.join(", ")}`)}let W=bd(_.creds,u);if(W==="open"){u=!0;let j=$d(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${j}`),ar(j)}else W==="rearm"&&(u=!1)}catch(A){r.warn(`[readiness] check failed: ${A instanceof Error?A.message:String(A)}`)}},R=()=>{T(),v=setInterval(()=>void T(),a),typeof v.unref=="function"&&v.unref()},x=()=>{v&&(clearInterval(v),v=null)},$=150,C=new Map,U=A=>{let _=C.get(A);if(!_||(_.timer&&clearTimeout(_.timer),C.delete(A),_.events.length===0||g.readyState!==g.OPEN))return;let O={type:"run_activity",projectId:t.projectId,runId:A,events:_.events};g.send(JSON.stringify(O))},H=(A,_)=>{let O=C.get(A);if(O||(O={events:[],timer:null},C.set(A,O)),O.events.push(_),_.kind==="result"){U(A);return}O.timer||(O.timer=setTimeout(()=>U(A),$),O.timer.unref?.())},I=o?.contextDir?new ri(o.contextDir,t.projectId,A=>{g.readyState===g.OPEN&&g.send(JSON.stringify(A))},r):null,y=async()=>{let A=o?.contextDir;if(!A)throw new Error("no context repo clone on this CLI");let _;try{_=(await te(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let O=await Ap(A,t.projectId,_,r);return g.readyState===g.OPEN&&g.send(JSON.stringify(O)),O},L=null,N=async()=>{let A=o?.contextDir;if(A)try{let{readContextIndexHub:_,collectSearchRows:O}=await Promise.resolve().then(()=>(Qn(),Jn));if(_(A)!=="metadata")return;let W=O(A);g.readyState===g.OPEN&&(g.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:W})),r.info(`[model] tier-2 index snapshot pushed (${W.length} rows)`))}catch(_){r.warn(`[model] tier-2 index push failed (non-fatal): ${_ instanceof Error?_.message:String(_)}`)}},F=()=>{L&&clearTimeout(L),L=setTimeout(()=>void N(),5e3)};return g.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let A=_u(t.projectId),_=q("ORIGIN")==="farm"?"farm":"local",O=q("FARM_ID"),W=t.accountEmail??A.email,j;try{let E=Kp(t.projectId);E&&(j=E.publicKey,r.info(`[cred-channel] key fingerprint: ${E.fingerprint}`))}catch(E){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${E instanceof Error?E.message:String(E)}`)}let S={type:"register",projectId:t.projectId,platformVersion:Le,protocolVersion:ot,accountId:A.accountId,accountLabel:A.label,origin:_,inFlightActionIds:[...p],...W?{accountEmail:W}:{},..._==="farm"&&O?{farmId:O}:{},...j?{sealPublicKey:j}:{}};g.send(JSON.stringify(S))}),g.on("message",async A=>{let _=A.toString("utf-8");if(_==="pong"||_==="ping")return;let O;try{O=JSON.parse(_)}catch{return}if(!O||typeof O!="object")return;let W=O.type;if(W==="registered"){let S=O;if(S.ok){if(r.info(`[ws] registered for project ${S.projectId}`),n({kind:"registered",projectId:S.projectId??t.projectId}),w.start(),I?.start(),R(),za(t,o,r),o?.contextDir){try{let E=ai(o.contextDir,t.projectId);g.readyState===g.OPEN&&g.send(JSON.stringify(E)),E.outdated&&(r.warn(`[ctx] context format outdated: v${E.templateVersion} \u2192 v${E.currentVersion}`+(E.missingPaths.length>0?` (missing: ${E.missingPaths.join(", ")})`:"")),l||(l=!0,y().catch(()=>{})))}catch(E){r.warn(`[ctx] context-format detect failed (non-fatal): ${E instanceof Error?E.message:String(E)}`)}N()}}else r.warn(`[ws] register rejected: ${S.reason??"unknown"}`),n({kind:"register_rejected",reason:S.reason??"unknown"}),c=!0,g.close();return}if(W==="hello"){let S=O;k=$o(S.protocolVersion);let E=k?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${E}`),k||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Le}, protocol ${ot}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Va}`),n({kind:"incompatible",hubVersion:typeof S.platformVersion=="string"?S.platformVersion:null,hubProtocol:typeof S.protocolVersion=="number"?S.protocolVersion:null,updateCommand:Va}));return}if(W==="tracking_targets"){w.setTargets(O.targets);return}if(W==="youtrack_sync_request"){h.setRequest(O);return}if(W==="youtrack_force_sync"){h.forceSync();return}if(W==="sync_local"){await qv(O,o,g,r);return}if(W==="provision_repo"){let S=O;r.info(`[repo] provision_repo: ${S.repo.name} (${S.repo.host}:${S.repo.owner}/${S.repo.repoName})`),await Wv(t,o,S.repo,r),await za(t,o,r);return}if(W==="remove_repo"){let S=O;r.info(`[repo] remove_repo: ${S.repoName}${S.purge?" (purge)":""}`),await za(t,o,r),S.purge&&Yv(t,o,S.repoName,r);return}if(W==="context_write"){await Vv(O,o,g,r);return}if(W==="adr_promote"){await zv(O,o,g,r);return}if(W==="cred_update"){let S=O,E=Y(t.projectId),z=E?.sealKey?await Gp(t.projectId,S.kind,S.sealed,E.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},ie={type:"cred_update_result",updateId:S.updateId,projectId:t.projectId,ok:z.ok,...z.detail?{detail:z.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(ie)),z.ok?(r.info(`[cred] ${S.kind} replaced${z.detail?` \u2014 ${z.detail}`:""}`),T()):r.warn(`[cred] ${S.kind} replacement rejected: ${z.detail??"unknown"}`);return}if(W==="readiness_check"){r.info("[readiness] on-demand check requested"),T();return}if(W==="agent_login_start"){kd(t,g,O,r,T);return}if(W==="move_to_farm"){let S=O;r.info(`[farm-move] request to move ${t.projectId} onto farm ${S.farmName} (${S.farmId})`);let E=await gm(t,S,o?.contextDir,r);g.readyState===g.OPEN&&g.send(JSON.stringify(E)),E.ok?r.info(`[farm-move] done \u2014 farm daemon ${E.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${E.error??"unknown error"}`);return}if(W==="gh_runner_setup"){let S=O;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let E=await Sm(t,S,r);g.readyState===g.OPEN&&g.send(JSON.stringify(E)),E.ok?r.info(`[ghr] runners connected on ${S.runnerName}`):r.warn(`[ghr] setup failed: ${E.error??"see per-repo statuses"}`);return}if(W==="gh_runner_teardown"){let S=O;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let E=await Tm(t,S,r);g.readyState===g.OPEN&&g.send(JSON.stringify(E)),E.ok?r.info(`[ghr] runners disconnected from ${S.runnerName}`):r.warn(`[ghr] teardown failed: ${E.error??"unknown error"}`);return}if(W==="tracker_fields_request"){let S=O,E={type:"tracker_fields_result",requestId:S.requestId,projectId:t.projectId,ok:!1},z=ft({contextDir:o?.contextDir??null});if(!z.ok)E.error=z.error;else try{E.fields=await z.provider.fetchStateFields(S.projectKey),E.ok=!0}catch(ie){E.error=ie instanceof Error?ie.message:String(ie)}g.readyState===g.OPEN&&g.send(JSON.stringify(E)),E.ok||r.warn(`[yt-fields] listing failed: ${E.error??"unknown"}`);return}if(W==="project_secret_update"||W==="project_secret_delete"){let S=O,E;if(S.type==="project_secret_update"){let ie=Y(t.projectId);E=ie?.sealKey?Im(t.projectId,S.name,S.sealed,ie.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else E=Cm(t.projectId,S.name);let z={type:"project_secret_update_result",updateId:S.updateId,projectId:t.projectId,ok:E.ok,...E.detail?{detail:E.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(z)),E.ok?(r.info(`[secret] ${S.name} ${S.type==="project_secret_update"?"saved":"deleted"}`+(E.detail?` \u2014 ${E.detail}`:"")),T()):r.warn(`[secret] ${S.name} rejected: ${E.detail??"unknown"}`);return}if(W==="auto_apply_local"){let S=O;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${S.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let E=await Xd({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},S.claim,r).catch(z=>({ok:!1,message:z instanceof Error?z.message:String(z)}));E.ok?r.info(`[apply] ${S.claim.taskKey}: ${E.message}`):r.warn(`[apply] ${S.claim.taskKey}: ${E.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:S.claim.taskKey,ok:E.ok,...E.ok?{branches:E.branches??[]}:{error:E.message}});return}if(W==="sandbox_keys"){let S=Y(t.projectId);if(!S){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let E=Nr(t.projectId),z=Lp(O,S,E,r);for(let ie of z)g.readyState===g.OPEN&&g.send(JSON.stringify(ie));return}if(W!=="dispatch_action")return;let j=O;if(k===!1){let S=`refused: HUB protocol incompatible with CLI v${Le} (protocol ${ot})`;g.send(JSON.stringify({type:"action_result",actionId:j.actionId,status:"failed",error:S})),r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 REFUSED: ${S}`),r.warn(`[exec] update the CLI to clear this: ${Va}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:!1,error:S});return}if(j.action.type==="local_apply"){p.add(j.actionId);try{let S;if(!o)S={status:"failed",error:"no local workspace on this CLI"};else{let z=await lm(o,j.action.repos,r);if(S=z.ok?{status:"done",result:{repos:z.repos}}:{status:"failed",error:z.error},z.ok&&o.contextDir){let ie=j.action.taskId.split(":")[1]??"";for(let Qt of ie?z.repos:[]){let D=o.repos.find(he=>he.name===Qt.repoName);if(!D)continue;let{recordPipelineEvent:le}=await Promise.resolve().then(()=>(Ua(),Zf));await le({contextDir:o.contextDir,repoDir:Jr(o.root,D.mountAs),repoName:Qt.repoName,taskKey:ie,commitSha:Qt.commit}).catch(he=>r.warn(`[model] task event for ${ie} failed: ${he instanceof Error?he.message:String(he)}`))}F()}}g.send(JSON.stringify({type:"action_result",actionId:j.actionId,...S}));let E=S.status!=="failed";E?r.info(`[exec] ${j.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${j.actionId} (local_apply) \u2192 FAILED: ${S.status==="failed"?S.error:"?"}`),n({kind:"action",actionId:j.actionId,actionType:"local_apply",ok:E,...S.status==="failed"?{error:S.error}:{}})}finally{p.delete(j.actionId)}return}p.add(j.actionId);try{let S=await sm({action:j.action,repo:j.repo,trackerIssueId:j.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:I?()=>I.reportNow():void 0,refreshContextStatus:o?.contextDir?y:void 0,onRunActivity:H}).catch(ie=>({status:"failed",error:ie instanceof Error?ie.message:String(ie)}));j.action.type==="tracker_comment"&&S.status==="done"&&"result"in S&&typeof S.result?.commentId=="string"&&d.add(S.result.commentId),g.send(JSON.stringify({type:"action_result",actionId:j.actionId,...S}));let E=S.status!=="failed",z=!E&&"error"in S?S.error:void 0;E?r.info(`[exec] ${j.actionId} (${j.action.type}) \u2192 done`):r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 FAILED: ${z??"?"}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:E,...z?{error:z}:{}}),E&&["apply_delivery","context_write","create_pr"].includes(j.action.type)&&F()}finally{p.delete(j.actionId)}}),g.on("close",(A,_)=>{let O=_?.toString("utf-8")??"";if(r.info(`[ws] closed code=${A}${O?` reason=${O}`:""}`),w.stop(),h.stop(),I?.stop(),x(),O==="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:A}),!c&&setTimeout(()=>{f=m()},2e3)}),g.on("error",A=>r.warn(`[ws] error: ${A.message}`)),g}return{stop(){c=!0,f.close()}}}async function za(t,e,r){try{let n=await te(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Yn(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 Wv(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?Jr(e.root,o):Re(t.projectId,r.name);if(Dm(Jr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await Hv().clone(Bn(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 Yv(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Jr(e.root,o):Re(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Dm(Jr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Gv(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 qv(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=Jr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Qd(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 Vv(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 Se(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 zv(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 mp(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 Om(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var Va,Xa=b(()=>{"use strict";Ae();K();ju();wd();vd();Yo();Zs();Zd();ip();gp();Ze();bt();da();Pp();ha();Ur();Mp();Hp();am();um();hm();Rm();xe();Am();Mr();ue();Pm();Nm();Ii();Va="npm i -g @code-partner/codepipe@latest"});import{execFileSync as Xv}from"node:child_process";import{mkdtempSync as Jv,mkdirSync as Qv,readFileSync as Lm,rmSync as Zv,writeFileSync as ex}from"node:fs";import{tmpdir as tx}from"node:os";import{dirname as rx,join as Mm}from"node:path";function Um(t="codepipe-context"){let e=Jv(Mm(tx(),"codepipe-ssh-")),r=Mm(e,"id_ed25519");try{return Xv("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Lm(r,"utf-8"),publicKey:Lm(`${r}.pub`,"utf-8").trim()}}finally{Zv(e,{recursive:!0,force:!0})}}async function Bm(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 Fm(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 Km(t,e){Qv(rx(t),{recursive:!0});let r=e.endsWith(`
|
|
638
641
|
`)?e:e+`
|
|
639
|
-
`;return
|
|
640
|
-
`,{mode:384})}var
|
|
641
|
-
`}async function
|
|
642
|
-
`))!==-1;){let
|
|
643
|
-
`)){let
|
|
642
|
+
`;return ex(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Ja=b(()=>{"use strict"});import{existsSync as Gm,mkdirSync as Hm}from"node:fs";import{dirname as Wm}from"node:path";import{simpleGit as Qr}from"simple-git";function nx(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 ox(t,e){return e?.contextWrite?.token?{user:Po(t),secret:e.contextWrite.token}:t===jn.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===jn.bitbucket?e?.bitbucket?.apiToken?{user:nr,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Ym(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 Oi))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 Di(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await te(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new Oi(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=ox(_r(s.cloneUrl),r);if(a){let c=await ix({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 sx({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 ix(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=nx(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(Gm(`${r}/.git`)){let l=Qr(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=oa(r);await l.reset(["--hard",`origin/${s}`]),ia(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Hm(Wm(r),{recursive:!0}),await Qr().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await qm(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 sx(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Km(i,n),a=Fm(e.cloneUrl),c=e.branch;try{if(Gm(`${r}/.git`)){let l=Qr(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 u=oa(r);await l.reset(["--hard",`origin/${c}`]),ia(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Hm(Wm(r),{recursive:!0}),await Qr().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Qr(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await qm(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 qm(t){let e=Qr(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 Oi,Qa=b(()=>{"use strict";K();xe();bt();Ja();Oi=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as ax}from"node:child_process";function cx(){try{return ax("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function zm(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:cx(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Xm=b(()=>{"use strict"});import{homedir as Zr}from"node:os";import{mkdirSync as lx,readFileSync as Jm,writeFileSync as ux,existsSync as ec}from"node:fs";import{dirname as dx,join as Bt}from"node:path";function px(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function tt(t){let e=q("SANDBOX_CONFIG");if(e)return e;let r=Bt(Zr(),".codepipe","worker");return t?Bt(r,"profiles",t,"config.json"):Bt(r,"config.json")}function Qm(){return Bt(Zr(),".devpipe-sandbox","config.json")}function Li(){or(Bt(Zr(),".devpipe"),Bt(Zr(),".codepipe")),q("SANDBOX_CONFIG")||or(Bt(Zr(),".devpipe-sandbox"),Bt(Zr(),".codepipe-sandbox"))}function Zm(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Ee(t){let e=tt(t),r=null;return ec(e)?r=JSON.parse(Jm(e,"utf-8")):!t&&!q("SANDBOX_CONFIG")&&ec(Qm())&&(r=JSON.parse(Jm(Qm(),"utf-8"))),r?(r.planningLane=px(),r):null}function eg(t,e){let r=tt(e);lx(dx(r),{recursive:!0}),ux(r,JSON.stringify(t,null,2)+`
|
|
643
|
+
`,{mode:384})}var Mi=b(()=>{"use strict";Ae();_o();ec(".env")&&process.loadEnvFile(".env")});import fx from"ws";var en,tc=b(()=>{"use strict";en=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 fx(e)}}});import{hostname as mx}from"node:os";async function kr(t){Li();let e=Ee(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${tt(t.profile)}.`),process.exit(1));let r=t.name??mx(),n=zm({projects:t.projects??[],llm:t.llm??null}),o=new en(t.hub.replace(/\/$/,"")),i=ui(),s=Pe(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});eg({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 ${tt(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 tg=b(()=>{"use strict";Ke();Xm();Mi();tc()});import{spawn as gx}from"node:child_process";function rc(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function yx(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 kx(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function wr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function nc(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
|
|
644
|
+
`}async function ig(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new vt;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(),u=c.type;if(u==="assistant"){let p=c.message;for(let d of p?.content??[]){let f=d.type;if(f==="text"){let m=String(d.text??"").trim();m&&o({ts:l,kind:"text",author:"agent",text:rc(m,rg)})}else if(f==="tool_use"){let m=String(d.name??""),g=d.input?.file_path??d.input?.path,k=yx(g,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:m,...k?{file:k}:{}})}}return}if(u==="user"){let p=c.message;for(let d of p?.content??[])if(d.type==="tool_result"){let f=d.is_error===!0,m=f?rc(kx(d.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:f,...m?{text:m}:{}})}return}if(u==="result"){s=c;let p=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...p?{text:p}:{}});return}if(u==="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 u=gx(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let p=!1,d=!1,f=null,m=()=>{p=!0,u.kill("SIGTERM"),f=setTimeout(()=>u.kill("SIGKILL"),ng)};e.signal?.addEventListener("abort",m,{once:!0});let g=null,k=()=>{g&&clearTimeout(g),g=setTimeout(()=>{d=!0,console.warn(`[claude:chat] idle for ${og}ms \u2014 ending session`),u.kill("SIGTERM"),f=setTimeout(()=>u.kill("SIGKILL"),ng)},og)},w=()=>{f&&clearTimeout(f),g&&clearTimeout(g),e.signal?.removeEventListener("abort",m)},h=!0,v=x=>{if(!(!h||u.stdin.destroyed))try{u.stdin.write(x)}catch{}};v(nc(e.prompt)),k(),(async()=>{try{for await(let x of e.interactive.inbox){if(p||!h)break;if(k(),x.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:rc(x.text,rg)}),v(nc(x.text));else{v(nc(hx)),h=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let T="",R=x=>{let $;try{$=JSON.parse(x)}catch{return}a($)};u.stdout.on("data",x=>{i.push(x),k(),T+=x;let $;for(;($=T.indexOf(`
|
|
645
|
+
`))!==-1;){let C=T.slice(0,$).trim();T=T.slice($+1),C&&R(C)}}),u.stderr.on("data",x=>{i.push(x);for(let $ of x.split(`
|
|
646
|
+
`)){let C=$.trim();C&&console.warn(`[claude:chat:stderr] ${C}`)}}),u.on("error",x=>{w(),l(x)}),u.on("close",x=>{if(w(),p){l(new vt);return}if(d){l(new Error("chat session ended: idle for too long without a reply"));return}T.trim()&&R(T.trim()),console.log(`[claude:chat] exit code=${x}`),c({artifactPaths:[],log:i.join(""),usage:wx(s)})})})}function wx(t){let e=er();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=wr(r.input_tokens),e.outputTokens=wr(r.output_tokens),e.cacheReadInputTokens=wr(r.cache_read_input_tokens),e.cacheCreationInputTokens=wr(r.cache_creation_input_tokens)),e.totalCostUsd=wr(t.total_cost_usd),e.numTurns=wr(t.num_turns),e.durationMs=wr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var rg,ng,og,hx,sg=b(()=>{"use strict";K();tn();rg=16e3,ng=5e3,og=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),hx="\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 bx}from"node:child_process";import{existsSync as $x}from"node:fs";function xx(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function ag(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: ${Ft(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=Rx(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=lg(o.content);console.log(`[claude] tool_result (error)${i?`: ${Ft(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)} ${Ft(JSON.stringify(e),200)}`),e}function Sx(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(Ft(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(Ft(r.trim().split(`
|
|
644
647
|
`).slice(-5).join(`
|
|
645
|
-
`),500)),n.join(" \u2014 ")}function
|
|
646
|
-
`))!==-1;){let
|
|
647
|
-
`)){let
|
|
648
|
+
`),500)),n.join(" \u2014 ")}function Tx(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 lg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Rx(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=${Ft(r,80)}`}return""}function Ft(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 Ex(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 Ix(t,e,r,n){let o=er(),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 Cx(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:Ft(c,cg)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=Ax(u,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?Ft(lg(s.content),cg):"";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 Ax(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 rn,vt,vx,no,cg,tn=b(()=>{"use strict";K();sg();rn=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},vt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},vx=5e3;no=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return ig(this.binary,e);if(e.signal?.aborted)throw new vt;let r=["-p",xx(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 m of e.addDirs??[])r.push("--add-dir",m);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=m=>{if(m){if(m.type==="result"){i=m;return}if(m.type==="rate_limit_event"){let g=Ex(m.rate_limit_info);g&&(!l||g.utilization>l.utilization)&&(l=g);return}if(m.type==="assistant"){let g=m.message;typeof g?.model=="string"&&(c=g.model);let k=g?.usage;k&&(a+=1,s.input+=_e(k.input_tokens),s.output+=_e(k.output_tokens),s.cacheRead+=_e(k.cache_read_input_tokens),s.cacheCreate+=_e(k.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,f=m=>{if(d)for(let g of Cx(m,e.workspaceDir))try{d(g)}catch{}};return d?.({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((m,g)=>{let k=bx(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"}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let w=!1,h=null,v=()=>{w=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),k.kill("SIGTERM"),h=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},vx)};e.signal?.addEventListener("abort",v,{once:!0});let T=()=>{h&&clearTimeout(h),e.signal?.removeEventListener("abort",v)},R="";k.stdout.on("data",x=>{n.push(x),R+=x;let $;for(;($=R.indexOf(`
|
|
649
|
+
`))!==-1;){let C=R.slice(0,$).trim();if(R=R.slice($+1),C){let U=ag(C);u(U),U&&f(U)}}}),k.stderr.on("data",x=>{n.push(x),o.push(x);for(let $ of x.split(`
|
|
650
|
+
`)){let C=$.trim();C&&console.warn(`[claude:stderr] ${C}`)}}),k.on("error",x=>{T(),g(x)}),k.on("close",x=>{if(T(),w){g(new vt);return}if(R.trim()){let C=ag(R.trim());u(C),C&&f(C)}let $=i?.is_error===!0;if(x!==0||$){let C=typeof i?.api_error_status=="number"?i.api_error_status:void 0,U=typeof i?.subtype=="string"?i.subtype:void 0,H=typeof i?.result=="string"?i.result:void 0;g(new rn(Sx(x,i,o.join("")),{code:x,apiErrorStatus:C,subtype:U,resultText:H,retryAfterMs:Tx(i)}));return}console.log("[claude] exit code=0"),m({artifactPaths:[],log:n.join(""),usage:Ix(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("/")&&$x(n))}};cg=200});import{mkdirSync as Px,writeFileSync as nn}from"node:fs";import{dirname as _x,join as on}from"node:path";function ug(t,e,r){let n=on(t,e);Px(_x(n),{recursive:!0}),nn(n,r)}function jx(t,e,r){return`# ${t} \u2014 Estimate
|
|
648
651
|
|
|
649
652
|
**Title:** ${e}
|
|
650
653
|
|
|
@@ -665,7 +668,7 @@ production-grade estimates.)
|
|
|
665
668
|
${r.split(`
|
|
666
669
|
`).slice(0,8).join(`
|
|
667
670
|
`).trim()||"(empty)"}
|
|
668
|
-
`}function
|
|
671
|
+
`}function Nx(t,e,r,n){let o=n?`
|
|
669
672
|
## Reviewer rework instruction
|
|
670
673
|
|
|
671
674
|
> ${n.split(`
|
|
@@ -694,10 +697,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
694
697
|
${r.split(`
|
|
695
698
|
`).slice(0,8).join(`
|
|
696
699
|
`).trim()||"(empty)"}
|
|
697
|
-
`}function
|
|
700
|
+
`}function Ox(t){return`# ${t} \u2014 Open questions
|
|
698
701
|
|
|
699
702
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
700
|
-
`}function
|
|
703
|
+
`}function Dx(t,e,r){let n=r?` (rework: ${r.split(`
|
|
701
704
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
702
705
|
index 0000000..1111111 100644
|
|
703
706
|
--- a/CHANGELOG.md
|
|
@@ -708,7 +711,7 @@ index 0000000..1111111 100644
|
|
|
708
711
|
+- mock-runner placeholder change for slice 5 testing.
|
|
709
712
|
+
|
|
710
713
|
# Changelog
|
|
711
|
-
`}function
|
|
714
|
+
`}function Lx(t,e,r){return`# ${t} \u2014 Diff summary
|
|
712
715
|
|
|
713
716
|
**Title:** ${e}
|
|
714
717
|
${r?`
|
|
@@ -719,143 +722,143 @@ ${r?`
|
|
|
719
722
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
720
723
|
|
|
721
724
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
722
|
-
`}var
|
|
723
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:
|
|
725
|
+
`}var oo,oc=b(()=>{"use strict";K();tn();oo=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=jx(n,o,i);nn(on(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;nn(on(e.workspaceDir,"SOLUTION.md"),Nx(n,o,i,a)),s.push("SOLUTION.md"),nn(on(e.workspaceDir,"QUESTIONS.md"),Ox(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;ug(e.workspaceDir,"changes/sample.patch",Dx(n,o,a)),s.push("changes/sample.patch"),ug(e.workspaceDir,"diff-summary.md",Lx(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(nn(on(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
726
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:er()}}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 vt;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 nn(on(e.workspaceDir,"DRAFT.md"),`${o}
|
|
724
727
|
|
|
725
728
|
\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).
|
|
726
|
-
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:
|
|
729
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:er()}}}});function dg(t){switch(t){case"mock":return new oo;case"claude-headless":return new no;default:return null}}function pg(t,e){let r=e&&e.trim().length>0?e.trim():at;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var fg=b(()=>{"use strict";K();tn();oc();tn();oc()});function hg(t=process.env){return{maxAttempts:Ui(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Ui(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Ui(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Ui(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function Fx(t){if(t instanceof rn){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return Ux.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&Bx.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:Mx.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:mg.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 mg.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function yg(t){if(t instanceof rn){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&gg.test(n)}let e=t instanceof Error?t.message:String(t);return gg.test(e)}function Kx(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 kg(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=Fx(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 u=Kx(s,r.policy,c.retryAfterMs);if(Date.now()+u>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 ${u}ms`),await r.onBeforeRetry(),await n(u)}}function Ui(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var Mx,mg,Ux,Bx,gg,wg=b(()=>{"use strict";tn();Mx=new Set([429,500,502,503,529]),mg=/(\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,Ux=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,Bx=new Set(["error_max_turns"]);gg=/(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 Gx,rmSync as Hx,writeFileSync as bg}from"node:fs";import{tmpdir as Wx}from"node:os";import{join as ic}from"node:path";function Bi(t){return`[url "https://${t}/"]
|
|
727
730
|
insteadOf = git@${t}:
|
|
728
731
|
insteadOf = ssh://git@${t}/
|
|
729
|
-
`}function
|
|
732
|
+
`}function $g(t,e){if(t.length===0)return null;let r=Gx(ic(Wx(),"devpipe-gitcreds-")),n=ic(r,"credentials"),o=ic(r,"gitconfig");return bg(n,t.join(`
|
|
730
733
|
`)+`
|
|
731
|
-
`,{mode:384}),
|
|
734
|
+
`,{mode:384}),bg(o,`[credential]
|
|
732
735
|
helper = store --file=${n}
|
|
733
|
-
`+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{
|
|
734
|
-
`).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await
|
|
735
|
-
`).map(l=>l.trim()).filter(l=>l.length>0),c=await
|
|
736
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function
|
|
737
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
738
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=
|
|
739
|
-
`+e.subarray(e.length-
|
|
740
|
-
\u2026 [${r.length-e} bytes elided]`}var
|
|
736
|
+
`+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{Hx(r,{recursive:!0,force:!0})}catch{}}}}function sc(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Yx)),t.bitbucket?.apiToken&&(e.push(`https://${nr}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(qx)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Vx)),$g(e,r)}function vg(t,e){if(t.contextWrite?.token){let r=_r(e)??"github.com",n=Po(r);return $g([`https://${n}:${t.contextWrite.token}@${r}`],[Bi(r)])}return sc(t)}var Yx,qx,Vx,xg=b(()=>{"use strict";K();Yx=Bi("github.com"),qx=Bi("bitbucket.org"),Vx=Bi("gitlab.com")});import{spawn as Tg}from"node:child_process";import{existsSync as Fi,mkdirSync as io,readFileSync as zx,rmSync as ac,symlinkSync as Xx}from"node:fs";import{homedir as Jx}from"node:os";import{dirname as an,join as Kt}from"node:path";function Rg(t){let e=Kt(Jx(),".codepipe-sandbox","repos");return t?Kt(e,t):e}function Eg(t,e){let n=(sn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{sn.get(t)===o&&sn.delete(t)},()=>{sn.get(t)===o&&sn.delete(t)});return sn.set(t,o),n}function Sg(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 Qx(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 Ig(t,e,r,n,o){let i=async c=>{await ne(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ne(t,["reset","--hard",`origin/${c}`],o),await ne(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!Sg(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Fi(t)&&ac(t,{recursive:!0,force:!0}),io(an(t),{recursive:!0});try{return await ne(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Sg(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Fi(t)&&ac(t,{recursive:!0,force:!0}),io(an(t),{recursive:!0}),await ne(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Fi(Kt(t,".git")))try{return await s()}catch(c){if(!Qx(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 Cg(t){await ne(t.workspacePath,["reset","--hard",t.baseSha]),await ne(t.workspacePath,["clean","-fdx"])}async function Ag(t,e){let r=t.workspacePath;await ne(r,["add","-A"]);let n=(await Te(r,["write-tree"])).trim(),o=(await Te(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:cn,GIT_AUTHOR_EMAIL:ln,GIT_COMMITTER_NAME:cn,GIT_COMMITTER_EMAIL:ln};return(await Te(r,["commit-tree",n,"-m",e],i)).trim()}async function Pg(t,e,r,n,o){try{await ne(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw _r(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 _g(t,e){return Te(t.workspacePath,["diff","--binary",t.baseSha,e])}async function jg(t,e,r,n,o){await ne(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ne(t.workspacePath,["checkout","--force",r])}async function Ng(t,e,r,n,o,i){let s=t.workspacePath;await ne(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await Te(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=m=>Te(s,["rev-parse","-q","--verify",`${m}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Te(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ne(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(g=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(g)}`)}),await c(n)||await ne(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:cn,GIT_AUTHOR_EMAIL:ln,GIT_COMMITTER_NAME:cn,GIT_COMMITTER_EMAIL:ln},u=(await Te(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Te(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ne(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ne(s,["cherry-pick","--no-commit",p],l)}catch(m){d=m instanceof Error?m.message:String(m)}let f=(await Te(s,["diff","--name-only","--diff-filter=U"])).split(`
|
|
737
|
+
`).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await ne(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return f}async function cc(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:cn,GIT_AUTHOR_EMAIL:ln,GIT_COMMITTER_NAME:cn,GIT_COMMITTER_EMAIL:ln};(await Te(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ne(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 ne(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ne(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Te(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
738
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await Te(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 ne(t,e,r){return new Promise((n,o)=>{let i=Tg("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}):
|
|
739
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function Te(t,e,r){return new Promise((n,o)=>{let i=Tg("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}):
|
|
740
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function Og(t,e){Fi(t)&&ac(t,{recursive:!0,force:!0}),io(an(t),{recursive:!0}),Xx(e,t,"dir")}async function Dg(t,e,r){await ne(t,["worktree","prune"]).catch(()=>{}),io(an(r),{recursive:!0}),await ne(t,["worktree","add","--detach",r,`origin/${e}`])}async function Zx(t,e,r){io(an(r),{recursive:!0}),await ne(an(r),["clone","--quiet","--no-checkout",t,r]),await ne(r,["checkout","--force","--detach",e])}async function Lg(t,e,r,n="worktree",o,i){return r.length===0?[]:Eg(e,async()=>{let s=[];for(let a of r){let c=Kt(Rg(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await Ig(c,a.cloneUrl,a.ref,a.defaultBranch,o)}catch(d){throw new Error(`failed to materialize project repo "${a.name}" (${a.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let u=(await Te(c,["rev-parse","HEAD"])).trim(),p=Kt(t,"code",a.name);n==="direct"?(Og(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await Zx(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await Dg(c,l,p),console.log(`[git] code: worktree ${p} \u2190 ${c} @ ${u.slice(0,10)}`)),s.push({name:a.name,workspacePath:p,cachePath:c,ref:l,baseSha:u})}return s})}async function Mg(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return Eg(e,async()=>{let a=Kt(Rg(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await Ig(a,s.cloneUrl,s.ref,void 0,o)}catch(u){throw new Error(`failed to materialize context repo (${s.cloneUrl}): `+(u instanceof Error?u.message:String(u)))}let c=Kt(t,"context");n==="direct"?(Og(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Dg(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Te(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function Ug(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ne(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Te(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
|
|
741
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=zx(Kt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var sn,cn,ln,Bg=b(()=>{"use strict";K();sn=new Map;cn="CodePipe Agent",ln="codepipe@codepartner.ee"});import{readFileSync as eS}from"node:fs";import{join as tS}from"node:path";function Fg(t){let e=tS(t,so),r;try{r=eS(e,"utf-8")}catch{throw new Gt(`BUILD produced no ${so} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Gt(`${so} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Gt(`${so} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Gt(`${so}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,f=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||f===null)return[];let m={name:d,exitCode:f};return typeof p.durationMs=="number"&&(m.durationMs=p.durationMs),[m]}),c=typeof o.logTail=="string"?rS(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let u=a.find(p=>p.exitCode!==0);u&&(l.failedStep=u.name)}return l}function rS(t){let e=Buffer.from(t,"utf-8");return e.length<=lc?t:`\u2026 [${e.length-lc} bytes elided] \u2026
|
|
742
|
+
`+e.subarray(e.length-lc).toString("utf-8")}var lc,Gt,so,Kg=b(()=>{"use strict";lc=8*1024,Gt=class extends Error{},so="meta/build-result.json"});import{readFileSync as nS}from"node:fs";import{join as oS}from"node:path";function Hg(t){let e=oS(t,un),r;try{r=nS(e,"utf-8")}catch{throw new xt(`code review produced no ${un} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new xt(`${un} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new xt(`${un} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new xt(`${un}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?Gg(o.remarks,iS):"";if(!i&&s.trim().length===0)throw new xt(`${un}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?Gg(o.summary,sS):"";return{approved:i,remarks:s,summary:a}}function Gg(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
|
|
743
|
+
\u2026 [${r.length-e} bytes elided]`}var iS,sS,xt,un,Wg=b(()=>{"use strict";iS=16*1024,sS=4*1024,xt=class extends Error{},un="meta/review-result.json"});import{readFileSync as aS,statSync as cS}from"node:fs";import{join as Yg}from"node:path";function gS(t){return t.startsWith("meta/")||mS.has(t)}function hS(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 yS(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function qg(t,e,r){let n=r?.maxBytes??lS,o=r?.totalBytes??uS,i=r?.maxCount??dS,s=e.map((m,g)=>{let k=null;try{k=cS(Yg(t,m)).size}catch{}return{path:m,index:g,size:k}}),a=[...s].sort((m,g)=>{let k=w=>gS(w.path)?0:1;return k(m)!==k(g)?k(m)-k(g):(m.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((m,g)=>m.index-g.index).map(m=>m.path),u=new Array(s.length),p=[],d=0;for(let m of c){let g=null;if(m.size!==null&&m.size<=n&&d+m.size<=o)try{g=aS(Yg(t,m.path))}catch{}if(g!==null){d+=g.length,u[m.index]={path:m.path,contentBase64:g.toString("base64")};continue}let k=m.size===null?yS(m.path):hS(m.path,m.size,n,o),w=Buffer.from(k,"utf-8");d+=w.length,u[m.index]={path:m.path,contentBase64:w.toString("base64")},p.push({path:m.path,bytes:m.size??0})}let f=u.filter(m=>m!==void 0);if(l.length>0){let m=l.slice(0,fS),g=`# Artifacts omitted from upload
|
|
741
744
|
|
|
742
745
|
${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.
|
|
743
746
|
|
|
744
747
|
`+m.map(k=>`- ${k}
|
|
745
748
|
`).join("")+(l.length>m.length?`
|
|
746
749
|
\u2026and ${l.length-m.length} more.
|
|
747
|
-
`:"");f.push({path:
|
|
748
|
-
${n}`.match(
|
|
749
|
-
${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let f of c){let m=f.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!m||!m.includes("/")&&!m.includes("."))continue;let g=a.get(m)??[];g.length===1&&s(g[0],
|
|
750
|
-
${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let m=l.get(f.toLowerCase());m&&s(m,
|
|
751
|
-
${n}`),d=[];for(let[f,m]of o.events){if(f===e||!m.title)continue;let g=
|
|
752
|
-
`));let u=
|
|
750
|
+
`:"");f.push({path:pS,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:f,omitted:p,dropped:l}}var lS,uS,dS,pS,fS,mS,Vg=b(()=>{"use strict";lS=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),uS=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),dS=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),pS="artifacts-omitted.md",fS=500,mS=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 kS,mkdtempSync as wS,readFileSync as bS,readdirSync as Xg,rmSync as zg}from"node:fs";import{tmpdir as $S}from"node:os";import{join as Ki,relative as vS}from"node:path";function Jg(t){let e=wS(Ki($S(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>zg(e,{recursive:!0,force:!0}),listFiles:()=>Qg(e,e),readFile:r=>bS(Ki(e,r),"utf-8"),clean:()=>{for(let r of Xg(e))SS.has(r)||zg(Ki(e,r),{recursive:!0,force:!0})}}}function Qg(t,e){let r=[];for(let n of Xg(e)){let o=Ki(e,n),i=kS(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&xS.has(n))continue;r.push(...Qg(t,o))}else r.push(vS(t,o))}return r}var xS,SS,Zg=b(()=>{"use strict";xS=new Set(["code","context","scratch"]),SS=new Set(["code","context"])});import{existsSync as Hi,readFileSync as eh,readdirSync as uc}from"node:fs";import{join as St}from"node:path";import{parse as TS}from"yaml";function Wi(t){if(!Hi(t))return[];let e=[];for(let r of uc(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=St(t,r.name);r.isDirectory()?e.push(...Wi(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Gi(t){try{return TS(eh(t,"utf-8"))}catch{return null}}function th(t){let e={nodes:new Map,adjacency:new Map,events:new Map,annotations:new Map,keyByEntity:new Map,orphanedEntities:new Set,empty:!0},r=(i,s,a,c)=>{e.adjacency.has(i)||e.adjacency.set(i,[]),e.adjacency.has(s)||e.adjacency.set(s,[]),e.adjacency.get(i).push({to:s,kind:a,weight:c}),e.adjacency.get(s).push({to:i,kind:a,weight:c})};for(let i of Wi(St(t,"model/derived/structure"))){let s=Ir(Gi(i));if(s.ok){for(let a of s.value.nodes)e.nodes.set(a.key,a);for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}}for(let i of[...Wi(St(t,"model/derived/correlates")),St(t,"model/derived/relates.yaml")]){if(!Hi(i))continue;let s=So(Gi(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=St(t,"model/facts/events");if(Hi(n))for(let i of uc(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Et(Gi(St(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=ve(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,ve(l),"references",1)}for(let i of Wi(St(t,"model/facts/identity"))){let s=Eo(Gi(i));if(s.ok)for(let a of s.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=St(t,"model/facts/annotations");if(Hi(o)){for(let i of uc(o).sort())if(i.endsWith(".md"))try{let s=eh(St(o,i),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(s);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var rh=b(()=>{"use strict";K()});function oh(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function _S(t,e){if(t.size===0||e.size===0)return 0;let r=0;for(let n of t)e.has(n)&&r++;return r/(t.size+e.size-r)}function ih(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(f,m)=>{(i.get(f)??0)<m&&i.set(f,m)};(o.events.has(e)||o.adjacency.has(ve(e)))&&s(ve(e),nh);for(let f of`${r}
|
|
751
|
+
${n}`.match(PS)??[]){if(f===e)continue;let m=ve(f);(o.events.has(f)||o.adjacency.has(m))&&s(m,nh)}let a=new Map;for(let f of o.nodes.keys()){let m=Q(f);if(m?.level!=="code")continue;let g=m.path.slice(m.path.lastIndexOf("/")+1);for(let k of[m.path,g])a.has(k)||a.set(k,[]),a.get(k).push(f)}let c=`${r}
|
|
752
|
+
${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let f of c){let m=f.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!m||!m.includes("/")&&!m.includes("."))continue;let g=a.get(m)??[];g.length===1&&s(g[0],RS)}let l=new Map,u=(f,m)=>{let g=f.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==m?null:m)};for(let f of o.nodes.keys()){let m=Q(f);if(!m)continue;let g=m.path.slice(m.path.lastIndexOf("/")+1);m.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),f),m.level==="component"&&u(g,f)}for(let f of`${r}
|
|
753
|
+
${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let m=l.get(f.toLowerCase());m&&s(m,ES)}let p=oh(`${r}
|
|
754
|
+
${n}`),d=[];for(let[f,m]of o.events){if(f===e||!m.title)continue;let g=_S(p,oh(m.title));g>=CS&&d.push({key:ve(f),score:g})}return d.sort((f,m)=>m.score-f.score||(f.key<m.key?-1:1)).slice(0,AS).forEach(f=>s(f.key,IS)),i}var nh,RS,ES,IS,CS,AS,PS,sh=b(()=>{"use strict";K();nh=1,RS=.9,ES=.7,IS=.5,CS=.15,AS=3,PS=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function ah(t,e,r={}){let n=r.cutoff??Er.activationCutoff,o=r.topK??Er.topKPerNode,i=r.nodeCap??Er.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=ul[p.kind]??.3,f=l.activation*d*Math.min(p.weight,1);if(f<n)continue;let m=s.get(p.to);(!m||m.activation<f)&&(s.set(p.to,{activation:f,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:f}))}}return s}var ch=b(()=>{"use strict";K()});import{existsSync as lh,readFileSync as uh,readdirSync as jS}from"node:fs";import{join as pc}from"node:path";function dc(t){return Math.ceil(t.length/4)}function Yi(t,e){return[...t.entries()].filter(([r])=>e(r)).map(([r,n])=>({key:r,activation:n.activation,via:n.via})).sort((r,n)=>n.activation-r.activation||(r.key<n.key?-1:1))}function Ht(t){let e=Q(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function qi(t){if(!t.via)return"matched from the task text";let e=Ht(t.via.from);switch(t.via.kind){case"touched_by":return t.via.from.startsWith("task::")?`touched by ${e}`:`touches ${e}`;case"correlates":return`co-changes with ${e}`;case"relates":return`related to ${e} (shared files)`;case"references":return`referenced by ${e}`;case"contains":return`contained in ${e}`;default:return`linked to ${e}`}}function LS(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=pc(t,"adr");if(!lh(n))return null;let o=r.padStart(4,"0");for(let i of jS(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:uh(pc(n,i),"utf-8").trim()}}catch{return null}return null}function dh(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??Er.budgetTokens,a=[],c=0,l=R=>{let x=dc(R);return c+x>s?!1:(a.push(R),c+=x,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
|
|
755
|
+
`));let u=Yi(i,R=>R.startsWith("adr::")),p=!1;for(let R of u){let x=LS(n,Ht(R.key));if(!x)continue;let $=`${p?"":`
|
|
753
756
|
## Governing decisions
|
|
754
757
|
`}
|
|
755
|
-
### ${
|
|
758
|
+
### ${Ht(R.key)} (\`${x.file}\`, ${qi(R)})
|
|
756
759
|
|
|
757
760
|
${x.content}
|
|
758
|
-
`;if(!l($))break;p=!0}let d=
|
|
761
|
+
`;if(!l($))break;p=!0}let d=Yi(i,R=>o.nodes.get(R)?.entityId!==void 0).filter(R=>o.annotations.has(o.nodes.get(R.key).entityId)),f=!1;for(let R of d){let x=o.nodes.get(R.key).entityId,$=o.annotations.get(x),C=`${f?"":`
|
|
759
762
|
## Why the code is shaped this way (intent notes)
|
|
760
763
|
`}
|
|
761
|
-
### \`${
|
|
764
|
+
### \`${Ht(R.key)}\`
|
|
762
765
|
|
|
763
766
|
${$}
|
|
764
|
-
`;if(!l(
|
|
765
|
-
> ${
|
|
766
|
-
> _(full text: \`${U}\`)_`}catch{}let
|
|
767
|
+
`;if(!l(C))break;f=!0}let m=ve(e),g=Yi(i,R=>R.startsWith("task::")&&R!==m).slice(0,NS),k=!1;for(let R of g){let x=o.events.get(Ht(R.key));if(!x)continue;let $=[...x.files].filter(y=>!y.entityId||!o.orphanedEntities.has(y.entityId)).sort((y,L)=>(L.churn??0)-(y.churn??0)||(y.key<L.key?-1:1)).slice(0,3).map(y=>`\`${Ht(y.key)}\``).join(", "),C="",U=x.links?.solution??`tasks/${x.taskKey}/SOLUTION.md`,H=pc(n,U);if(lh(H))try{C=`
|
|
768
|
+
> ${uh(H,"utf-8").trim().slice(0,DS).replace(/\n+/g," ").trim()}\u2026
|
|
769
|
+
> _(full text: \`${U}\`)_`}catch{}let I=`${k?"":`
|
|
767
770
|
## Related past tasks
|
|
768
771
|
`}
|
|
769
|
-
- **${x.taskKey}**${x.title?` \u2014 ${x.title}`:""}${x.date?` (${x.date})`:""}, ${
|
|
770
|
-
`))+
|
|
771
|
-
`))}let T=h.filter(R=>!w(R)).slice(0,10);if(T.length>0){let R=["","## Possibly stale (verify before trusting)","","These entries reference files that no longer exist at their recorded","location. Useful as history, wrong as current fact.","",...T.map(x=>`- \`${
|
|
772
|
+
- **${x.taskKey}**${x.title?` \u2014 ${x.title}`:""}${x.date?` (${x.date})`:""}, ${qi(R)}. Files: ${$||"\u2014"}.${C}`;if(!l(I))break;k=!0}let w=R=>{let x=o.nodes.get(R.key)?.entityId;return!x||!o.orphanedEntities.has(x)},h=Yi(i,R=>R.startsWith("code:")),v=h.filter(w).slice(0,OS);if(v.length>0){let R=["","## Files likely involved",""];for(let x of v){let $=`- \`${Ht(x.key)}\` \u2014 ${qi(x)}`;if(c+dc(R.join(`
|
|
773
|
+
`))+dc($)>s)break;R.push($)}R.length>3&&l(R.join(`
|
|
774
|
+
`))}let T=h.filter(R=>!w(R)).slice(0,10);if(T.length>0){let R=["","## Possibly stale (verify before trusting)","","These entries reference files that no longer exist at their recorded","location. Useful as history, wrong as current fact.","",...T.map(x=>`- \`${Ht(x.key)}\` \u2014 ${qi(x)}`)];l(R.join(`
|
|
772
775
|
`))}return a.length<=1?null:a.join(`
|
|
773
776
|
`)+`
|
|
774
|
-
`}var
|
|
777
|
+
`}var NS,OS,DS,ph=b(()=>{"use strict";K();NS=5,OS=300,DS=400});var fh={};Rn(fh,{assembleContextPack:()=>FS});import{existsSync as MS,readFileSync as US}from"node:fs";import{join as BS}from"node:path";function FS(t){let e=th(t.contextDir);if(e.empty)return null;let r="",n=BS(t.contextDir,`tasks/${t.taskKey}/task.md`);if(MS(n))try{r=US(n,"utf-8")}catch{r=""}let o=ih({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=ah(e,o);return dh({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var mh=b(()=>{"use strict";rh();sh();ch();ph()});import{mkdirSync as gh,readFileSync as hh,readdirSync as KS,writeFileSync as yh}from"node:fs";import{homedir as GS}from"node:os";import{dirname as HS,join as Wt}from"node:path";function YS(t){let e=Buffer.from(t,"utf-8");if(e.length<=Vi)return t;let r=Math.floor(Vi/4),n=Vi-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}
|
|
775
778
|
|
|
776
|
-
\u2026 [${s} bytes elided \u2014 log capped at ${
|
|
779
|
+
\u2026 [${s} bytes elided \u2014 log capped at ${Vi} bytes for upload] \u2026
|
|
777
780
|
|
|
778
|
-
${i}`}function
|
|
781
|
+
${i}`}function qS(){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 ao(t={}){Li();let e=Ee(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=Zm(t.profile,e.sandboxId,!!q("SANDBOX_CONFIG")),s=Wt(GS(),".codepipe","logs"),a=Uo("SANDBOX_LOG",i,s);if(a.enabled){let I=new Dr(a);Bo(I),console.log(`[log] file logging \u2192 ${I.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Le} (protocol ${ot})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=dg(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=hg();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new en(e.hubUrl,e.token),p=!1,d=new AbortController,f=new Map,m=null,g=null,k=!1,w=()=>{let I=u.openControlSocket();return m=I,I.on("open",()=>{console.log("[ws] connected");let y={type:"sandbox_hello",platformVersion:Le,protocolVersion:ot};I.send(JSON.stringify(y))}),I.on("message",y=>{let L=y.toString("utf-8"),N=null;try{let F=JSON.parse(L);F&&typeof F=="object"&&(N=F)}catch{}if(N&&N.type==="hello"){let F=N;g=$o(F.protocolVersion);let A=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${F.platformVersion} (protocol ${F.protocolVersion}) \u2014 ${A}`),g&&(k=!1);return}if(N&&N.type==="pause_job"){let F=typeof N.jobId=="string"?N.jobId:"",A=F?f.get(F):void 0;A?(console.warn(`[ws] pause_job ${F} \u2014 aborting agent`),A.paused=!0,A.abort.abort()):console.log(`[ws] pause_job ${F} \u2014 not a running job, ignoring`),F&&I.send(JSON.stringify({type:"job_paused",jobId:F}));return}if(N&&(N.type==="chat_user_message"||N.type==="chat_finalize")){let F=typeof N.jobId=="string"?N.jobId:"",A=F?f.get(F):void 0;if(A?.chatInbox)if(N.type==="chat_user_message"){let _=typeof N.text=="string"?N.text:"";_.trim()&&A.chatInbox.push({kind:"user",text:_})}else A.chatInbox.finalize();else console.log(`[ws] ${String(N.type)} ${F} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${L}`)}),I.on("close",(y,L)=>{console.log(`[ws] closed code=${y} reason=${L?.toString()||""}`),m===I&&(m=null),!p&&setTimeout(w,2e3)}),I.on("error",y=>console.warn(`[ws] error: ${y.message}`)),I},h=w(),v=async I=>{for(;!p;){if(g===!1){k||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Le}, protocol ${ot}) \u2014 not claiming jobs until versions align.`),k=!0),await new Promise(y=>setTimeout(y,5e3));continue}try{let y=await u.claim(d.signal,I);if(y.status===204)continue;if(y.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(!y.ok){console.warn(`[claim:${I}] ${y.status} \u2014 backoff 5s`),await new Promise(N=>setTimeout(N,5e3));continue}let L=await y.json();await T(u,L)}catch(y){if(d.signal.aborted)break;let L=y instanceof Error?y.message:String(y);console.warn(`[claim:${I}] error: ${L} \u2014 backoff 5s`),await new Promise(N=>setTimeout(N,5e3))}}};async function T(I,y){let L={abort:new AbortController,paused:!1};y.role==="chat"&&(L.chatInbox=qS()),f.set(y.jobId,L);let N=!1,F=null,A=null,_=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),O=async()=>{try{await I.heartbeat(y.jobId)==="claim_lost"&&(N=!0,console.warn(`[job] ${y.jobId} claim lost \u2014 HUB sweeper took it`))}catch(X){let re=X instanceof Error?X.message:String(X);console.warn(`[job] ${y.jobId} heartbeat error: ${re}`)}};O();let W=setInterval(()=>{O()},_),j=new Date().toISOString();console.log(`[job] ${y.jobId} claimed \u2014 role=${y.role} task=${y.taskId} phase=${y.phase}`),console.log(`[job] ${y.jobId} prompt (${y.prompt.length} chars):`),console.log(x(y.prompt," \u2502 "));let S=[],E=null,z=400,ie=25,Qt=500,D=()=>{if(E&&(clearTimeout(E),E=null),S.length===0)return;let X=S.splice(0,S.length),re=m;if(!re||re.readyState!==re.OPEN)return;let gt={type:"agent_activity",jobId:y.jobId,taskId:y.taskId,projectId:y.projectId,role:y.role,phase:y.phase,events:X};try{re.send(JSON.stringify(gt))}catch{}},le=X=>{S.push(X),S.length>Qt&&S.shift(),S.length>=ie?D():E||(E=setTimeout(D,z))},he=y.role==="analysis"&&y.taskId.startsWith("draft::")?y.taskId.slice(7):null,He=new Set,Rt=null;try{if(!c){N||await I.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:j,finishedAt:new Date().toISOString()});return}if(!pg(o,y.provider??null)){N||await I.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${y.provider??"claude"}"`},startedAt:j,finishedAt:new Date().toISOString()});return}let X=Jg(y.jobId);console.log(`[job] ${y.jobId} workspace=${X.dir}`);let re=R(y,r);F=re.gitCreds,A=re.contextGitCreds;let gt=F?.env,Gc=re.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:re.claudeOauthToken}:void 0,ht=[],Zt=null,ss=null;try{let M=y.role==="build"?"clone":"worktree";ht=await Lg(X.dir,y.projectId,y.projectRepos,M,gt,n);let B=await Mg(X.dir,y.projectId,y.contextRepo,"worktree",gt,n);ss=B,Zt=B?.workspacePath??null}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${y.jobId} materialize failed: ${B}`),N||await I.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${B}`},startedAt:j,finishedAt:new Date().toISOString()}),X.dispose();return}let Hc=async()=>{if(!y.deliveries||y.deliveries.length===0)return[];let M=y.contextRepo?.cloneUrl;if(!M||!gt)throw new Error(M?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let B=[];for(let Z of y.deliveries){let J=ht.find(ye=>ye.name===Z.name);if(J){if(y.role==="implement"&&Z.baseSha&&Z.baseSha!==J.baseSha){let ye=await Ng(J,Z.deliveryRef,Z.deliverySha,Z.baseSha,M,gt);console.log(`[job] ${y.jobId} ${J.name}: base moved ${Z.baseSha.slice(0,10)} \u2192 ${J.baseSha.slice(0,10)} \u2014 re-applied delivery ${Z.deliverySha.slice(0,10)} (${ye.length} conflicted file(s))`),ye.length>0&&B.push(`- **${J.name}**:`,...ye.map(xn=>` - \`${xn}\``));continue}await jg(J,Z.deliveryRef,Z.deliverySha,M,gt),console.log(`[job] ${y.jobId} ${J.name}: checked out delivery ${Z.deliverySha.slice(0,10)} for ${y.role}`)}}return B},as=[];if(y.role==="build"||y.role==="implement"||y.role==="code-review")try{as=await Hc()}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${y.jobId} delivery checkout failed: ${B}`),N||await I.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${B}`},startedAt:j,finishedAt:new Date().toISOString()}),X.dispose();return}let cs=y.role==="resolve-conflict"?y.metadata?.taskBranchByRepo??{}:{},Wc="";if(y.role==="resolve-conflict"){if(!ht.some(M=>cs[M.name])){let M="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] ${y.jobId} ${M}`),N||await I.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:M},startedAt:j,finishedAt:new Date().toISOString()}),X.dispose();return}try{let M=[];for(let B of ht){let Z=cs[B.name];if(!Z)continue;let J=await cc(B,Z,gt);console.log(`[job] ${y.jobId} ${B.name}: merged ${Z} into ${B.ref} \u2014 ${J.length} conflicted file(s)`),J.length>0?M.push(`- **${B.name}**:`,...J.map(ye=>` - \`${ye}\``)):M.push(`- **${B.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Wc=`
|
|
779
782
|
|
|
780
783
|
## Conflicts to resolve
|
|
781
784
|
|
|
782
785
|
`+(M.length>0?M.join(`
|
|
783
786
|
`):"(no task branches to merge)")+`
|
|
784
|
-
`}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${y.jobId} conflict merge failed: ${B}`),
|
|
787
|
+
`}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${y.jobId} conflict merge failed: ${B}`),N||await I.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${B}`},startedAt:j,finishedAt:new Date().toISOString()}),X.dispose();return}}if(y.contextPack&&Zt)try{let{assembleContextPack:M}=await Promise.resolve().then(()=>(mh(),fh)),B=M({contextDir:Zt,taskKey:String(y.metadata?.trackerIssueKey??y.taskId.split(":")[1]??""),title:String(y.metadata?.taskTitle??"")});B?(gh(Wt(X.dir,"meta"),{recursive:!0}),yh(Wt(X.dir,"meta","context-pack.md"),B),console.log(`[job] ${y.jobId} context pack: ${B.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${y.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(M){let B=M instanceof Error?M.message:String(M);console.warn(`[job] ${y.jobId} context pack failed (non-fatal): ${B}`)}let nk=as.length>0?`
|
|
785
788
|
|
|
786
789
|
## Base branch moved \u2014 conflicts to resolve
|
|
787
790
|
|
|
788
791
|
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:
|
|
789
792
|
|
|
790
|
-
`+
|
|
793
|
+
`+as.join(`
|
|
791
794
|
`)+`
|
|
792
|
-
`:"",
|
|
793
|
-
`).map(
|
|
794
|
-
`)}function $(
|
|
795
|
-
[${
|
|
796
|
-
${e}`);let r=await
|
|
797
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=jS(await PS({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||Ze.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):(Ze.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 ih,sh=b(()=>{"use strict";Fo();Dr();ie();Ds();ih={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:DS,promptManual:LS,validate:jt}});function ah(t){return ih}async function ch(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var lh=b(()=>{"use strict";sh()});async function ln(t,e,r){return e.host==="github"?US(t,e,r):e.host==="gitlab"?YS(t,e,r):VS(t,e,r)}async function uh(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 Ht(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await dh(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 Gt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await ph(e.gitlabToken,t):o}}return e.bitbucket?(await cn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await fh(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 dh(t,e){let r=!1;try{r=(await Ht(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 ph(t,e){let r=!1;try{r=(await Gt(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 fh(t,e){let r=!1;try{r=(await cn(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 Ht(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(MS+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 US(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 BS(n,e,r),i=await KS(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Kr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await GS(n,o.owner,o.name,a.path,i)||await HS(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 BS(t,e,r){let n=await Ht(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 dh(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await FS(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 Ht(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 FS(t,e){let{status:r,data:n}=await Ht(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function KS(t,e,r){let{data:n}=await Ht(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function GS(t,e,r,n,o){let{status:i,data:s}=await Ht(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function HS(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 Ht(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Gt(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(WS+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 YS(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 Gt(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 ph(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Gt(n,"GET","/user"),d={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 m=await Gt(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(m.status===404||!m.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`);d.namespace_id=m.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let f=await Gt(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Kr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await Gt(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let m of f)l.add(m.path);if(f.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Gt(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):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 cn(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(qS+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 VS(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 cn(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 fh(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 cn(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=Kr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await cn(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 f of l)p.set(f.path,f.content);if((await cn(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 u=i.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var MS,WS,qS,Bi=b(()=>{"use strict";pr();MS="https://api.github.com";WS="https://gitlab.com/api/v4";qS="https://api.bitbucket.org/2.0"});function Fe(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=zS[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 zS,Fi=b(()=>{"use strict";zS={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as JS}from"node:crypto";import{existsSync as mh,mkdirSync as XS,readFileSync as gh,readdirSync as QS,rmSync as Ki,writeFileSync as ZS}from"node:fs";import{homedir as eT}from"node:os";import{dirname as tT,join as rc}from"node:path";function hh(){return rc(eT(),".codepipe","init-drafts")}function nc(t){let e=JS("sha256").update(t).digest("hex").slice(0,16);return rc(hh(),`${e}.json`)}function yh(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=rT)}function kh(t){let e=nc(t);if(!mh(e))return null;try{let r=JSON.parse(gh(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:yh(r.savedAt)?(Ki(e,{force:!0}),null):r}catch{return null}}function oc(t){Ki(nc(t),{force:!0})}function wh(){let t=hh();if(mh(t))for(let e of QS(t)){let r=rc(t,e);try{let n=JSON.parse(gh(r,"utf-8"));yh(n.savedAt)&&Ki(r,{force:!0})}catch{Ki(r,{force:!0})}}}var rT,un,bh=b(()=>{"use strict";rT=24*60*60*1e3;un=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(){oc(this.cwd)}persist(){let e=nc(this.cwd);XS(tT(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};ZS(e,JSON.stringify(r,null,2)+`
|
|
798
|
-
`,{mode:384})}}});function
|
|
799
|
-
`).map(n=>n.trim()).filter(Boolean);return
|
|
800
|
-
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`),
|
|
801
|
-
`))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function
|
|
795
|
+
`:"",ok=C($(y.prompt,ht,Zt),Zt,y.taskId)+Wc+nk,ls=[...ht.map(M=>M.workspacePath),...Zt?[Zt]:[]];ls.length>0&&console.log(`[job] ${y.jobId} --add-dir: ${ls.join(", ")}`),he&&(Rt=setInterval(()=>{let B=m;if(!B||B.readyState!==B.OPEN)return;let Z;try{Z=KS(Wt(X.dir,"drafts")).filter(J=>J.endsWith(".json")).sort()}catch{return}for(let J of Z){if(He.has(J))continue;if(He.size>=nu)break;let ye;try{let We=JSON.parse(hh(Wt(X.dir,"drafts",J),"utf-8")),xr=typeof We.localRef=="string"?We.localRef:"",wo=typeof We.title=="string"?We.title:"",us=typeof We.body=="string"?We.body:"";if(!xr||!wo)continue;ye={localRef:xr,title:wo,body:us,...We.isEpic===!0?{isEpic:!0}:{},...Array.isArray(We.links)?{links:We.links}:{}}}catch{continue}He.add(J);let xn={type:"child_draft",jobId:y.jobId,projectId:y.projectId,draftId:he,child:ye};try{B.send(JSON.stringify(xn))}catch{}}},1500));try{let M={workspaceDir:X.dir,role:y.role,prompt:ok,addDirs:ls,metadata:y.metadata??{},...y.model?{model:y.model}:{},...Gc?{env:Gc}:{},signal:L.abort.signal,onActivity:le},B=L.chatInbox?await c.run({...M,interactive:{inbox:L.chatInbox.iterable}}):await kg(c,M,{jobId:y.jobId,policy:l,onBeforeRetry:async()=>{X.clean();for(let se of ht)try{await Cg(se);let ke=cs[se.name];y.role==="resolve-conflict"&&ke&&await cc(se,ke,gt)}catch(ke){let Sn=ke instanceof Error?ke.message:String(ke);console.warn(`[job] ${y.jobId} worktree reset failed (${se.name}): ${Sn}`)}try{await Hc()}catch(se){let ke=se instanceof Error?se.message:String(se);console.warn(`[job] ${y.jobId} delivery re-checkout failed: ${ke}`)}},aborted:()=>N||L.paused}),Z=[];if(WS.has(y.role)&&ht.length>0){let se=y.metadata??{},ke=typeof se.commitMessage=="string"?se.commitMessage:`${y.taskId}: changes`,Sn=y.contextRepo?.cloneUrl,qc=A?.env;if(!Sn||!qc)throw new Error("delivery requested but "+(Sn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let ik=y.taskId.includes(":")?y.taskId.slice(y.taskId.indexOf(":")+1):y.taskId;for(let yt of ht){let Tn=await Ag(yt,ke);if(!Tn){console.log(`[job] ${y.jobId} ${yt.name}: no changes \u2014 no delivery`);continue}let ds=`codepipe/deliveries/${ik}/${y.jobId}/${yt.name}`;await Pg(yt,Tn,ds,Sn,qc),Z.push({name:yt.name,deliveryRef:ds,deliverySha:Tn,baseSha:yt.baseSha}),console.log(`[job] ${y.jobId} ${yt.name}: delivered ${Tn.slice(0,10)} \u2192 ${ds}`);let Vc=await _g(yt,Tn);if(Vc.trim().length>0){let sk=Wt("display",`${yt.name}.diff`),zc=Wt(X.dir,sk);gh(HS(zc),{recursive:!0}),yh(zc,Vc)}}}if(y.role==="resolve-conflict"&&Z.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 J;y.role==="build"&&(J=Fg(X.dir),console.log(`[job] ${y.jobId} build verdict: ok=${J.ok}`+(J.failedStep?` failedStep=${J.failedStep}`:"")));let ye;y.role==="code-review"&&(ye=Hg(X.dir),console.log(`[job] ${y.jobId} review verdict: approved=${ye.approved}`));let xn=B.artifactPaths.length>0?B.artifactPaths:X.listFiles(),We=Array.from(new Set(xn)),xr;if(ss)try{let se=y.role==="index"?["adr/SOURCES.md"]:y.role==="backfill"?["adr"]:[],ke=await Ug(ss,se);ke.length>0&&(xr=ke,console.log(`[job] ${y.jobId} captured ${ke.length} knowledge file(s) for Context Repo`))}catch(se){let ke=se instanceof Error?se.message:String(se);console.warn(`[job] ${y.jobId} knowledge capture failed (non-fatal): ${ke}`)}let{artifacts:wo,omitted:us,dropped:Yc}=qg(X.dir,We);for(let se of us)console.warn(`[job] ${y.jobId} artifact ${se.path} (${se.bytes} bytes) exceeded upload budget \u2014 content omitted`);Yc.length>0&&console.warn(`[job] ${y.jobId} artifact listing truncated: ${Yc.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let bo={jobId:y.jobId,status:"succeeded",artifacts:wo,...xr?{contextWrites:xr}:{},...Z.length>0?{deliveries:Z}:{},log:YS(B.log),startedAt:j,finishedAt:new Date().toISOString(),usage:B.usage,...B.rateLimit?{rateLimit:B.rateLimit}:{},...J?{build:J}:{},...ye?{review:ye}:{}};if(N||L.paused)console.warn(`[job] ${y.jobId} skipping result upload \u2014 ${L.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await I.submitResult(bo),console.log(`[job] ${y.jobId} done \u2014 uploaded ${bo.artifacts.length} artifact(s):`);for(let se of bo.artifacts){let ke=Buffer.from(se.contentBase64,"base64").length;console.log(` \xB7 ${se.path} (${ke} bytes)`)}bo.artifacts.length===0&&console.warn(`[job] ${y.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(M){let B=M instanceof Error?M.message:String(M);if(L.paused)console.log(`[job] ${y.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(N)console.warn(`[job] ${y.jobId} failed after claim lost (${B}) \u2014 skipping result upload`);else{let Z=yg(M),J=M instanceof Gt,ye=M instanceof xt;console.warn(Z?`[job] ${y.jobId} failed: ${B} (Claude auth \u2014 token invalid/expired)`:J?`[job] ${y.jobId} failed: ${B} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:ye?`[job] ${y.jobId} failed: ${B} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${y.jobId} failed: ${B}`),await I.submitResult({jobId:y.jobId,status:"failed",artifacts:[],error:{message:B},startedAt:j,finishedAt:new Date().toISOString(),...Z?{authError:!0}:{},...J?{buildInconclusive:!0}:{},...ye?{reviewInconclusive:!0}:{}})}}finally{X.dispose()}}finally{clearInterval(W),Rt&&clearInterval(Rt),D(),L.chatInbox?.close(),f.delete(y.jobId),F?.cleanup(),A?.cleanup()}}function R(I,y){if(!I.credBundle)return{gitCreds:null,contextGitCreds:null};if(!y)return console.warn(`[job] ${I.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let L;try{L=JSON.parse(Wr(y,I.credBundle).toString("utf-8"))}catch(_){return console.warn(`[job] ${I.jobId} failed to open credBundle: ${_ instanceof Error?_.message:String(_)}`),{gitCreds:null,contextGitCreds:null}}let N=sc(L);N&&console.log(`[job] ${I.jobId} cred bundle opened \u2014 git creds configured`);let F=vg(L,I.contextRepo.cloneUrl),A={gitCreds:N,contextGitCreds:F};return L.claudeOauthToken&&(A.claudeOauthToken=L.claudeOauthToken),A}function x(I,y){return I.split(`
|
|
796
|
+
`).map(L=>y+L).join(`
|
|
797
|
+
`)}function $(I,y,L){let N=y[0]?.workspacePath??"";return I.replace(/\{\{codeDir\}\}/g,N).replace(/\{\{codeRoot\}\}/g,N?N.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,L??"")}function C(I,y,L){let N=I,F=L.includes("::")?"":L.split(":",2)[1]??"",A=_=>{if(!y||!F)return"";try{return hh(Wt(y,"tasks",F,_),"utf-8").trim()}catch{return""}};if(N.includes("{{solutionMd}}")){let _=A("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";N=N.replace(/\{\{solutionMd\}\}/g,()=>_)}if(N.includes("{{taskDescription}}")){let _=A("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";N=N.replace(/\{\{taskDescription\}\}/g,()=>_)}return N}let U=I=>{if(p)return;p=!0,console.log(`
|
|
798
|
+
[${I}] shutting down`),d.abort();let y=[...f.keys()];for(let F of f.values())F.abort.abort();let L=new AbortController,N=setTimeout(()=>L.abort(),3e3);(async()=>(await Promise.all(y.map(async F=>{try{await u.releaseJob(F,`sandbox ${I}`,L.signal),console.log(`[${I}] released job ${F}`)}catch(A){let _=A instanceof Error?A.message:String(A);console.warn(`[${I}] release failed: ${_} (sweeper will reclaim)`)}})),clearTimeout(N),h.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>U("SIGINT")),process.on("SIGTERM",()=>U("SIGTERM"));let H=[v("implementation")];e.planningLane!==!1?H.push(v("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(H)}var Vi,WS,kh=b(()=>{"use strict";K();Ke();Ps();fg();wg();Ae();Mi();xg();tc();Bg();Kg();Wg();Vg();Zg();Vi=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),WS=new Set(["implement","resolve-conflict"])});var dn=b(()=>{"use strict";tg();kh();Mi()});import{cancel as VS,isCancel as bh,log as rt,password as zS,text as XS}from"@clack/prompts";function JS(t){return bh(t)&&(VS("aborted"),process.exit(1)),typeof t=="string"?t:""}function QS(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function ZS(t){let e=Gs({redirectUri:Ks,challenge:t.challenge,state:t.state});rt.message(`Open this URL, approve the access, and paste the code shown:
|
|
799
|
+
${e}`);let r=await XS({message:"Authorization code \u2014 blank to skip"});if(bh(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=hd(r,t.state);return await Hs({code:n,verifier:t.verifier,state:t.state,redirectUri:Ks})}catch(n){return rt.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function eT(t){if(Cs()?.claude?.oauthToken&&!t.farm)return rt.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;rt.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=Wo(),n;try{n=await yd({...r,openUrl:ar,log:i=>rt.message(i)})}catch(i){rt.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await ZS(r);if(s===null)return null;n=s}let o=await Dt(n.oauthToken);return o==="invalid"?(rt.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(rt.success(`Claude: logged in \u2014 ${QS(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function tT(t){rt.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?`
|
|
800
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=JS(await zS({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||rt.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):(rt.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 $h,vh=b(()=>{"use strict";Yo();Mr();ue();Ys();$h={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:eT,promptManual:tT,validate:Dt}});function xh(t){return $h}async function Sh(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Th=b(()=>{"use strict";vh()});async function fn(t,e,r){return e.host==="github"?nT(t,e,r):e.host==="gitlab"?uT(t,e,r):pT(t,e,r)}async function Rh(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 qt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Eh(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 Yt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ih(e.gitlabToken,t):o}}return e.bitbucket?(await pn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ch(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 Eh(t,e){let r=!1;try{r=(await qt(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 Ih(t,e){let r=!1;try{r=(await Yt(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 Ch(t,e){let r=!1;try{r=(await pn(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 qt(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(rT+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 nT(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 oT(n,e,r),i=await sT(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Hr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await aT(n,o.owner,o.name,a.path,i)||await cT(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 oT(t,e,r){let n=await qt(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 Eh(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await iT(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 qt(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 iT(t,e){let{status:r,data:n}=await qt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function sT(t,e,r){let{data:n}=await qt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function aT(t,e,r,n,o){let{status:i,data:s}=await qt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function cT(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 qt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Yt(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(lT+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 uT(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 Yt(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 Ih(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Yt(n,"GET","/user"),d={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 m=await Yt(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(m.status===404||!m.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`);d.namespace_id=m.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let f=await Yt(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Hr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await Yt(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let m of f)l.add(m.path);if(f.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Yt(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):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 pn(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(dT+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 pT(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 pn(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 Ch(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 pn(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=Hr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await pn(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 f of l)p.set(f.path,f.content);if((await pn(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 u=i.links?.clone?.find(p=>p.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var rT,lT,dT,zi=b(()=>{"use strict";hr();rT="https://api.github.com";lT="https://gitlab.com/api/v4";dT="https://api.bitbucket.org/2.0"});function Ge(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=fT[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 fT,Xi=b(()=>{"use strict";fT={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as mT}from"node:crypto";import{existsSync as Ah,mkdirSync as gT,readFileSync as Ph,readdirSync as hT,rmSync as Ji,writeFileSync as yT}from"node:fs";import{homedir as kT}from"node:os";import{dirname as wT,join as fc}from"node:path";function _h(){return fc(kT(),".codepipe","init-drafts")}function mc(t){let e=mT("sha256").update(t).digest("hex").slice(0,16);return fc(_h(),`${e}.json`)}function jh(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=bT)}function Nh(t){let e=mc(t);if(!Ah(e))return null;try{let r=JSON.parse(Ph(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:jh(r.savedAt)?(Ji(e,{force:!0}),null):r}catch{return null}}function gc(t){Ji(mc(t),{force:!0})}function Oh(){let t=_h();if(Ah(t))for(let e of hT(t)){let r=fc(t,e);try{let n=JSON.parse(Ph(r,"utf-8"));jh(n.savedAt)&&Ji(r,{force:!0})}catch{Ji(r,{force:!0})}}}var bT,mn,Dh=b(()=>{"use strict";bT=24*60*60*1e3;mn=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(){gc(this.cwd)}persist(){let e=mc(this.cwd);gT(wT(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};yT(e,JSON.stringify(r,null,2)+`
|
|
801
|
+
`,{mode:384})}}});function Lh(t){let e=[],r=[];return t.localClones&&(e.push({value:"map",label:"Project map from git history",hint:"local, a few seconds \u2014 a graph of files, tasks and their connections for the AI agent"}),r.push("map")),e.push(t.indexExists?{value:"index",label:"Re-index the context (an index already exists)",hint:"background job; keeps nothing if skipped"}:{value:"index",label:"Context index \u2014 knowledge and docs map",hint:"background job, recommended on first run"}),t.indexExists||r.push("index"),!t.indexExists&&t.reposNonEmpty&&(e.push({value:"backfill",label:"Reconstruct architecture decisions from the existing code",hint:"deep one-off AI analysis \u2014 proposes decision drafts you review before they become canonical"}),r.push("backfill")),{message:"Analyze the project? Pick what to run (space to toggle, enter to confirm):",options:e,initialValues:r,reindex:t.indexExists}}async function Mh(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 Uh=b(()=>{"use strict"});import{existsSync as $T}from"node:fs";import{join as vT}from"node:path";import{simpleGit as xT}from"simple-git";function ET(t){let e=t.split("/");return e[e.length-1]??t}function Bh(t){if(t.filter(r=>!TT.test(ET(r))).length>ST)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(RT.has(n))return!0}return!1}async function IT(t){try{let r=(await xT(t).raw(["ls-files"])).split(`
|
|
802
|
+
`).map(n=>n.trim()).filter(Boolean);return Bh(r)}catch{return!1}}async function CT(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)?Bh(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Fh(t,e){for(let r of t)try{let n=e.localRoot!=null?vT(e.localRoot,r.mountAs??r.name):null;if(n&&$T(n)?await IT(n):await CT(r,e.tokens))return!0}catch{}return!1}var ST,TT,RT,Kh=b(()=>{"use strict";ST=3,TT=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,RT=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Gh}from"node:fs";import{join as Hh}from"node:path";import{simpleGit as Wh}from"simple-git";async function lo(t,e,r={}){let n=r.log??AT,o=[];for(let i of e){let s=Hh(t,i.mountAs),a=au(i);if(!Gh(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 Wh().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=co(u instanceof Error?u.message:String(u));n.warn(`clone failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}continue}if(!Gh(Hh(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=Wh(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!PT(l,a)){n.warn(`${i.mountAs}/ origin (${co(l)||"none"}) != expected (${co(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:co(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(u){let p=co(u instanceof Error?u.message:String(u));n.warn(`fetch failed for ${i.mountAs}: ${p}`),o.push({mountAs:i.mountAs,status:"error",detail:p})}}return o}function PT(t,e){return Yh(t)===Yh(e)}function Yh(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function co(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function qh(t={}){let e=$e();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 lo(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 AT,Qi=b(()=>{"use strict";lt();AT={info:t=>console.log(t),warn:t=>console.warn(t)}});import{spawn as zh}from"node:child_process";import{existsSync as Vh}from"node:fs";import{homedir as _T,hostname as jT}from"node:os";import{join as Zi}from"node:path";async function NT(t,e,r){let n=Ee(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${tt(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 Rd(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 ${tt(e)} still holds its token.
|
|
803
|
+
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`),Tu(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function OT(t,e,r){let n=Ee(e)!==null;if(!await NT(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 zo(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof G&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof G&&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 G?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 kr({hub:t.hubUrl,token:o,name:r.name??`${jT()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function DT(t,e){let r=Ee(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=Pe(r.sealPublicKey);if(!Y(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Lo(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 hc(t,e,r){await OT(t,e,r),DT(t.projectId,e)}function LT(t){return[...t?["--profile",t]:[],"worker","start"]}function MT(t){let e={...t};for(let r of As)delete e[r];return e}function yc(t){let e=zh(process.execPath,[t.entry,...LT(t.profile)],{stdio:["ignore","pipe","pipe"],env:MT(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
|
|
804
|
+
`))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function UT(t,e){let r=process.cwd(),n=Zi(r,ct);if(No(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Vh(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 te(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await bc(r);if(!su(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=Y(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Di({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=Zi(_T(),".codepipe",e?Zi("profiles",e,"context-config"):"context-config");if(ni(c.contextDir,l,a),!Vh(Zi(c.contextDir,"project.yaml"))){Kr(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Kn(c.contextDir,pt(u,!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 kc(t){let{cfg:e,profile:r}=Do(t.profile);await UT(e,r),await hc(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(f,m)=>{let g=k=>w=>{for(let h of w.toString("utf-8").split(`
|
|
802
805
|
`))h.length>0&&k.write(`${m} ${h}
|
|
803
|
-
`)};f.stdout?.on("data",g(process.stdout)),f.stderr?.on("data",g(process.stderr))},i=(f,m)=>{let g=
|
|
806
|
+
`)};f.stdout?.on("data",g(process.stdout)),f.stderr?.on("data",g(process.stderr))},i=(f,m)=>{let g=zh(process.execPath,[n,...m],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,f),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=yc({entry:n,profile:r,onLine:f=>process.stdout.write(`[worker] ${f}
|
|
804
807
|
`)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=f=>{if(!l){l=!0,console.log(`
|
|
805
|
-
[up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${m} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:f,child:m})=>new Promise(g=>{m.on("exit",(k,w)=>g({name:f,code:k??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var
|
|
808
|
+
[up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${m} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:f,child:m})=>new Promise(g=>{m.on("exit",(k,w)=>g({name:f,code:k??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var wc=b(()=>{"use strict";Ke();dn();Ne();bt();Qa();hr();xe();ue();lt();uo()});var oy={};Rn(oy,{replCommand:()=>Sc});import{existsSync as ty,mkdirSync as BT,readFileSync as FT,writeFileSync as KT}from"node:fs";import{homedir as GT}from"node:os";import{dirname as HT,join as ry}from"node:path";import*as gn from"node:readline";async function Sc(t={}){let e=$e();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=Y(e.spec.projectId);r||(console.error(`no secrets for project ${e.spec.projectId} at ~/.codepipe/secrets/${e.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),Nn(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let n=mr(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
|
|
806
809
|
\u26A0 unfinished local apply: ${o.map(a=>`${a} (${n[a].repos.map(c=>c.mountAs).join(", ")})`).join("; ")}
|
|
807
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=
|
|
808
|
-
`))}async function
|
|
809
|
-
`)}`:" (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}
|
|
810
|
-
`),t.unread+=1,
|
|
810
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=gn.createInterface({input:process.stdin,output:process.stdout,completer:WT,history:dR(),removeHistoryDuplicates:!0}),s={ws:e,secrets:r,connection:"connecting",rl:i,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Md(a=>zt(s,a)),s.daemon=Ni({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>zt(s,a),warn:a=>zt(s,a)},onEvent:a=>iR(s,a),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos.map(a=>({name:a.name,mountAs:a.mountAs,defaultBranch:a.defaultBranch}))}});try{let a={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await hc(a,t.profile,{profile:t.profile});let c=process.argv[1];if(!c)throw new Error("cannot resolve the codepipe entry script for the worker process");let l=yc({entry:c,profile:t.profile,onLine:u=>zt(s,`[worker] ${u}`)});l.on("exit",(u,p)=>{s.workerExited=!0,!xc&&Vt(s,`[worker] exited (code ${u??(p?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),s.workerChild=l,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(a){console.warn(`[worker] could not start the embedded worker (${a instanceof Error?a.message:String(a)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}vc(s),i.prompt(),i.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await YT(s,c)){ey(s);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}s.unread=0,vc(s),i.prompt()}),i.on("close",()=>{ey(s)})}function WT(t){let e=Xh.filter(r=>r.startsWith(t));return[e.length?e:Xh,t]}async function YT(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return qT(),!1;case"/status":return await VT(t),!1;case"/tasks":return await zT(t,n),!1;case"/task":return await XT(t,n),!1;case"/sync":return await JT(t),!1;case"/logs":return sR(t,n),!1;case"/monitor":return aR(t),!1;case"/apply":return await Qh(t,n,"apply"),!1;case"/unstash":return await Qh(t,n,"unstash"),!1;case"/applied":return await QT(t,n),!1;case"/abort":return await ZT(t,n),!1;case"/approve":return await Zh(t,n,"approve"),!1;case"/merge":return await Zh(t,n,"merge"),!1;case"/login":return tR(t,n),!1;case"/secret":return rR(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function qT(){console.log(["/help show this list","/status connection, project, embedded worker, 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/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker 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 the worker, exit"].join(`
|
|
811
|
+
`))}async function VT(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`);let r=t.workerChild?t.workerExited?"exited \u2014 agent jobs will not run (restart codepipe)":`running (pid ${t.workerChild.pid})`:"not started \u2014 agent jobs will not run";console.log(` worker: ${r}`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let n of t.ws.spec.repos){let o=ty(ry(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function zT(t,e){let r=cR(e,"--phase");try{let n=await Ad(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){po(n)}}async function XT(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Pd(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){po(n)}}async function JT(t){let e=await lo(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 Qh(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await zd(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function QT(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=mr(t.ws.contextDir)[r],i=lR(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("="),u,p;if(l>0?(u=c.slice(0,l),p=c.slice(l+1)):(p=c,u=o?.repos.length===1?eR(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${p}`);return}let d=p.match(/(?:pull|pull-requests)\/(\d+)/);if(!d){console.log(` cannot parse PR number from ${p}`);return}a.push({repoName:u,url:p,number:Number(d[1])})}try{let c=await _d(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Qs(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){po(c)}}async function Zh(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Nd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){po(o)}}async function ZT(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=uR(e,"--reason")||"local apply aborted";await Jd(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await jd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){po(o)}}function eR(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function tR(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},ee(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 rR(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(`
|
|
812
|
+
`)}`:" (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}nR(t.secrets,n,i),ee(t.secrets),Nn(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}oR(t.secrets,n),ee(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function nR(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 oR(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 iR(t,e){switch(e.kind){case"connected":t.connection="connecting",zt(t,"[hub] connected");break;case"registered":t.connection="registered",zt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Vt(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",zt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Vt(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Vt(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?zt(t,`[hub] action ${e.actionType} done`):Vt(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?Vt(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):Vt(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function zt(t,e){t.logBuffer.push(e),t.logBuffer.length>ny&&t.logBuffer.shift(),t.follow&&Vt(t,e)}function sR(t,e){let r=e[0];if(r==="follow"||r==="on"){$c(t,!0);return}if(r==="off"){$c(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(ny,Number(r)||Jh)):Jh,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 aR(t){$c(t,!t.follow)}function $c(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Vt(t,e){gn.cursorTo(process.stdout,0),gn.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
813
|
+
`),t.unread+=1,vc(t),t.rl.prompt(!0)}function vc(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function ey(t){if(xc)return;xc=!0,pR(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
|
|
811
814
|
bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
|
|
812
|
-
stopping the embedded worker\u2026`),e.kill("SIGTERM"),e.on("exit",()=>{console.log("bye."),setTimeout(()=>process.exit(0),150)}),setTimeout(()=>{t.workerExited||e.kill("SIGKILL")},8e3).unref(),setTimeout(()=>process.exit(0),1e4).unref()}function
|
|
815
|
+
stopping the embedded worker\u2026`),e.kill("SIGTERM"),e.on("exit",()=>{console.log("bye."),setTimeout(()=>process.exit(0),150)}),setTimeout(()=>{t.workerExited||e.kill("SIGKILL")},8e3).unref(),setTimeout(()=>process.exit(0),1e4).unref()}function cR(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function lR(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 uR(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function po(t){t instanceof G?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function dR(){if(!ty(es))return[];try{return FT(es,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function pR(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{BT(HT(es),{recursive:!0}),KT(es,r.slice().reverse().join(`
|
|
813
816
|
`)+`
|
|
814
|
-
`)}catch{}}var Wi,Nh,Fh,Oh,pc,mc=b(()=>{"use strict";Ua();we();Wo();ie();st();Gi();cc();Gs();Wi=Bh(TT(),".codepipe","history"),Nh=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Fh=500,Oh=40;pc=!1});import{existsSync as Gh,readFileSync as zT,readdirSync as JT}from"node:fs";import{join as Hh}from"node:path";import{simpleGit as XT}from"simple-git";import{parse as QT}from"yaml";function ZT(t){let e=new Map,r=Hh(t,ss);if(!Gh(r))return e;let n;try{n=QT(zT(r,"utf-8"))}catch{return e}let o=n?.repos;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object")continue;let a=s,c=a.counts??{};typeof a.builtFromCommit=="string"&&e.set(i,{builtFromCommit:a.builtFromCommit,counts:{component:typeof c.component=="number"?c.component:0,code:typeof c.code=="number"?c.code:0,correlates:typeof c.correlates=="number"?c.correlates:0}})}return e}function eR(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return Cr({modelFormatVersion:2,repos:e})}function Wh(t,e){let r=Hh(t,e);if(!Gh(r))return[];let n=[];for(let o of JT(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Wh(t,i)):n.push(i)}return n}async function gc(t,e,r={}){let n=[],o=0;for(let p of e){n.push(...p.files);let d=`model/derived/structure/${p.repo}`;for(let f of Wh(t,d))p.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=ZT(t);for(let p of e)i.set(p.repo,{builtFromCommit:p.headCommit,counts:p.counts});n.push({path:ss,content:eR(i)});let s=jf(mi(t),r.halfLifeDays??We.halfLifeDays);n.push({path:xr,content:gi(s)});let a=XT(t),c=(await a.revparse(["HEAD"]).catch(()=>"")).trim(),l=`model: build ${e.map(p=>`${p.repo}@${p.headCommit.slice(0,10)}`).join(", ")}`;return await be(t,n,l),{committed:(await a.revparse(["HEAD"]).catch(()=>"")).trim()!==c,filesWritten:n.filter(p=>!p.deleted).length,filesDeleted:o}}var Yh=b(()=>{"use strict";F();Sa();Xe()});var Qh={};mo(Qh,{bootstrapWorkspaceModel:()=>Xh,modelBootstrapCommand:()=>wc,modelBuildCommand:()=>kc});import{existsSync as tR}from"node:fs";import{join as qh}from"node:path";import{cancel as rR,intro as Vh,log as yc,outro as hc}from"@clack/prompts";function io(t){rR(t),process.exit(1)}function zh(t,e){let r=t.spec.repos.filter(o=>!e||o.name===e);r.length===0&&io(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let n=[];for(let o of r){let i=o.mountAs==="."?t.root:qh(t.root,o.mountAs);if(!tR(qh(i,".git"))){yc.warn(`${o.name}: no local clone at ${i} \u2014 skipped (run \`codepipe clone\` first)`);continue}n.push({name:o.name,dir:i})}return n.length===0&&io("nothing to do \u2014 no repo clones found"),n}async function Jh(t,e,r){let n=[];for(let o of e)try{let i=await Cf({repo:o.name,repoDir:o.dir,contextDir:t.contextDir,settings:r});n.push(i),yc.info(`${o.name}: ${i.counts.code} files, ${i.counts.component} components, ${i.counts.correlates} co-change edges @ ${i.headCommit.slice(0,10)}`)}catch(i){io(`${o.name}: ${i instanceof Error?i.message:String(i)}`)}return n}async function kc(t){Vh("codepipe model build");let e=ye();e||io("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");let r=Wn(e.contextDir),n=await Jh(e,zh(e,t.repo),r),o=await gc(e.contextDir,n,{halfLifeDays:r.cochange.halfLifeDays});o.committed?hc(`model updated: ${o.filesWritten} files written, ${o.filesDeleted} stale removed`):hc("model already up to date (no changes)")}async function wc(t){Vh("codepipe model bootstrap");let e=ye();e||io("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)"),await Xh(e,t.repo,{onLog:r=>yc.info(r)}),hc("bootstrap complete")}async function Xh(t,e,r){let n=Wn(t.contextDir),o=zh(t,e),i=await Jh(t,o,n),s=tf(t.contextDir),a=ef(n.issueKeyPattern,s),c=fr([...n.ignore,...Wr]),l=[];for(let d of i){let f=o.find(g=>g.name===d.repo),m=await nf({repo:d.repo,repoDir:f.dir,headCommit:d.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:a,pathToCurrent:ui(d.identityTable),entityByKey:d.entityByKey,ignored:c});l.push(m),r.onLog(`${d.repo}: ${m.size} task events mined from history`)}let{files:u,skippedPipeline:p}=of(t.contextDir,l);return p>0&&r.onLog(`${p} events already recorded by the live pipeline \u2014 left untouched`),u.length>0&&await be(t.contextDir,u,`model: bootstrap ${u.length} task events from history`),await gc(t.contextDir,i,{halfLifeDays:n.cochange.halfLifeDays}),{events:u.length}}var bc=b(()=>{"use strict";Xe();Yh();va();wa();di();fi();st()});import{existsSync as pn,mkdirSync as ey,readFileSync as ty,readdirSync as nR,writeFileSync as ry}from"node:fs";import{join as hr,resolve as ny}from"node:path";import{setTimeout as $c}from"node:timers/promises";import{cancel as oR,confirm as fn,intro as oy,isCancel as Sc,log as N,multiselect as iR,outro as vc,password as so,select as xt,spinner as Tc,text as de}from"@clack/prompts";import{simpleGit as qi}from"simple-git";function oe(t){oR(t),process.exit(1)}function Se(t){return Sc(t)&&oe("aborted"),t}function re(t){return Sc(t)&&oe("aborted"),typeof t=="string"?t:""}async function iy(t={}){oy("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();wh();let r=kh(e),n,o=!1;r&&Object.keys(r.answers).length>0?Se(await fn({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(N.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new un(e,r),o=!0):(oc(e),n=new un(e)):n=new un(e);let i=t.force===!0?null:await lc(e),s=await n.ask("target",async()=>Se(await xt({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?N.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||ay(e,t.force===!0));let c=await n.ask("hubUrl",async()=>re(await de({message:"HUB URL",placeholder:et,initialValue:W("HUB_URL")??et,validate:D=>D.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>mn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>gn(c,l)),d=null;s==="farm"&&(d=await sR(c,u));let f=a?cR(a.parsed.repoName):"",m=await n.ask("projectId",async()=>re(await de({message:"project id (slug)",placeholder:f||"acme",...f?{initialValue:f}:{},validate:D=>Qt.test(D.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>re(await de({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:D=>D.trim().length>0?void 0:"required"})).trim()),k=await n.ask("automationLevel",async()=>Se(await xt({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"}))),w=s==="farm"?"auto":await n.ask("applyMode",async()=>Se(await xt({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"}))),h=await n.ask("trackerProvider",async()=>Se(await xt({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=h==="internal",T=null,R,x=!0;if(v){let D,ce=Tc();ce.start("checking task-key prefixes on your account\u2026");try{D=await gd(c,u,{excludeProjectId:m}),ce.stop("prefixes checked")}catch{ce.stop("could not reach the HUB",1),oe("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 Ne=Ul(Ml(g),D);R=await n.ask("trackerPrefix",async()=>re(await de({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Ne,initialValue:Ne,validate:Ke=>{let St=Ke.trim();if(!Ir.test(St))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(D.has(St.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else T=await n.ask("youtrack",()=>my()),R=await n.ask("youtrackProjectKey",async()=>re(await de({message:"YouTrack project key",placeholder:"DEV",validate:D=>D.trim().length>0?void 0:"required"})).trim()),x=await n.ask("youtrackWrites",async()=>Se(await fn({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let $=n.get("tokens")??{},_=()=>n.set("tokens",$),U=await n.ask("repos",()=>dR($,l,a,{onCred:_,initial:n.get("reposPartial")??[],onProgress:D=>n.set("reposPartial",D)}));n.delete("reposPartial");let G=await pR(await n.ask("contextRepo",()=>dy(m,U,$,l)),m,U,$,l,_,D=>n.set("contextRepo",D)),{spec:P,mode:y}=G,I;v||(N.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()=>re(await de({message:"your YouTrack login (the assignee value)",...T?.login?{initialValue:T.login}:{},validate:D=>D.trim().length>0?void 0:"required"})).trim()));let E=await n.ask("llmProvider",async()=>{for(;;){if(Se(await xt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";N.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),C=E==="claude"?await n.ask("claudeToken",()=>ch(ah("claude"),{farm:s==="farm"})):"",O;if(C){let D=await rd(C);if(D){let ce=ul(D);ce&&(O=ce,N.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${ce} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let j={projectId:m,name:g,automationLevel:k,repos:U,trackerProvider:h,youtrackProjectKey:R};N.step(`${y==="attach"?"attaching to":"provisioning"} Context Repo ${P.owner}/${P.name} (${P.host})\u2026`);let S;try{S=await ln(j,P,{...py($),youtrackWrites:x,...T?{trackerUrl:T.url}:{},mode:y,log:{info:D=>N.message(D),warn:D=>N.warn(D)}})}catch(D){oe(`Context Repo provisioning failed: ${D instanceof Error?D.message:String(D)}`)}j.contextRepo=S,N.success(`Context Repo ready: ${S.owner}/${S.name}@${S.branch}`),N.step(`registering project on ${c}\u2026`);let A;try{A=await Nt(c,u,j)}catch(D){if(D instanceof K&&D.status===409){N.warn(`project ${m} already exists on HUB \u2014 reusing it`);try{A=await Q(c,u,m)}catch(ce){throw ce instanceof K&&oe(`HUB \u2192 ${ce.status} ${ce.message}`),ce}}else if(D instanceof K&&D.status===401)n.delete("cliToken"),oe("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(D instanceof K)oe(`HUB \u2192 ${D.status} ${D.message}`);else throw D}let L=A.contextRepo??S;N.success(`project ${A.projectId} ready (${A.provisioningStatus})`);let V=await yR(L),Re=T?{url:T.url,token:T.token}:void 0;if(s==="farm"){let D=d,ce={...$,...V?{contextWrite:V}:{},...C?{claude:{oauthToken:C}}:{},...Re?{youtrack:Re}:{}},Ne=$.github?.token;if(L.host==="github"&&Ne)try{let Z=xm(`devpipe-${m}`);await Sm(L,Ne,Z.publicKey,`devpipe-${m}`),ce.contextSsh={privateKey:Z.privateKey},N.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(Z){N.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 Ke={projectId:m,config:{hubUrl:c,cliToken:u,projectId:m},secrets:ce,contextRepo:L,projectConfig:lt(j,x,T?.url,I||void 0,"auto",E,O)},St=wt(D.farm.publicKey,JSON.stringify(Ke));N.step(`handing project ${m} to farm ${D.farm.name}\u2026`);let q;try{q=await Go(c,u,D.farm.farmId,{projectId:m,sealedBundle:St})}catch(Z){throw Z instanceof K&&oe(Z.status===409?`farm ${D.farm.name} is offline \u2014 start it and re-run.`:Z.status===504?`farm ${D.farm.name} did not respond in time.`:`HUB \u2192 ${Z.status} ${Z.message}`),Z}q.ok||oe(`farm rejected provisioning: ${q.error??"unknown error"}`),await xc(c,u,m,L,Ne,A.repos,null,$),n.clear(),vc(`done. project ${m} is now hosted on farm ${D.farm.name} (daemon ${q.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}fy($),await cy(e,L.cloneUrl,L.branch),uy(e),a&&await uR(e);{let D=hr(e,it);Br(D);let ce=lt(j,x,T?.url,I||void 0,w,E,O),Ne=Ln(D,ce);Ne.length>0&&N.success(`local project config \u2192 .codepipe/{${Ne.join(", ")}}`),dr(m,ce,{info:Ke=>N.message(Ke),warn:Ke=>N.warn(Ke)})}await ly(e,A.repos);let wr={hubUrl:c,cliToken:u,projectId:m,...$,...V?{contextWrite:V}:{},...C?{claude:{oauthToken:C}}:{},...Re?{youtrack:Re}:{}};X(wr),yt({hubUrl:c,cliToken:u,projectId:m,accountEmail:p},m),N.success(`secrets \u2192 ${at(m)}`),await xc(c,u,m,L,$.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,A.repos,e,$),n.clear();let br=`${c}/?project=${encodeURIComponent(m)}`;nr(br),vc(`done. your project on the dashboard (sign in there to work with it):
|
|
815
|
-
${
|
|
816
|
-
starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:
|
|
817
|
+
`)}catch{}}var es,Xh,ny,Jh,xc,Tc=b(()=>{"use strict";Xa();xe();Xo();ue();lt();Qi();wc();Zs();es=ry(GT(),".codepipe","history"),Xh=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],ny=500,Jh=40;xc=!1});import{existsSync as iy,readFileSync as fR,readdirSync as mR}from"node:fs";import{join as sy}from"node:path";import{simpleGit as gR}from"simple-git";import{parse as hR}from"yaml";function yR(t){let e=new Map,r=sy(t,gs);if(!iy(r))return e;let n;try{n=hR(fR(r,"utf-8"))}catch{return e}let o=n?.repos;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object")continue;let a=s,c=a.counts??{};typeof a.builtFromCommit=="string"&&e.set(i,{builtFromCommit:a.builtFromCommit,counts:{component:typeof c.component=="number"?c.component:0,code:typeof c.code=="number"?c.code:0,correlates:typeof c.correlates=="number"?c.correlates:0}})}return e}function kR(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return Cr({modelFormatVersion:2,repos:e})}function ay(t,e){let r=sy(t,e);if(!iy(r))return[];let n=[];for(let o of mR(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...ay(t,i)):n.push(i)}return n}async function Rc(t,e,r={}){let n=[],o=0;for(let p of e){n.push(...p.files);let d=`model/derived/structure/${p.repo}`;for(let f of ay(t,d))p.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=yR(t);for(let p of e)i.set(p.repo,{builtFromCommit:p.headCommit,counts:p.counts});n.push({path:gs,content:kR(i)});let s=Wf(wi(t),r.halfLifeDays??qe.halfLifeDays);n.push({path:Tr,content:bi(s)});let a=gR(t),c=(await a.revparse(["HEAD"]).catch(()=>"")).trim(),l=`model: build ${e.map(p=>`${p.repo}@${p.headCommit.slice(0,10)}`).join(", ")}`;await Se(t,n,l);let u=(await a.revparse(["HEAD"]).catch(()=>"")).trim();if(u!==c){let{rebuildSearchIndex:p}=await Promise.resolve().then(()=>(Qn(),Jn));await p(t).catch(()=>{})}return{committed:u!==c,filesWritten:n.filter(p=>!p.deleted).length,filesDeleted:o}}var cy=b(()=>{"use strict";K();Na();Ze()});var my={};Rn(my,{bootstrapWorkspaceModel:()=>fy,modelBootstrapCommand:()=>Ac,modelBuildCommand:()=>Cc});import{existsSync as wR}from"node:fs";import{join as ly}from"node:path";import{cancel as bR,intro as uy,log as Ic,outro as Ec}from"@clack/prompts";function fo(t){bR(t),process.exit(1)}function dy(t,e){let r=t.spec.repos.filter(o=>!e||o.name===e);r.length===0&&fo(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let n=[];for(let o of r){let i=o.mountAs==="."?t.root:ly(t.root,o.mountAs);if(!wR(ly(i,".git"))){Ic.warn(`${o.name}: no local clone at ${i} \u2014 skipped (run \`codepipe clone\` first)`);continue}n.push({name:o.name,dir:i})}return n.length===0&&fo("nothing to do \u2014 no repo clones found"),n}async function py(t,e,r){let n=[];for(let o of e)try{let i=await Uf({repo:o.name,repoDir:o.dir,contextDir:t.contextDir,settings:r});n.push(i),Ic.info(`${o.name}: ${i.counts.code} files, ${i.counts.component} components, ${i.counts.correlates} co-change edges @ ${i.headCommit.slice(0,10)}`)}catch(i){fo(`${o.name}: ${i instanceof Error?i.message:String(i)}`)}return n}async function Cc(t){uy("codepipe model build");let e=$e();e||fo("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");let r=Xn(e.contextDir),n=await py(e,dy(e,t.repo),r),o=await Rc(e.contextDir,n,{halfLifeDays:r.cochange.halfLifeDays});o.committed?Ec(`model updated: ${o.filesWritten} files written, ${o.filesDeleted} stale removed`):Ec("model already up to date (no changes)")}async function Ac(t){uy("codepipe model bootstrap");let e=$e();e||fo("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)"),await fy(e,t.repo,{onLog:r=>Ic.info(r)}),Ec("bootstrap complete")}async function fy(t,e,r){let n=Xn(t.contextDir),o=dy(t,e),i=await py(t,o,n),s=mf(t.contextDir),a=ff(n.issueKeyPattern,s),c=yr([...n.ignore,...qr]),l=[];for(let d of i){let f=o.find(g=>g.name===d.repo),m=await hf({repo:d.repo,repoDir:f.dir,headCommit:d.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:a,pathToCurrent:gi(d.identityTable),entityByKey:d.entityByKey,ignored:c});l.push(m),r.onLog(`${d.repo}: ${m.size} task events mined from history`)}let{files:u,skippedPipeline:p}=yf(t.contextDir,l);return p>0&&r.onLog(`${p} events already recorded by the live pipeline \u2014 left untouched`),u.length>0&&await Se(t.contextDir,u,`model: bootstrap ${u.length} task events from history`),await Rc(t.contextDir,i,{halfLifeDays:n.cochange.halfLifeDays}),{events:u.length}}var Pc=b(()=>{"use strict";Ze();cy();_a();Ca();hi();ki();lt()});import{existsSync as hn,mkdirSync as hy,readFileSync as yy,readdirSync as $R,writeFileSync as ky}from"node:fs";import{join as br,resolve as wy}from"node:path";import{setTimeout as _c}from"node:timers/promises";import{cancel as vR,confirm as yn,intro as by,isCancel as Oc,log as P,multiselect as xR,outro as jc,password as mo,select as Tt,spinner as Dc,text as me}from"@clack/prompts";import{simpleGit as rs}from"simple-git";function ce(t){vR(t),process.exit(1)}function Ie(t){return Oc(t)&&ce("aborted"),t}function oe(t){return Oc(t)&&ce("aborted"),typeof t=="string"?t:""}async function $y(t={}){by("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Oh();let r=Nh(e),n,o=!1;r&&Object.keys(r.answers).length>0?Ie(await yn({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(P.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new mn(e,r),o=!0):(gc(e),n=new mn(e)):n=new mn(e);let i=t.force===!0?null:await bc(e),s=await n.ask("target",async()=>Ie(await Tt({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?P.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||xy(e,t.force===!0));let c=await n.ask("hubUrl",async()=>oe(await me({message:"HUB URL",placeholder:nt,initialValue:q("HUB_URL")??nt,validate:D=>D.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>kn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>wn(c,l)),d=null;s==="farm"&&(d=await SR(c,u));let f=a?RR(a.parsed.repoName):"",m=await n.ask("projectId",async()=>oe(await me({message:"project id (slug)",placeholder:f||"acme",...f?{initialValue:f}:{},validate:D=>rr.test(D.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>oe(await me({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:D=>D.trim().length>0?void 0:"required"})).trim()),k=await n.ask("automationLevel",async()=>Ie(await Tt({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"}))),w=s==="farm"?"auto":await n.ask("applyMode",async()=>Ie(await Tt({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"}))),h=await n.ask("trackerProvider",async()=>Ie(await Tt({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=h==="internal",T=null,R,x=!0;if(v){let D,le=Dc();le.start("checking task-key prefixes on your account\u2026");try{D=await Ed(c,u,{excludeProjectId:m}),le.stop("prefixes checked")}catch{le.stop("could not reach the HUB",1),ce("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 he=Jl(Xl(g),D);R=await n.ask("trackerPrefix",async()=>oe(await me({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:he,initialValue:he,validate:He=>{let Rt=He.trim();if(!Pr.test(Rt))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(D.has(Rt.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else T=await n.ask("youtrack",()=>Ay()),R=await n.ask("youtrackProjectKey",async()=>oe(await me({message:"YouTrack project key",placeholder:"DEV",validate:D=>D.trim().length>0?void 0:"required"})).trim()),x=await n.ask("youtrackWrites",async()=>Ie(await yn({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let $=n.get("tokens")??{},C=()=>n.set("tokens",$),U=await n.ask("repos",()=>CR($,l,a,{onCred:C,initial:n.get("reposPartial")??[],onProgress:D=>n.set("reposPartial",D)}));n.delete("reposPartial");let H=await AR(await n.ask("contextRepo",()=>Ey(m,U,$,l)),m,U,$,l,C,D=>n.set("contextRepo",D)),{spec:I,mode:y}=H,L;v||(P.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),L=await n.ask("assigneeLogin",async()=>oe(await me({message:"your YouTrack login (the assignee value)",...T?.login?{initialValue:T.login}:{},validate:D=>D.trim().length>0?void 0:"required"})).trim()));let N=await n.ask("llmProvider",async()=>{for(;;){if(Ie(await Tt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";P.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),F=N==="claude"?await n.ask("claudeToken",()=>Sh(xh("claude"),{farm:s==="farm"})):"",A;if(F){let D=await md(F);if(D){let le=vl(D);le&&(A=le,P.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${le} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let _={projectId:m,name:g,automationLevel:k,repos:U,trackerProvider:h,youtrackProjectKey:R};P.step(`${y==="attach"?"attaching to":"provisioning"} Context Repo ${I.owner}/${I.name} (${I.host})\u2026`);let O;try{O=await fn(_,I,{...Iy($),youtrackWrites:x,...T?{trackerUrl:T.url}:{},mode:y,log:{info:D=>P.message(D),warn:D=>P.warn(D)}})}catch(D){ce(`Context Repo provisioning failed: ${D instanceof Error?D.message:String(D)}`)}_.contextRepo=O,P.success(`Context Repo ready: ${O.owner}/${O.name}@${O.branch}`),P.step(`registering project on ${c}\u2026`);let W;try{W=await Lt(c,u,_)}catch(D){if(D instanceof G&&D.status===409){P.warn(`project ${m} already exists on HUB \u2014 reusing it`);try{W=await te(c,u,m)}catch(le){throw le instanceof G&&ce(`HUB \u2192 ${le.status} ${le.message}`),le}}else if(D instanceof G&&D.status===401)n.delete("cliToken"),ce("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(D instanceof G)ce(`HUB \u2192 ${D.status} ${D.message}`);else throw D}let j=W.contextRepo??O;P.success(`project ${W.projectId} ready (${W.provisioningStatus})`);let S=await OR(j),E=T?{url:T.url,token:T.token}:void 0;if(s==="farm"){let D=d,le={...$,...S?{contextWrite:S}:{},...F?{claude:{oauthToken:F}}:{},...E?{youtrack:E}:{}},he=$.github?.token;if(j.host==="github"&&he)try{let re=Um(`devpipe-${m}`);await Bm(j,he,re.publicKey,`devpipe-${m}`),le.contextSsh={privateKey:re.privateKey},P.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(re){P.warn(`could not set up Context Repo SSH deploy key (${re instanceof Error?re.message:String(re)}); the farm will fall back to the token path.`)}let He={projectId:m,config:{hubUrl:c,cliToken:u,projectId:m},secrets:le,contextRepo:j,projectConfig:pt(_,x,T?.url,L||void 0,"auto",N,A)},Rt=$t(D.farm.publicKey,JSON.stringify(He));P.step(`handing project ${m} to farm ${D.farm.name}\u2026`);let X;try{X=await Vo(c,u,D.farm.farmId,{projectId:m,sealedBundle:Rt})}catch(re){throw re instanceof G&&ce(re.status===409?`farm ${D.farm.name} is offline \u2014 start it and re-run.`:re.status===504?`farm ${D.farm.name} did not respond in time.`:`HUB \u2192 ${re.status} ${re.message}`),re}X.ok||ce(`farm rejected provisioning: ${X.error??"unknown error"}`),await Nc(c,u,m,j,he,W.repos,null,$),n.clear(),jc(`done. project ${m} is now hosted on farm ${D.farm.name} (daemon ${X.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Cy($),await Sy(e,j.cloneUrl,j.branch),Ry(e),a&&await IR(e);{let D=br(e,ct);Kr(D);let le=pt(_,x,T?.url,L||void 0,w,N,A),he=Kn(D,le);he.length>0&&P.success(`local project config \u2192 .codepipe/{${he.join(", ")}}`),gr(m,le,{info:He=>P.message(He),warn:He=>P.warn(He)})}await Ty(e,W.repos);let z={hubUrl:c,cliToken:u,projectId:m,...$,...S?{contextWrite:S}:{},...F?{claude:{oauthToken:F}}:{},...E?{youtrack:E}:{}};ee(z),wt({hubUrl:c,cliToken:u,projectId:m,accountEmail:p},m),P.success(`secrets \u2192 ${ut(m)}`),await Nc(c,u,m,j,$.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,W.repos,e,$),n.clear();let ie=`${c}/?project=${encodeURIComponent(m)}`;ar(ie),jc(`done. your project on the dashboard (sign in there to work with it):
|
|
818
|
+
${ie}
|
|
819
|
+
starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:Qt}=await Promise.resolve().then(()=>(Tc(),oy));await Qt({})}async function Nc(t,e,r,n,o,i=[],s=null,a={}){let c=await Mh(n,o),l=!1;if(!c)try{l=await Fh(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Lh({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await xR({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Oc(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let f=$e(s);if(!f)throw new Error("workspace not found");let{bootstrapWorkspaceModel:m}=await Promise.resolve().then(()=>(Pc(),my)),g=await m(f,void 0,{onLog:k=>P.message(k)});P.success(`project map ready: ${g.events} task events mined from history`)}catch(f){P.warn(`could not build the project map: ${f instanceof Error?f.message:String(f)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:f}=await Ln(t,e,r,{reindex:!1,backfill:!0});P.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){P.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:f}=await Ln(t,e,r,{reindex:u.reindex});P.success(`indexing queued (job ${f}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(f){P.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function SR(t,e){let r;try{r=await xd(t,e)}catch(c){throw c instanceof G&&ce(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&ce("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=Ie(await Tt({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=Pi(i.farmId,i.publicKey)}catch(c){ce(c instanceof Error?c.message:String(c))}return Ie(await yn({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
817
820
|
${s}
|
|
818
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||
|
|
821
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||ce("farm fingerprint not confirmed \u2014 aborting."),Ai(i.farmId,s),{farm:i,fingerprint:s}}async function vy(t){by(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();xy(e,t.force===!0);let r=oe(await me({message:"HUB URL",initialValue:q("HUB_URL")??nt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await kn(),{cliToken:o,accountEmail:i}=await wn(r,n);P.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await te(r,o,t.projectId)}catch(d){throw d instanceof G&&ce(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||ce(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Ay(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let f=s.repos.find(m=>m.host===d);await ts(d,l,f?.owner??s.contextRepo.owner,n,f?.repoName)}Cy(l),await Sy(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Ry(e);{let d=br(e,ct);Kr(d);let f={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},m=pt(f,!0,c?.url,void 0,"auto",s.llmProvider??at),g=Kn(d,m);g.length>0&&P.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),gr(t.projectId,m,{info:k=>P.message(k),warn:k=>P.warn(k)})}await Ty(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ee(p),wt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),P.success(`secrets \u2192 ${ut(t.projectId)}`),await Nc(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),jc("done.")}function xy(t,e){if(!hn(t)){hy(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=$R(t).filter(o=>!r.has(o));n.length!==0&&(e||ce(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function bc(t){if(!hn(br(t,".git")))return null;try{let r=(await rs(t).remote(["get-url","origin"])||"").toString().trim(),n=r?Ge(r):null;return n?{parsed:n,defaultBranch:await TR(t)}:null}catch{return null}}async function TR(t){let e=rs(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 RR(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return rr.test(e)?e:""}function ER(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function IR(t){let e=br(t,".gitignore"),r=hn(e)?yy(e,"utf-8"):"";if(ER(r))return;if(!Ie(await yn({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){P.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
|
|
819
822
|
`)?"":`
|
|
820
|
-
`;
|
|
823
|
+
`;ky(e,r+o+`
|
|
821
824
|
# codepipe workspace (added by \`codepipe init\`)
|
|
822
825
|
.codepipe/
|
|
823
|
-
`),
|
|
826
|
+
`),P.success(`.codepipe/ added to ${wy(e)}`)}async function kn(){let t="";try{t=(await rs().raw(["config","--global","user.email"])||"").trim()}catch{}return oe(await me({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function wn(t,e){P.step(`connecting account ${e}`);let r;try{r=await Id(t,e)}catch(s){throw s instanceof Dn&&ce(`${e} is not authorized on this HUB yet.
|
|
824
827
|
Sign up at ${t} (registration form on the login screen),
|
|
825
828
|
wait for the operator to approve it by email, then re-run
|
|
826
|
-
\`codepipe init\` with the same email.`),s}r.accountCreated&&
|
|
829
|
+
\`codepipe init\` with the same email.`),s}r.accountCreated&&P.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&P.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(ar(r.authorizeUrl),P.message(`a browser tab was opened to confirm this CLI:
|
|
827
830
|
${r.authorizeUrl}
|
|
828
831
|
`+(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
|
|
829
|
-
otherwise use the emailed link the page offers.`))),r.approvalRequired&&
|
|
830
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
832
|
+
otherwise use the emailed link the page offers.`))),r.approvalRequired&&P.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),P.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 Cd(t,r.requestId)}catch(a){P.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await _c(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&P.message(`connected as ${a} (the account confirmed in the browser).`),P.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&ce("the HUB rejected this account"),s.status==="expired"&&ce("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,P.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
833
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await _c(5e3);continue}await _c(2e3)}ce("bootstrap timed out")}async function Sy(t,e,r){let n=br(t,ct);if(hn(br(n,".git"))){P.message(`${n} already cloned \u2014 skipping`);return}hn(n)&&ce(`${n} exists but is not a git repo \u2014 remove it and re-run`),hy(n,{recursive:!0}),P.step(`cloning Context Repo \u2192 ${n}`);try{await rs().clone(e,n,["--branch",r]),P.success(`cloned ${e}`)}catch(o){ce(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function Ty(t,e){if(e.length===0)return;P.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 lo(t,r,{log:{info:o=>P.message(o),warn:o=>P.warn(o)}});for(let o of n)P.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Ry(t){let e=br(t,ct,".gitignore"),r="";if(hn(e)&&(r=yy(e,"utf-8")),gy.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
|
|
831
834
|
`)||r.length===0?"":`
|
|
832
|
-
`,i=
|
|
835
|
+
`,i=gy.join(`
|
|
833
836
|
`)+`
|
|
834
|
-
`;
|
|
835
|
-
`:"")+i),
|
|
837
|
+
`;ky(e,r+o+(r?`
|
|
838
|
+
`:"")+i),P.message(`appended runtime entries to ${wy(e)}`)}async function CR(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;P.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await ts(s.host,t,s.owner,e,s.repoName),i?.();let c=oe(await me({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=oe(await me({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.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(;Ie(await yn({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=oe(await me({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||Ge(f)?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=Ge(a);P.message(`${c.host}: ${c.owner}/${c.repoName}`),await ts(c.host,t,c.owner,e,c.repoName),i?.();let l=oe(await me({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=oe(await me({message:"default branch (optional)",placeholder:"main"})).trim(),p=oe(await me({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),d={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(d.defaultBranch=u),p&&p!==l&&(d.mountAs=p),o.push(d),n.onProgress?.(o)}return o}async function Ey(t,e,r,n){P.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=Ie(await Tt({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"&&P.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=oe(await me({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:kt(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!Ge(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=Ge(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await PR(),l=oe(await me({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=oe(await me({message:"Context Repo name",placeholder:kt(t),initialValue:kt(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function Iy(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??Or()}}async function AR(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await ts(c.host,n,c.owner,o),i?.();let u=Dc();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await Rh(c,Iy(n),{explain:l==="attach"});if(p.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(p.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${p.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(p.detail,1);let d=Ie(await Tt({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(d==="abort"&&ce("aborted"),d==="create")return a={spec:c,mode:"create"},s(a),a;a=await Ey(e,r,n,o),s(a)}}async function PR(){return Ie(await Tt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function go(t,e){let r=Dc();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 Cy(t){qn(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Vn(t.gitlab?.token??process.env.GITLAB_TOKEN),zn(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function ts(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await _R(r);i?e.github=i:P.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await jR(r,n,o);i?e.bitbucket=i:P.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 NR();i?e.gitlab=i:P.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function _R(t){for(;;){let e=oe(await mo({message:`GitHub PAT \u2014 blank to skip
|
|
836
839
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
837
840
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
838
841
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
839
842
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
840
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await
|
|
843
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await go("GitHub",()=>At(e,t?{owner:t}:void 0)))return{token:e};P.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function jR(t,e,r){for(P.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
841
844
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
842
845
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
|
|
843
846
|
read:repository:bitbucket + write:repository:bitbucket +
|
|
844
847
|
read:pullrequest:bitbucket + write:pullrequest:bitbucket
|
|
845
848
|
\u2014 write scopes do NOT include read: pick BOTH scopes of each pair
|
|
846
849
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
847
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let n=
|
|
848
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
850
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let n=oe(await me({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=oe(await mo({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){P.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await go("Bitbucket",async()=>{let i=await Pt(n,o,t);if(t&&r){let s=await Ho(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};P.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function NR(){for(;;){let t=oe(await mo({message:`GitLab PAT \u2014 blank to skip
|
|
851
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await go("GitLab",()=>_t(t))){let e=await Du(t);return e&&P.warn(e),{token:t}}P.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function OR(t){if(Ie(await yn({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
849
852
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
850
853
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
851
|
-
your trusted network.`,initialValue:!1})))for(t.host==="github"?
|
|
854
|
+
your trusted network.`,initialValue:!1})))for(t.host==="github"?P.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
852
855
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
853
|
-
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):
|
|
854
|
-
(${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=
|
|
855
|
-
[${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}an();Pe();we();async function nh(t={profile:void 0}){let e=Le(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Ko(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 u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);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,u)=>{s.push(`close:${l}:${u?.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 Q(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=xe(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`)")}no();import{readFileSync as wR}from"node:fs";F();Pe();kt();Bi();pr();At();rr();we();ie();function ue(t){throw new Error(t)}function he(t,e){return(typeof t!="string"||t.trim().length===0)&&ue(`config: '${e}' must be a non-empty string`),t.trim()}function co(t,e){if(t==null)return;typeof t!="string"&&ue(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function bR(t){(!t||typeof t!="object")&&ue("config: expected a JSON object");let e=t,r=he(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ue("config: 'hubUrl' must start with http(s)://");let n=he(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ue("config: 'project' is required");let i=o,s=he(i.id,"project.id");Qt.test(s)||ue("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=he(i.name,"project.name"),c=he(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ue("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ue("config: 'project.repos' must be an array");let u=l.map((h,v)=>{(!h||typeof h!="object")&&ue(`config: project.repos[${v}] must be an object`);let T=h,R=he(T.host,`project.repos[${v}].host`);R!=="github"&&R!=="bitbucket"&&R!=="gitlab"&&ue(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let x={name:he(T.name,`project.repos[${v}].name`),host:R,owner:he(T.owner,`project.repos[${v}].owner`),repoName:he(T.repoName,`project.repos[${v}].repoName`)},$=co(T.defaultBranch,`project.repos[${v}].defaultBranch`);$&&(x.defaultBranch=$);let _=co(T.mountAs,`project.repos[${v}].mountAs`);return _&&(x.mountAs=_),x}),p=i.contextRepo;(!p||typeof p!="object")&&ue("config: 'project.contextRepo' is required");let d=p,f=co(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&ue("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:he(d.owner,"project.contextRepo.owner"),name:co(d.name,"project.contextRepo.name")??ht(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},k=co(i.youtrackProjectKey,"project.youtrackProjectKey");if(k&&(g.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&ue("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ue("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let h=he(i.llmProvider,"project.llmProvider");h==="codex"&&ue(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),h!=="claude"&&ue("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=h}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&ue("config: 'secrets' must be an object");let h=w,v={};if(h.github){let T=h.github;v.github={token:he(T.token,"secrets.github.token")}}if(h.bitbucket){let T=h.bitbucket;v.bitbucket={email:he(T.email,"secrets.bitbucket.email"),apiToken:he(T.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let T=h.gitlab;v.gitlab={token:he(T.token,"secrets.gitlab.token")}}if(h.youtrack){let T=h.youtrack;v.youtrack={url:he(T.url,"secrets.youtrack.url").replace(/\/$/,""),token:he(T.token,"secrets.youtrack.token")}}if(h.contextWrite){let T=h.contextWrite;v.contextWrite={token:he(T.token,"secrets.contextWrite.token")}}g.secrets=v}return g}async function $R(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function vR(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Ct(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 Et(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Uo(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 It(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 gy(t){let e=!t.configPath||t.configPath==="-"?await $R():wR(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){ue(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=bR(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 vR(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 ln(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??jr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){ue(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await Nt(o,i,a)}catch(d){if(d instanceof K&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await Q(o,i,s.id);else if(d instanceof K)ue(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(X(p),yt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${at(s.id)}`),dr(s.id,lt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??ot),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await _n(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}Pe();ie();import{cancel as hy,intro as yy,isCancel as ky,log as Rc,outro as xR,password as wy}from"@clack/prompts";async function SR(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function by(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await SR(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){yy("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Rc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await wy({message:"Claude OAuth token"});ky(i)&&(hy("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),mu({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${jo()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Le(t.profile);if(!e){yy(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Rc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await wy({message:"Claude OAuth token"});ky(i)&&(hy("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=H(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}.`):(Rc.success("Claude OAuth token saved."),xR("It will be sealed into job bundles when a SANDBOX (re)connects."))}bc();F();Pe();kt();Bi();pr();Fi();we();ie();import{cancel as TR,confirm as RR,intro as CR,isCancel as $y,log as Te,outro as ER,select as vy,text as qt}from"@clack/prompts";function xy(t){TR(t),process.exit(1)}function hn(t){return $y(t)&&xy("aborted"),t}function lo(t){return $y(t)&&xy("aborted"),typeof t=="string"?t:""}async function IR(t,e){let r=hn(await vy({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=lo(await qt({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=lo(await qt({message:"Context Repo name",placeholder:ht(t),initialValue:ht(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Sy(t={profile:void 0}){let e=Le(t.profile);CR(`codepipe project add \u2192 ${e.hubUrl}`);let r=hn(await qt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Qt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=hn(await qt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=hn(await vy({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=hn(await qt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=hn(await RR({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=lo(await qt({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:w=>!w||!w.trim()||Fe(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let f=Fe(d);Te.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=lo(await qt({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),g=lo(await qt({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:m,host:f.host,owner:f.owner,repoName:f.repoName};g&&(k.defaultBranch=g),a.push(k)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await IR(r,a),u=H(e.projectId);Te.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await ln(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??jr(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Te.message(d),warn:d=>Te.warn(d)}})}catch(d){Te.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Te.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Nt(e.hubUrl,e.cliToken,c);Te.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),dr(r,lt(c,s,u?.youtrack?.url),{info:f=>Te.message(f),warn:f=>Te.warn(f)}),d.contextRepo&&(Te.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Te.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Te.error(` error: ${d.provisioningError}`),ER("done")}catch(d){d instanceof K?(Te.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Te.message(JSON.stringify(d.payload,null,2))):Te.error(d instanceof Error?d.message:String(d)),process.exit(1)}}an();Pe();we();ie();st();no();import{existsSync as AR,rmSync as PR}from"node:fs";import{confirm as _R,intro as jR,isCancel as NR,log as Vt,outro as OR,spinner as DR}from"@clack/prompts";function dt(t){Vt.error(t),process.exit(1)}var Ty=t=>t.trim().replace(/\/+$/,"");async function Ry(t){jR("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ye()?.spec.projectId??void 0;e||dt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=qe(e);r||dt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Ty(r.hubUrl),o=r.projectId,i=Ty(t.hub);i.startsWith("http")||dt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&dt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=DR();w.start(`reading project ${o} from ${n}\u2026`);try{l=await Q(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(h){throw w.stop("could not read the source project",1),h instanceof K&&dt(`source HUB ${n} \u2192 ${h.status} ${h.message}. The source HUB must be reachable with a valid token to move a project.`),h}}l.contextRepo||dt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=H(o),p=(t.account??r.accountEmail??await mn()).trim().toLowerCase();if(Vt.message(`move project '${o}'
|
|
856
|
+
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):P.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
857
|
+
(${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=oe(await mo({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await go("contextWrite",()=>DR(r,t)))return{token:r};P.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function DR(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 Ay(){for(;;){let t=oe(await me({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=oe(await mo({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await go("YouTrack",()=>Ot({baseUrl:t,token:e}))){let r=await Xu({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}P.warn("re-enter the YouTrack URL / token.")}}var gy,uo=b(()=>{"use strict";Ae();K();Ke();Th();Yo();Ne();bt();hr();Mr();zi();Ja();Xi();jt();sr();Dh();xe();Uh();Kh();Wa();di();ue();Qi();lt();gy=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});K();Ae();Ne();import{Command as gE}from"commander";_o();import{homedir as pu}from"node:os";import{join as fu}from"node:path";function mu(){or(fu(pu(),".devpipe"),fu(pu(),".codepipe"))}Ne();ue();async function Eu(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=ze(e);r&&!t.force&&(console.error(`already configured at ${jr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");wt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...Y(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ee(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${jr(e)}`)}Ps();Ne();Xa();xe();ue();bt();Qa();lt();di();import{homedir as Za}from"node:os";import{join as ro}from"node:path";async function Vm(t={profile:void 0}){let{cfg:e,profile:r}=Do(t.profile),n=Y(e.projectId);n&&Nn(n),qn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Vn(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),zn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=ro(Za(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Uo("CLI_LOG",i,o);if(s.enabled){let d=new Dr(s);Bo(d),console.log(`[log] file logging \u2192 ${d.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=No(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 d=ro(Za(),".codepipe",r?ro("profiles",r,"context"):"context");if(await zs(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Ym(()=>Di({cfg:e,secrets:n,contextDir:d,log:{info:f=>console.log(f),warn:f=>console.warn(f)}}),{log:{warn:f=>console.warn(f)}}),a||await zs(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 f=ro(Za(),".codepipe",r?ro("profiles",r,"context-config"):"context-config");ni(a.contextDir,f,{info:m=>console.log(m),warn:m=>console.warn(m)})}}let l=Ni(e,{...a?{workspace:a}:{},onEvent:d=>{d.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))}}),u=!1;function p(d){u||(u=!0,console.log(`
|
|
858
|
+
[${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}dn();Ne();xe();async function wh(t={profile:void 0}){let e=Ue(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=qo(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 u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);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,u)=>{s.push(`close:${l}:${u?.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 te(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=Ee(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`)")}uo();import{readFileSync as LR}from"node:fs";K();Ne();bt();zi();hr();jt();sr();xe();ue();function fe(t){throw new Error(t)}function be(t,e){return(typeof t!="string"||t.trim().length===0)&&fe(`config: '${e}' must be a non-empty string`),t.trim()}function ho(t,e){if(t==null)return;typeof t!="string"&&fe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function MR(t){(!t||typeof t!="object")&&fe("config: expected a JSON object");let e=t,r=be(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||fe("config: 'hubUrl' must start with http(s)://");let n=be(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&fe("config: 'project' is required");let i=o,s=be(i.id,"project.id");rr.test(s)||fe("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=be(i.name,"project.name"),c=be(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&fe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||fe("config: 'project.repos' must be an array");let u=l.map((h,v)=>{(!h||typeof h!="object")&&fe(`config: project.repos[${v}] must be an object`);let T=h,R=be(T.host,`project.repos[${v}].host`);R!=="github"&&R!=="bitbucket"&&R!=="gitlab"&&fe(`config: project.repos[${v}].host must be 'github', 'bitbucket' or 'gitlab'`);let x={name:be(T.name,`project.repos[${v}].name`),host:R,owner:be(T.owner,`project.repos[${v}].owner`),repoName:be(T.repoName,`project.repos[${v}].repoName`)},$=ho(T.defaultBranch,`project.repos[${v}].defaultBranch`);$&&(x.defaultBranch=$);let C=ho(T.mountAs,`project.repos[${v}].mountAs`);return C&&(x.mountAs=C),x}),p=i.contextRepo;(!p||typeof p!="object")&&fe("config: 'project.contextRepo' is required");let d=p,f=ho(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&fe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:be(d.owner,"project.contextRepo.owner"),name:ho(d.name,"project.contextRepo.name")??kt(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},k=ho(i.youtrackProjectKey,"project.youtrackProjectKey");if(k&&(g.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&fe("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&fe("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let h=be(i.llmProvider,"project.llmProvider");h==="codex"&&fe(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),h!=="claude"&&fe("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=h}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&fe("config: 'secrets' must be an object");let h=w,v={};if(h.github){let T=h.github;v.github={token:be(T.token,"secrets.github.token")}}if(h.bitbucket){let T=h.bitbucket;v.bitbucket={email:be(T.email,"secrets.bitbucket.email"),apiToken:be(T.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let T=h.gitlab;v.gitlab={token:be(T.token,"secrets.gitlab.token")}}if(h.youtrack){let T=h.youtrack;v.youtrack={url:be(T.url,"secrets.youtrack.url").replace(/\/$/,""),token:be(T.token,"secrets.youtrack.token")}}if(h.contextWrite){let T=h.contextWrite;v.contextWrite={token:be(T.token,"secrets.contextWrite.token")}}g.secrets=v}return g}async function UR(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function BR(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await At(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 Pt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Ho(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 _t(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Ot({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Py(t){let e=!t.configPath||t.configPath==="-"?await UR():LR(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){fe(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=MR(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 BR(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 fn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Or(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){fe(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await Lt(o,i,a)}catch(d){if(d instanceof G&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await te(o,i,s.id);else if(d instanceof G)fe(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(ee(p),wt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${ut(s.id)}`),gr(s.id,pt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??at),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Ln(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}Ne();ue();import{cancel as _y,intro as jy,isCancel as Ny,log as Lc,outro as FR,password as Oy}from"@clack/prompts";async function KR(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Dy(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await KR(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){jy("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Lc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Oy({message:"Claude OAuth token"});Ny(i)&&(_y("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Ru({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Mo()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ue(t.profile);if(!e){jy(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Lc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Oy({message:"Claude OAuth token"});Ny(i)&&(_y("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=Y(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ee(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Lc.success("Claude OAuth token saved."),FR("It will be sealed into job bundles when a SANDBOX (re)connects."))}Pc();K();Ne();bt();zi();hr();Xi();xe();ue();import{cancel as GR,confirm as HR,intro as WR,isCancel as Ly,log as Ce,outro as YR,select as My,text as Xt}from"@clack/prompts";function Uy(t){GR(t),process.exit(1)}function bn(t){return Ly(t)&&Uy("aborted"),t}function yo(t){return Ly(t)&&Uy("aborted"),typeof t=="string"?t:""}async function qR(t,e){let r=bn(await My({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=yo(await Xt({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=yo(await Xt({message:"Context Repo name",placeholder:kt(t),initialValue:kt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function By(t={profile:void 0}){let e=Ue(t.profile);WR(`codepipe project add \u2192 ${e.hubUrl}`);let r=bn(await Xt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>rr.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=bn(await Xt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=bn(await My({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=bn(await Xt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=bn(await HR({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=yo(await Xt({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:w=>!w||!w.trim()||Ge(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let f=Ge(d);Ce.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=yo(await Xt({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),g=yo(await Xt({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:m,host:f.host,owner:f.owner,repoName:f.repoName};g&&(k.defaultBranch=g),a.push(k)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await qR(r,a),u=Y(e.projectId);Ce.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await fn(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??Or(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Ce.message(d),warn:d=>Ce.warn(d)}})}catch(d){Ce.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Ce.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Lt(e.hubUrl,e.cliToken,c);Ce.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),gr(r,pt(c,s,u?.youtrack?.url),{info:f=>Ce.message(f),warn:f=>Ce.warn(f)}),d.contextRepo&&(Ce.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Ce.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Ce.error(` error: ${d.provisioningError}`),YR("done")}catch(d){d instanceof G?(Ce.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Ce.message(JSON.stringify(d.payload,null,2))):Ce.error(d instanceof Error?d.message:String(d)),process.exit(1)}}dn();Ne();xe();ue();lt();uo();import{existsSync as VR,rmSync as zR}from"node:fs";import{confirm as XR,intro as JR,isCancel as QR,log as Jt,outro as ZR,spinner as eE}from"@clack/prompts";function mt(t){Jt.error(t),process.exit(1)}var Fy=t=>t.trim().replace(/\/+$/,"");async function Ky(t){JR("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??$e()?.spec.projectId??void 0;e||mt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=ze(e);r||mt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Fy(r.hubUrl),o=r.projectId,i=Fy(t.hub);i.startsWith("http")||mt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&mt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=eE();w.start(`reading project ${o} from ${n}\u2026`);try{l=await te(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(h){throw w.stop("could not read the source project",1),h instanceof G&&mt(`source HUB ${n} \u2192 ${h.status} ${h.message}. The source HUB must be reachable with a valid token to move a project.`),h}}l.contextRepo||mt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=Y(o),p=(t.account??r.accountEmail??await kn()).trim().toLowerCase();if(Jt.message(`move project '${o}'
|
|
856
859
|
from : ${n} (profile ${e})
|
|
857
860
|
to : ${i} (profile ${s}, project ${a}, account ${p})
|
|
858
861
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
859
862
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
860
|
-
`+(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 w=await
|
|
861
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await xd(e.hubUrl,e.cliToken,e.projectId,m)}catch(h){h instanceof K&&je(`HUB \u2192 ${h.status} ${h.message}`),je(h instanceof Error?h.message:String(h))}let{updated:k,errors:w}=Fn(e.projectId,g.repos,r?.contextDir);for(let h of k)pe.message(`updated ${h}`);for(let h of w)pe.warn(`could not update ${h.path}: ${h.error}`);pe.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),Iy("done")}async function _y(t){let e=Le(t.profile);Ey(`codepipe repo remove \u2192 project ${e.projectId}`);let r=ye()??void 0,n;try{let c=(await Q(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 Sd(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof K&&(a.status===404&&je(`no repo named "${t.name}" in this project`),je(`HUB \u2192 ${a.status} ${a.message}`)),je(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Fn(e.projectId,o.repos,r?.contextDir);for(let a of i)pe.message(`updated ${a}`);for(let a of s)pe.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")pe.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Vi(r.root,n):ve(e.projectId,t.name);if(Cc(Vi(a,".git")))try{LR(a,{recursive:!0,force:!0}),pe.message(`deleted local clone ${a}`)}catch(c){pe.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else pe.message(`no local clone found to purge (${a})`)}pe.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Iy("done")}async function jy(t){let e=Le(t.profile),r;try{r=(await Q(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}`)}}Gi();cc();mc();an();F();Ce();an();Pe();we();no();import{hostname as WR}from"node:os";import{cancel as YR,confirm as Ny,intro as qR,isCancel as Ly,log as yn,multiselect as VR,outro as Oy,password as zR,select as Ec,text as Ic}from"@clack/prompts";function uo(t){YR(t),process.exit(1)}function kn(t){return Ly(t)&&uo("aborted"),t}function zi(t){return Ly(t)&&uo("aborted"),typeof t=="string"?t:""}function Ji(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Dy(t,e){try{let{secret:r}=await Ho(t,e);return r}catch(r){throw r instanceof K&&r.status===404&&uo("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 JR(t,e){if(kn(await Ec({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 Ls(t,e);if(o.length>0)return kn(await VR({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}));yn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){yn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return zi(await Ic({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 Ac(t){qR("codepipe worker \u2014 set up this machine as a runner");let e=xe(t.profile);e&&(yn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),kn(await Ny({message:"re-register this worker?",initialValue:!1}))||uo("keeping the existing registration"));let r=qe(t.profile)??qe(),n=zi(await Ic({message:"HUB URL",placeholder:et,initialValue:W("HUB_URL")??r?.hubUrl??et,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=kn(await Ec({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 Dy(n,a),yn.success("account-issued registration token minted");else if(i==="login"){let d=await mn();a=(await gn(n,d)).cliToken,s=await Dy(n,a),yn.success("account-issued registration token minted")}else s=zi(await zR({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||uo("a registration token is required");let c=await JR(n,a),l=zi(await Ic({message:"worker name",initialValue:WR(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=kn(await Ec({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 mr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),yn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!kn(await Ny({message:"start the claim-loop now?",initialValue:!0}))){Oy("registered. start later with `codepipe worker`.");return}Oy("starting the claim-loop\u2026"),await eo(t.profile?{profile:t.profile}:{})}function QR(){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 W("PROFILE")}var ae=QR();Zl(ae);ru();var Ae=new XR;Ae.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Oe).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{Ji()?await fc({profile:ae}):await ac({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ae.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 gy({configPath:t.config,skipVerify:t.skipVerify===!0}):await iy({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.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 gu({...t,profile:ae})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.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 sy({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ae.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await _m({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ae.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 Ph({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.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 by({profile:ae,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await nh({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ae.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 ac({profile:ae,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var My=Ae.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");My.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??W("HUB_URL")??qe(ae)?.hubUrl??et,r=t.token??W("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ji()){await Ac({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=W("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??W("WORKER_NAME"),i=t.llm??W("WORKER_LLM");await mr({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)}});My.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!xe(ae)&&Ji()){await Ac({profile:ae});return}await eo(ae?{profile:ae}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Uy=Ae.command("project").description("Manage CodePipe projects");Uy.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Sy({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Uy.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 Ry({...t,cliProfile:ae})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Pc=Ae.command("repo").description("Manage the project's git repositories");Pc.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 Py({profile:ae,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Pc.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 _y({profile:ae,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Pc.command("list").description("List the project's repos").action(async()=>{try{await jy({profile:ae})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var By=Ae.command("model").description("Project map (model/ in the Context Repo)");By.command("build").description("Build the project map from the local repo clones' git history").option("--repo <name>","Build only this repo (logical name)").action(async t=>{try{await kc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});By.command("bootstrap").description("Build the map and mine task events from the whole git history (cold start)").option("--repo <name>","Bootstrap only this repo (logical name)").action(async t=>{try{await wc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ae.parseAsync();
|
|
863
|
+
`+(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 w=await XR({message:"Continue?",initialValue:!0});(QR(w)||!w)&&mt("aborted")}!c&&a===o&&Jt.warn(`source and destination share the same project id, so they share one secrets file (${ut(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:d,accountEmail:f}=await wn(i,p),m={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:f,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Jt.step(`registering project on ${i}\u2026`);let g;try{g=await Lt(i,d,m)}catch(w){if(w instanceof G&&w.status===409){Jt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await te(i,d,a)}catch(h){throw h instanceof G&&mt(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if(w instanceof G&&w.status===403)mt(`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(w instanceof G)mt(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}Jt.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),wt({hubUrl:i,cliToken:d,projectId:a,accountEmail:f},s);let k={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete k.sandboxPins,ee(k),Jt.success(`profile '${s}' \u2192 ${ut(a)}`),c){let w=tt(s);VR(w)&&(zR(w),Jt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}ZR(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Ne();ha();Xi();xe();Ur();ue();lt();import{existsSync as Mc,rmSync as tE,statSync as rE}from"node:fs";import{join as ns,relative as nE,resolve as oE}from"node:path";import{cancel as iE,intro as Hy,isCancel as sE,log as ge,outro as Wy,text as $r}from"@clack/prompts";import{simpleGit as Yy}from"simple-git";function De(t){iE(t),process.exit(1)}function vr(t){return sE(t)&&De("aborted"),typeof t=="string"?t:""}async function Gy(t){try{let e=await Yy(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function aE(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function cE(t,e){let r=Y(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(aE(r,e)){ge.message(`reusing existing ${e} credentials`);return}if(ge.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=vr(await $r({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=vr(await $r({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=vr(await $r({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}}ee(r),ge.success(`saved ${e} credentials`)}async function qy(t){let e=Ue(t.profile);Hy(`codepipe repo add \u2192 project ${e.projectId}`);let r=$e()??void 0,n;try{n=(await te(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){De(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await Gy(process.cwd());h?(o=process.cwd(),ge.message(`using the current directory (${h})`)):o=vr(await $r({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:v=>v.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Mc(o)&&rE(o).isDirectory()){i=oE(o);let h=await Gy(i);h||De(`${i} is not a git repository (no origin remote)`);let v=Ge(h);v||De(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=v,s=h,ge.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=Ge(o);h||De(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,ge.message(`${a}: ${c}/${l}`)}let u=vr(await $r({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:h=>h.trim()?void 0:"required"})).trim();n.some(h=>h.name===u)&&De(`a repo named "${u}" is already registered`);let p=vr(await $r({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=nE(r.root,i);d=h===""?".":h}let f=vr(await $r({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(h=>(h.mountAs??h.name)===f)&&De(`mount_as "${f}" is already used by another repo`),await cE(e,a);let m={name:u,host:a,owner:c,repoName:l,mountAs:f,...p?{defaultBranch:p}:{}};if(!i){let h=r?ns(r.root,f):Re(e.projectId,u);if(Mc(ns(h,".git")))ge.message(`already cloned at ${h}`);else{ge.info(`cloning ${s} \u2192 ${h} \u2026`);try{await Yy().clone(s,h),ge.success(`cloned into ${h}`)}catch(v){De(`clone failed: ${v instanceof Error?v.message.trim():String(v)}
|
|
864
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await Od(e.hubUrl,e.cliToken,e.projectId,m)}catch(h){h instanceof G&&De(`HUB \u2192 ${h.status} ${h.message}`),De(h instanceof Error?h.message:String(h))}let{updated:k,errors:w}=Yn(e.projectId,g.repos,r?.contextDir);for(let h of k)ge.message(`updated ${h}`);for(let h of w)ge.warn(`could not update ${h.path}: ${h.error}`);ge.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),Wy("done")}async function Vy(t){let e=Ue(t.profile);Hy(`codepipe repo remove \u2192 project ${e.projectId}`);let r=$e()??void 0,n;try{let c=(await te(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 Dd(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof G&&(a.status===404&&De(`no repo named "${t.name}" in this project`),De(`HUB \u2192 ${a.status} ${a.message}`)),De(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Yn(e.projectId,o.repos,r?.contextDir);for(let a of i)ge.message(`updated ${a}`);for(let a of s)ge.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ge.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?ns(r.root,n):Re(e.projectId,t.name);if(Mc(ns(a,".git")))try{tE(a,{recursive:!0,force:!0}),ge.message(`deleted local clone ${a}`)}catch(c){ge.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ge.message(`no local clone found to purge (${a})`)}ge.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Wy("done")}async function zy(t){let e=Ue(t.profile),r;try{r=(await te(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}`)}}Qi();wc();Tc();dn();K();Ae();dn();Ne();xe();uo();import{hostname as lE}from"node:os";import{cancel as uE,confirm as Xy,intro as dE,isCancel as Zy,log as $n,multiselect as pE,outro as Jy,password as fE,select as Uc,text as Bc}from"@clack/prompts";function ko(t){uE(t),process.exit(1)}function vn(t){return Zy(t)&&ko("aborted"),t}function os(t){return Zy(t)&&ko("aborted"),typeof t=="string"?t:""}function is(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Qy(t,e){try{let{secret:r}=await zo(t,e);return r}catch(r){throw r instanceof G&&r.status===404&&ko("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 mE(t,e){if(vn(await Uc({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 qs(t,e);if(o.length>0)return vn(await pE({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}));$n.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){$n.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return os(await Bc({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 Fc(t){dE("codepipe worker \u2014 set up this machine as a runner");let e=Ee(t.profile);e&&($n.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),vn(await Xy({message:"re-register this worker?",initialValue:!1}))||ko("keeping the existing registration"));let r=ze(t.profile)??ze(),n=os(await Bc({message:"HUB URL",placeholder:nt,initialValue:q("HUB_URL")??r?.hubUrl??nt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=vn(await Uc({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 Qy(n,a),$n.success("account-issued registration token minted");else if(i==="login"){let d=await kn();a=(await wn(n,d)).cliToken,s=await Qy(n,a),$n.success("account-issued registration token minted")}else s=os(await fE({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||ko("a registration token is required");let c=await mE(n,a),l=os(await Bc({message:"worker name",initialValue:lE(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=vn(await Uc({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 kr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),$n.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!vn(await Xy({message:"start the claim-loop now?",initialValue:!0}))){Jy("registered. start later with `codepipe worker`.");return}Jy("starting the claim-loop\u2026"),await ao(t.profile?{profile:t.profile}:{})}function hE(){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 q("PROFILE")}var de=hE();du(de);mu();var je=new gE;je.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Le).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{is()?await Sc({profile:de}):await kc({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});je.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 Py({configPath:t.config,skipVerify:t.skipVerify===!0}):await $y({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});je.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 Eu({...t,profile:de})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});je.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 vy({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});je.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Vm({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});je.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 qh({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});je.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 Dy({profile:de,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});je.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await wh({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});je.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 kc({profile:de,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var ek=je.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");ek.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??q("HUB_URL")??ze(de)?.hubUrl??nt,r=t.token??q("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&is()){await Fc({profile:de});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=q("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??q("WORKER_NAME"),i=t.llm??q("WORKER_LLM");await kr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...de?{profile:de}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ek.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Ee(de)&&is()){await Fc({profile:de});return}await ao(de?{profile:de}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var tk=je.command("project").description("Manage CodePipe projects");tk.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await By({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});tk.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 Ky({...t,cliProfile:de})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Kc=je.command("repo").description("Manage the project's git repositories");Kc.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 qy({profile:de,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Kc.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 Vy({profile:de,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Kc.command("list").description("List the project's repos").action(async()=>{try{await zy({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var rk=je.command("model").description("Project map (model/ in the Context Repo)");rk.command("build").description("Build the project map from the local repo clones' git history").option("--repo <name>","Build only this repo (logical name)").action(async t=>{try{await Cc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});rk.command("bootstrap").description("Build the map and mine task events from the whole git history (cold start)").option("--repo <name>","Bootstrap only this repo (logical name)").action(async t=>{try{await Ac({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});je.parseAsync();
|