@code-partner/codepipe 0.14.1-dev.292.g57527023 → 0.14.1-dev.294.gec9a7ae7
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 +194 -194
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var xv=Object.defineProperty;var S=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ge=(t,e)=>{for(var r in e)xv(t,r,{get:e[r],enumerable:!0})};var Xe,ft,ga=S(()=>{"use strict";Xe="0.14.1-dev.294.gec9a7ae7",ft="https://hub.dev.codepipe.dev"});function so(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=od&&t<=mt}var mt,od,id=S(()=>{"use strict";ga();mt=4,od=4});var sd=S(()=>{"use strict";ga()});function ao(t=6){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 wa(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 ba(t,e=ya){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 ka(t,e=ya){return e.filter(r=>r.version>t)}var ad,ht,en,ya,cd=S(()=>{"use strict";ad=6,ht=".codepipe-context.yaml",en=".devpipe-context.yaml",ya=[{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",ht]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[ht]},{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"]},{version:5,summary:"Roles: roles/ scaffold with the format README (override a bundled critic by name, or add your own)",addedPaths:["roles/README.md"]},{version:6,summary:"Skills: skills/ scaffold with the format README (procedures the agent invokes instead of improvising)",addedPaths:["skills/README.md"]}]});function lo(t){return`model/facts/identity/${t}.yaml`}function $r(t){return`model/facts/events/${t}.yaml`}function xa(t){return`model/facts/annotations/${t}.md`}function Sa(t){return`model/derived/correlates/${t}.yaml`}function Ea(t){return`model/derived/touched/${t}.yaml`}function ld(t){return t===""?"root":t.replace(/\//g,"-")}function Ra(t,e){return`model/derived/structure/${t}/${ld(e)}.yaml`}function fi(t){return typeof t=="string"&&dd.test(t)}function te(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(!ud.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Iv.includes(n)||i===""?null:{level:n,repo:o,path:i}}function xe(t){return`task::${t}`}function fe(t,e,r){return`${t}:${e}:${r}`}function uo(t){let e=[];return St(t)?(hi(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}Ta.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),te(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),te(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 pd(t){return{...t,edges:tn(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function xr(t){return Er(pd(t))}function St(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function hi(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function gt(t){return typeof t=="string"&&t.length>0}function Pv(t){return t.modelFormatVersion!==2}function Mt(t){let e=[];if(!St(t))return{ok:!1,errors:["shard: not an object"]};hi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),gt(t.repo)||e.push("repo: missing or empty"),gt(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=te(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&&!fi(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}Ta.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!gt(o.to)||!te(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!gt(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 po(t){let e=[];if(!St(t))return{ok:!1,errors:["identity: not an object"]};if(hi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),gt(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!gt(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}fi(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)})`),te(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),gt(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),gt(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!St(i)||!te(i.key)||!gt(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 Dt(t){let e=[];return St(t)?(hi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),gt(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=>!gt(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!St(r)||!te(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!fi(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 tn(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function fd(t){return{...t,nodes:tn(t.nodes,e=>e.key),edges:tn(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function md(t){return{...t,entities:tn(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:tn(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function hd(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:tn(t.files,r=>r.key),...e?{links:e}:{}}}function co(t){return _v.test(t)?t:JSON.stringify(t)}function gd(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 yd(t){return t===null||["boolean","number","string"].includes(typeof t)}function va(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function wd(t,e,r){if(Array.isArray(t)){for(let n of t)if(yd(n))r.push(`${e}- ${gd(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=va(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;$a(i,s,c,`${e} `,r)})}}return}for(let[n,o]of va(t))$a(n,o,e,e,r)}function $a(t,e,r,n,o){if(yd(e))o.push(`${r}${co(t)}: ${gd(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${co(t)}: []`):(o.push(`${r}${co(t)}:`),wd(e,`${n} `,o));else{let i=va(e);if(i.length===0)o.push(`${r}${co(t)}: {}`);else{o.push(`${r}${co(t)}:`);for(let[s,a]of i)$a(s,a,`${n} `,`${n} `,o)}}}function Er(t){let e=[];return wd(t,"",e),e.join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`}function _a(t){return Sr(pd(t))}function Aa(t){return Sr(fd(t))}function tn(t){return Sr(md(t))}var Me,xv,Sv,Ev,Tv,di,kr,ld,Ta,ud,Rv,ot,Ra,Ia,Ca,fi,Iv,Pa,xr,Pv,ja=S(()=>{"use strict";Me=2,xv="model",Sv="model/README.md",Ev="model/facts",Tv="model/derived",di="model/derived/INDEX.yaml",kr="model/derived/relates.yaml";ld=["system","container","component","code","task","adr"],Ta=["contains","touched_by","correlates","relates","references","depends_on"],ud=/^e_[0-9a-f]{8}$/;Rv=["system","task","adr"];ot={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Ra=2,Ia=5,Ca=50,fi=2e3,Iv=5e4,Pa={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},xr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};Pv=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function _v(t){return t==="DONE"}function Av(t){return t==="AWAITING_EXTERNAL_FIX"?!1:Na.indexOf(t)>=Na.indexOf("IMPLEMENTING")}var Na,wd=S(()=>{"use strict";Na=["BACKLOG","QUEUED","INTAKE","AWAITING_APPROVAL","ANALYZING","ESTIMATING","AWAITING_ANSWER","REVIEW","READY","IMPLEMENTING","BUILD","CODE_REVIEW","TESTING","AWAITING_EXTERNAL_FIX","READY_TO_APPLY","APPLYING","AWAITING_CLUSTER","TRACKING","NEEDS_MANUAL","DONE"]});function Nv(t){for(let e of Oa)if(e.phases.includes(t))return e.id;return null}function Ov(t){for(let e of bd)if(e.phases.includes(t))return e.id;return null}var Oa,jv,bd,kd=S(()=>{"use strict";Oa=[{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"]}],jv=Oa.flatMap(t=>t.phases),bd=[{id:"review",label:"Review / tracking",phases:["CODE_REVIEW","TESTING","TRACKING"]},{id:"attention",label:"Need your attention",phases:["NEEDS_MANUAL","AWAITING_APPROVAL","AWAITING_EXTERNAL_FIX","AWAITING_ANSWER","REVIEW"]},{id:"backlog",label:"Backlog / queue",phases:["BACKLOG","QUEUED"]}]});function Ma(t){return $d.includes(t)}function Lv(t){return vd.includes(t)?"planning":"implementation"}function Ut(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var La,vd,$d,Mv,Da=S(()=>{"use strict";La=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","config","observer","council","testing"],vd=["draft","analysis","chat","config","observer","council"],$d=["chat","config"];Mv=1});function xd(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Ba(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Cd.every(o=>e.some(i=>xd(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 Id){let i=n.find(s=>xd(o,s.id));if(i)return i.id}return n[0].id}function rn(){return{default:null,roles:{}}}function Dv(t,e){let r=t?.roles?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():t?.default&&t.default.trim().length>0?t.default.trim():uo[e]??Rd}function Uv(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Ze}function Bv(t){let e=rn();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.provider;typeof n=="string"&&n.trim().length>0&&(e.provider=n.trim());let o=r.models;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o))typeof s!="string"||s.trim().length===0||(i==="default"?e.default=s.trim():e.roles[i]=s.trim());return e}function nn(){return{default:null,roles:{}}}function Fv(t,e){let r=t?.roles?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():t?.default&&t.default.trim().length>0?t.default.trim():po[e]}function Gv(t){let e=nn();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.effort;if(!n||typeof n!="object")return e;for(let[o,i]of Object.entries(n))typeof i!="string"||i.trim().length===0||(o==="default"?e.default=i.trim():e.roles[o]=i.trim());return e}function Kv(t){return t.default===null&&Object.keys(t.roles).length===0?null:JSON.stringify(t)}function Hv(t){if(!t)return nn();try{let e=JSON.parse(t);if(!e||typeof e!="object")return nn();let r=e,n=nn();typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return nn()}}function Wv(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Ze;if(t.default===null&&Object.keys(t.roles).length===0&&!e)return null;let{provider:r,...n}=t;return JSON.stringify(e?{provider:r.trim(),...n}:n)}function qv(t){if(!t)return rn();try{let e=JSON.parse(t);if(!e||typeof e!="object")return rn();let r=e,n=rn();typeof r.provider=="string"&&r.provider.trim().length>0&&(n.provider=r.provider.trim()),typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return rn()}}var Ze,Ua,Ie,on,hi,gi,Sd,Ed,Td,yi,uo,Rd,Id,Cd,Pd,wi,po,Fa=S(()=>{"use strict";Da();Ze="claude",Ua=[Ze],Ie="opus",on="sonnet",hi="haiku",gi=[Ie,on,hi],Sd="build-discovery",Ed="code-review-verify",Td=[Sd,Ed],yi=[...La,...Td],uo={analyze:Ie,implement:Ie,"resolve-conflict":Ie,rework:Ie,estimate:on,build:hi,"build-discovery":Ie,"code-review":Ie,"code-review-verify":on,draft:on,index:Ie,backfill:Ie,analysis:Ie,chat:Ie,config:Ie,observer:Ie,council:Ie,testing:Ie},Rd=Ie,Id=[Ie,on,hi],Cd=Array.from(new Set(Object.values(uo)));Pd=["low","medium","high","xhigh"],wi=Pd,po={build:"low",estimate:"low",draft:"medium",index:"medium","code-review-verify":"medium"}});function Bt(t){return Yv.has(t)?!0:Vv.some(e=>t.startsWith(e))}function bi(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Er(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Ka(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Wa(t,e){let r=bi(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Er(r.id,"id")??n;if(!Ga.test(o))throw new Error(`id must match ${Ga} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Er(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=bi(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Qe.test(d))throw new Error(`env name "${d}" must match ${Qe}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>_d)throw new Error(`too many params (max ${_d})`);let p=new Set;a=c.map((d,m)=>zv(d,m,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>Ad)throw new Error(`too many steps (max ${Ad})`);let u=l.map((p,d)=>{let m=bi(p,`steps[${d}]`),f=Er(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let y=Er(m.name,`steps[${d}].name`),w=Ka(m.timeout_sec,`steps[${d}].timeout_sec`);if(w!==void 0&&(!Number.isInteger(w)||w<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...y?{name:y}:{},...w!==void 0?{timeout_sec:w}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function zv(t,e,r){let n=bi(t,`params[${e}]`),o=Er(n.name,`params[${e}].name`);if(!o||!Qe.test(o))throw new Error(`params[${e}].name must match ${Qe}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=Er(n.label,`params[${e}].label`),c=Er(n.help,`params[${e}].help`),l=n.required===!0,u=Ka(n.min,`params[${e}].min`),p=Ka(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 qa(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 Qe,Yv,Vv,Ha,Ga,_d,Ad,Ya=S(()=>{"use strict";Qe=/^[A-Z][A-Z0-9_]*$/,Yv=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Vv=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ha=600,Ga=/^[a-z0-9-]+$/,_d=32,Ad=64});function jd(){return{primary:ge,context:ge,tasks:ge,docs:ge,code_comments:ge,chat:ge,code_review:ge,commits:ge}}function Nd(t){return!t||t.trim().length===0||t.trim().toLowerCase()===ge}function Xv(t){if(typeof t!="string")return ge;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===ge?ge:e}function Jv(t){let e=jd();if(!t||typeof t!="object")return e;let r=t.language;if(!r||typeof r!="object"||Array.isArray(r))return e;let n=r;for(let o of fo)e[o]=Xv(n[o]);return e}function Zv(t){return fo.every(e=>Nd(t[e]))}var ge,fo,sn,mo,Va=S(()=>{"use strict";ge="auto",fo=["primary","context","tasks","docs","code_comments","chat","code_review","commits"],sn=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],mo=40});function Za(t=Od){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Za(r.groups));return e}function Ld(t,e){let r=JSON.stringify(e);return Za().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Qa(t){let e=Ld(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)?{ok:!1,error:`${e.id} must be a number`}:!e.float&&!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>za)return{ok:!1,error:`${e.id} must have \u2264 ${za} entries`};let s={};for(let[a,c]of i){if(!Qe.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Qe}`};if(Bt(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>Xa)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Xa} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Qv,e$,za,Xa,Ja,Od,Md=S(()=>{"use strict";Ya();Fa();ja();Va();Qv={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat",code_review:"Code review comments",commits:"Commits & branches"},e$={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages.",code_review:"Review findings and PR comments. Empty \u21D2 follows the tracker-issues language.",commits:"Commit/PR subject & branch slug. Empty \u21D2 follows the tracker-issues language."},za=64,Xa=2e3,Ja=2e3,Od=[{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:[...Ua],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:[...gi],help:"Overrides the recommended defaults for every role not listed below."},...yi.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...gi],help:`recommended: ${uo[t]}`}))]},{id:"llm.effort",label:"Reasoning effort by role",help:"Reasoning effort per pipeline stage (Claude Code --effort). Empty \u21D2 the mechanical roles run lowered (build/estimate: low; draft/index/code-review-verify: medium) and every other role keeps the backend default.",fields:[{id:"llm.effort.default",file:"regimen.yaml",path:["llm","effort","default"],type:"enum",label:"default (catch-all)",nullable:!0,suggestions:[...wi],help:"Overrides the recommended lowerings for every role not listed below."},...yi.map(t=>({id:`llm.effort.${t}`,file:"regimen.yaml",path:["llm","effort",t],type:"enum",label:t,nullable:!0,suggestions:[...wi],help:po[t]?`recommended: ${po[t]}`:"recommended: backend default"}))]}]},{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:Ja,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:Ja,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{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:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"code_review",label:"Code review",help:"One review mechanism for the pipeline's own changes and for developers' branches (the review column); they differ only in where the findings go.",fields:[{id:"code_review.verify_pass",file:"regimen.yaml",path:["code_review","verify_pass"],type:"boolean",nullable:!1,label:"Verifier pass (precision)",help:"On by default, paired with the critics panel. A second, narrow agent checks every finding against the code (real? re-grade) before it costs a rework round or reaches a developer; the findings threshold below keeps small rounds cheap."},{id:"code_review.panel",file:"regimen.yaml",path:["code_review","panel"],type:"boolean",nullable:!1,label:"Critics panel",help:"On by default. The reviewer delegates to the project's critic roles (roles/ in the Context Repo, or the bundled set) as parallel subagents before its own pass. Cost grows with the number of roles."},{id:"code_review.verify_min_findings",file:"regimen.yaml",path:["code_review","verify_min_findings"],type:"number",nullable:!0,min:1,label:"Verifier threshold (findings)",help:"The verifier runs only when a round carries at least this many actionable findings \u2014 1-2 are cheap to absorb, noise scales with volume. Empty = 3; 1 = verify every round."},{id:"code_review.max_blocking",file:"regimen.yaml",path:["code_review","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (internal)",help:"Max blocker findings that keep their power in the pipeline's own review; the rest are demoted to major, weakest confidence first. Empty = 5."},{id:"code_review.external.max_blocking",file:"regimen.yaml",path:["code_review","external","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (external)",help:"The same budget for a developer's branch review \u2014 tighter by default because a human reads these. Empty = 3."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"quality",label:"Quality block",help:"Skip the whole quality block (build + code review) when a change touches only safe paths.",fields:[{id:"quality.skip_paths",file:"regimen.yaml",path:["quality","skip_paths"],type:"string_list",nullable:!0,label:"Skip paths (gitignore-style)",help:"When every changed file across all repos matches these globs, build and code review are skipped and the change goes straight to apply. One file outside the list runs both as usual. Use ! to re-include (e.g. !schema/**/*.md). Empty = never skip."}]},{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:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:fo.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:Qv[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[ge,...sn]:[...sn],help:e$[t]}))},{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:"On by default. Agents are asked to record intent annotations and receive an assembled context pack built from the project map. Off \u21D2 the pipeline ignores the map entirely and behaves exactly as if the feature were absent."},{id:"context.model.pack.idf_penalty",file:"regimen.yaml",path:["context","model","pack","idf_penalty"],type:"boolean",label:"Demote ubiquitous files in the pack",nullable:!1,help:"On by default. Files that reached the pack only through STATISTICAL co-change (not direct task evidence) are ranked down in proportion to how many past tasks touched them, so the budget goes to task-specific paths. Off restores pure activation order."},{id:"context.model.prompt.pack",file:"regimen.yaml",path:["context","model","prompt","pack"],type:"boolean",nullable:!1,label:"Give agents the context pack",help:"On by default. The assembled pack costs up to ~4000 tokens on every task of the analyze / estimate / implement / rework roles. Turning it off keeps the map building and stops the spend \u2014 the way to see what the pack is actually worth on this project."},{id:"context.model.prompt.annotations",file:"regimen.yaml",path:["context","model","prompt","annotations"],type:"boolean",nullable:!1,label:"Ask agents for intent annotations",help:"On by default. Adds the annotations block to the implement and rework prompts \u2014 the layer that records WHY the code is shaped this way. Cheap, and worth accumulating even while the pack is off."},{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 ${ot.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 ${ot.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 ${ot.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 ${ot.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 ${ot.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 ${ot.topK}.`}]},{id:"rate_limit",label:"Rate limit",help:"Automatic project pause as the LLM usage window fills up.",fields:[{id:"rate_limit.auto_pause.enabled",file:"project.yaml",path:["rate_limit","auto_pause","enabled"],type:"boolean",nullable:!1,label:"Pause the project near the limit",help:"On (default): when window utilization reaches the threshold, the project is paused (same pause as the manual one) and you get an email \u2014 the remaining window stays available for your own work. Off: agents keep working until the provider actually runs out."},{id:"rate_limit.auto_pause.threshold",file:"project.yaml",path:["rate_limit","auto_pause","threshold"],type:"number",float:!0,nullable:!0,min:.05,max:1,label:"Pause threshold (share of the window)",help:"Fraction of the usage window at which the pause fires; the rest (1 \u2212 threshold) is your manual-work reserve. Empty \u21D2 0.75."}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});var Dd=S(()=>{"use strict"});function Ud(t){if(t==null)return[];if(!Array.isArray(t))return null;let e=[];for(let r of t){if(typeof r!="string"||r.trim().length===0)return null;e.push(r.trim())}return e}function tc(t){let{name:e,body:r,origin:n}=t;if(!ec.test(e))return{ok:!1,error:`role name must match ${ec} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let i=o,s=i.description;if(typeof s!="string"||s.trim().length===0)return{ok:!1,error:"description is required (one line: what this role looks for)"};if(s.length>300)return{ok:!1,error:"description must be \u2264 300 characters"};let a=Ud(i.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let d of a)if(d.startsWith("/")||d.includes(".."))return{ok:!1,error:`ref "${d}" must be a path inside the Context Repo`};let c=Ud(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!ki.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${ki.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${ki.join(", ")}`};let u=i.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=i.enabled;return p!==void 0&&typeof p!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:s.trim(),...typeof u=="string"?{model:u.trim()}:{},refs:a,scenarios:l,enabled:p!==!1,body:r.trim(),origin:n}}}function rc(t,e){let r=new Map;for(let n of t)r.set(n.name,n);for(let n of e)r.set(n.name,n);return[...r.values()].sort((n,o)=>n.name<o.name?-1:n.name>o.name?1:0)}function nc(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var ki,ec,fj,mj,Bd=S(()=>{"use strict";ki=["plan_review","code_review","council"],ec=/^[a-z][a-z0-9-]{1,39}$/,fj=10,mj=300});function oc(t){return Fd.includes(t)}function ic(t){return`prompts/${t}.md`}var Fd,Gd=S(()=>{"use strict";Fd=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","code-review-verify","config","council","draft","estimate","implement","index","observer","resolve-conflict","review-comment","rework","testing"]});function ac(t){if(!sc.test(t.name))return{ok:!1,error:`skill directory name must match ${sc}`};if(t.body.trim().length===0)return{ok:!1,error:"SKILL.md has no body \u2014 the body IS the procedure"};let e=t.frontmatter;if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"SKILL.md has no frontmatter block"};let r=e.description;return typeof r!="string"||r.trim().length===0?{ok:!1,error:"description is required \u2014 it is what decides when the skill fires"}:r.length>300?{ok:!1,error:"description must be \u2264 300 characters"}:{ok:!0,skill:{name:t.name,description:r.trim()}}}function cc(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}function Hd(t){let e=t.trim(),r=e.lastIndexOf("@"),n=r===-1?e:e.slice(0,r),o=r===-1?"":e.slice(r+1).trim();if(!t$.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let i=Kd.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!r$.test(o)?{ok:!1,error:`"${t}": pin to a full 40-character commit sha \u2014 a branch or tag can change under you`}:!i&&!o?{ok:!1,error:`"${t}": a third-party marketplace must be pinned to a commit (<owner>/<repo>@<sha>). Its skills run beside your code with the agent's token.`}:{ok:!0,source:{repo:n,sha:o,name:i?.name??n.replace("/","-").toLowerCase(),official:!!i}}}function n$(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=Hd(o);if(!i.ok){r.push(i.error);continue}n.has(i.source.name)||(n.add(i.source.name),e.push(i.source))}return{sources:e,errors:r}}function i$(t,e){let r=new Set(e.map(i=>i.name)),n={},o=[];for(let i of t){let s=i.trim();if(s){if(!o$.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var sc,yj,Kd,t$,r$,o$,Wd=S(()=>{"use strict";sc=/^[a-z][a-z0-9-]{1,39}$/,yj=300;Kd=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],t$=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,r$=/^[0-9a-f]{40}$/;o$=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function qd(t,e){if(t==null)return[];if(!Array.isArray(t)||t.length>e)return null;let r=[];for(let n of t){if(typeof n!="string"||n.trim().length===0)return null;r.push(n.trim())}return r}function s$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"queue plan must be a JSON object"};let r=new Set(e),n=t,o=qd(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let f of o)if(!r.has(f))return{ok:!1,error:`order names ${f}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let i=e.filter(f=>!o.includes(f));if(o.length>0&&i.length>0)return{ok:!1,error:`order omits ${i.join(", ")}`};let s=n.tasks,a=[];if(s!=null){if(!Array.isArray(s))return{ok:!1,error:"tasks must be a list"};for(let f of s){if(!f||typeof f!="object")return{ok:!1,error:"each task entry must be an object"};let y=f,w=typeof y.taskKey=="string"?y.taskKey.trim():"";if(!r.has(w))return{ok:!1,error:`tasks names ${w||"(empty)"}, which is not in this batch`};let h=qd(y.after,e.length);if(h===null)return{ok:!1,error:`${w}: after must be a list of task keys`};for(let x of h){if(!r.has(x))return{ok:!1,error:`${w}: after names ${x}, not in this batch`};if(x===w)return{ok:!1,error:`${w}: cannot come after itself`}}let k=typeof y.decisions=="string"?y.decisions.trim():"";a.push({taskKey:w,decisions:k.slice(0,4e3),after:h})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let y=f,w=typeof y.taskKey=="string"?y.taskKey.trim():"",h=typeof y.adr=="string"?y.adr.trim():"",k=typeof y.detail=="string"?y.detail.trim():"";!r.has(w)||!k||c.push({taskKey:w,adr:h,detail:k.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let f of p){if(!f||typeof f!="object")continue;let y=f,w=typeof y.taskKey=="string"?y.taskKey.trim():"",h=typeof y.detail=="string"?y.detail.trim():"";!w||!h||u.push({taskKey:w,detail:h.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",m=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:m}}}var bj,kj,Yd=S(()=>{"use strict";bj=4e3,kj=4e3});function a$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"council verdict must be a JSON object"};let r=t,n=r.unresolved===!0,o=typeof r.fork=="string"?r.fork.trim().slice(0,4e3):"";if(n)return o?{ok:!0,verdict:{answers:[],unresolved:!0,fork:o}}:{ok:!1,error:"an unresolved verdict must describe the fork"};let i=r.answers;if(!Array.isArray(i))return{ok:!1,error:"answers must be a list"};if(i.length!==e.length)return{ok:!1,error:`expected ${e.length} answer(s), got ${i.length}`};let s=[];for(let[a,c]of i.entries()){if(!c||typeof c!="object")return{ok:!1,error:`answer ${a+1} must be an object`};let l=c,u=typeof l.answer=="string"?l.answer.trim():"";if(!u)return{ok:!1,error:`answer ${a+1} is empty`};s.push({question:typeof l.question=="string"?l.question.trim():e[a],answer:u.slice(0,4e3),rationale:typeof l.rationale=="string"?l.rationale.trim().slice(0,4e3):""})}return{ok:!0,verdict:{answers:s,unresolved:!1,fork:""}}}var $j,Vd=S(()=>{"use strict";$j=4e3});function u$(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of c$)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function lc(t){let e=[],r=new Map,n="",o=null,i=null;for(let a of t.split(`
|
|
8
|
-
`)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=
|
|
9
|
-
${a.trim()}`.trim();continue}a.trim()||(i=null)}let s=[...r.entries()].filter(([,a])=>a>1).map(([a])=>a);return{items:e,structured:e.length>=2&&s.length===0,duplicateIds:s}}function
|
|
7
|
+
`}function Aa(t){return Er(fd(t))}function ja(t){return Er(md(t))}function rn(t){return Er(hd(t))}var Le,Sv,Ev,Rv,Tv,pi,vr,ud,Ta,dd,Iv,ot,Ia,Ca,Pa,mi,Cv,_a,Sr,_v,Na=S(()=>{"use strict";Le=2,Sv="model",Ev="model/README.md",Rv="model/facts",Tv="model/derived",pi="model/derived/INDEX.yaml",vr="model/derived/relates.yaml";ud=["system","container","component","code","task","adr"],Ta=["contains","touched_by","correlates","relates","references","depends_on"],dd=/^e_[0-9a-f]{8}$/;Iv=["system","task","adr"];ot={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Ia=2,Ca=5,Pa=50,mi=2e3,Cv=5e4,_a={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},Sr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};_v=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function Av(t){return t==="DONE"}function jv(t){return t==="AWAITING_EXTERNAL_FIX"?!1:Oa.indexOf(t)>=Oa.indexOf("IMPLEMENTING")}var Oa,bd=S(()=>{"use strict";Oa=["BACKLOG","QUEUED","INTAKE","AWAITING_APPROVAL","ANALYZING","ESTIMATING","AWAITING_ANSWER","REVIEW","READY","IMPLEMENTING","BUILD","CODE_REVIEW","TESTING","AWAITING_EXTERNAL_FIX","READY_TO_APPLY","APPLYING","AWAITING_CLUSTER","TRACKING","NEEDS_MANUAL","DONE"]});function Ov(t){for(let e of La)if(e.phases.includes(t))return e.id;return null}function Lv(t){for(let e of kd)if(e.phases.includes(t))return e.id;return null}var La,Nv,kd,vd=S(()=>{"use strict";La=[{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"]}],Nv=La.flatMap(t=>t.phases),kd=[{id:"review",label:"Review / tracking",phases:["CODE_REVIEW","TESTING","TRACKING"]},{id:"attention",label:"Need your attention",phases:["NEEDS_MANUAL","AWAITING_APPROVAL","AWAITING_EXTERNAL_FIX","AWAITING_ANSWER","REVIEW"]},{id:"backlog",label:"Backlog / queue",phases:["BACKLOG","QUEUED"]}]});function Da(t){return xd.includes(t)}function Mv(t){return $d.includes(t)?"planning":"implementation"}function Ut(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ma,$d,xd,Dv,Ua=S(()=>{"use strict";Ma=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","config","observer","council","testing"],$d=["draft","analysis","chat","config","observer","council"],xd=["chat","config"];Dv=1});function Sd(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Fa(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Pd.every(o=>e.some(i=>Sd(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 Cd){let i=n.find(s=>Sd(o,s.id));if(i)return i.id}return n[0].id}function nn(){return{default:null,roles:{}}}function Uv(t,e){let r=t?.roles?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():t?.default&&t.default.trim().length>0?t.default.trim():fo[e]??Id}function Bv(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():Je}function Fv(t){let e=nn();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.provider;typeof n=="string"&&n.trim().length>0&&(e.provider=n.trim());let o=r.models;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o))typeof s!="string"||s.trim().length===0||(i==="default"?e.default=s.trim():e.roles[i]=s.trim());return e}function on(){return{default:null,roles:{}}}function Gv(t,e){let r=t?.roles?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():t?.default&&t.default.trim().length>0?t.default.trim():mo[e]}function Kv(t){let e=on();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.effort;if(!n||typeof n!="object")return e;for(let[o,i]of Object.entries(n))typeof i!="string"||i.trim().length===0||(o==="default"?e.default=i.trim():e.roles[o]=i.trim());return e}function Hv(t){return t.default===null&&Object.keys(t.roles).length===0?null:JSON.stringify(t)}function Wv(t){if(!t)return on();try{let e=JSON.parse(t);if(!e||typeof e!="object")return on();let r=e,n=on();typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return on()}}function qv(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==Je;if(t.default===null&&Object.keys(t.roles).length===0&&!e)return null;let{provider:r,...n}=t;return JSON.stringify(e?{provider:r.trim(),...n}:n)}function Yv(t){if(!t)return nn();try{let e=JSON.parse(t);if(!e||typeof e!="object")return nn();let r=e,n=nn();typeof r.provider=="string"&&r.provider.trim().length>0&&(n.provider=r.provider.trim()),typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return nn()}}var Je,Ba,Re,sn,gi,yi,Ed,Rd,Td,wi,fo,Id,Cd,Pd,_d,bi,mo,Ga=S(()=>{"use strict";Ua();Je="claude",Ba=[Je],Re="opus",sn="sonnet",gi="haiku",yi=[Re,sn,gi],Ed="build-discovery",Rd="code-review-verify",Td=[Ed,Rd],wi=[...Ma,...Td],fo={analyze:Re,implement:Re,"resolve-conflict":Re,rework:Re,estimate:sn,build:gi,"build-discovery":Re,"code-review":Re,"code-review-verify":sn,draft:sn,index:Re,backfill:Re,analysis:Re,chat:Re,config:Re,observer:Re,council:Re,testing:Re},Id=Re,Cd=[Re,sn,gi],Pd=Array.from(new Set(Object.values(fo)));_d=["low","medium","high","xhigh"],bi=_d,mo={build:"low",estimate:"low",draft:"medium",index:"medium","code-review-verify":"medium"}});function Bt(t){return Vv.has(t)?!0:zv.some(e=>t.startsWith(e))}function ki(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Rr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Ha(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function qa(t,e){let r=ki(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Rr(r.id,"id")??n;if(!Ka.test(o))throw new Error(`id must match ${Ka} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Rr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=ki(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Ze.test(d))throw new Error(`env name "${d}" must match ${Ze}`);if(typeof m!="string"&&typeof m!="number"&&typeof m!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(m)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Ad)throw new Error(`too many params (max ${Ad})`);let p=new Set;a=c.map((d,m)=>Xv(d,m,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>jd)throw new Error(`too many steps (max ${jd})`);let u=l.map((p,d)=>{let m=ki(p,`steps[${d}]`),f=Rr(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=Rr(m.name,`steps[${d}].name`),w=Ha(m.timeout_sec,`steps[${d}].timeout_sec`);if(w!==void 0&&(!Number.isInteger(w)||w<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...g?{name:g}:{},...w!==void 0?{timeout_sec:w}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function Xv(t,e,r){let n=ki(t,`params[${e}]`),o=Rr(n.name,`params[${e}].name`);if(!o||!Ze.test(o))throw new Error(`params[${e}].name must match ${Ze}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let m=n.enum;if(!Array.isArray(m)||m.length===0||!m.every(f=>typeof f=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=m}let a=Rr(n.label,`params[${e}].label`),c=Rr(n.help,`params[${e}].help`),l=n.required===!0,u=Ha(n.min,`params[${e}].min`),p=Ha(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 Ya(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 Ze,Vv,zv,Wa,Ka,Ad,jd,Va=S(()=>{"use strict";Ze=/^[A-Z][A-Z0-9_]*$/,Vv=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),zv=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Wa=600,Ka=/^[a-z0-9-]+$/,Ad=32,jd=64});function Nd(){return{primary:me,context:me,tasks:me,docs:me,code_comments:me,chat:me,code_review:me,commits:me}}function Od(t){return!t||t.trim().length===0||t.trim().toLowerCase()===me}function Jv(t){if(typeof t!="string")return me;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===me?me:e}function Zv(t){let e=Nd();if(!t||typeof t!="object")return e;let r=t.language;if(!r||typeof r!="object"||Array.isArray(r))return e;let n=r;for(let o of ho)e[o]=Jv(n[o]);return e}function Qv(t){return ho.every(e=>Od(t[e]))}var me,ho,an,go,za=S(()=>{"use strict";me="auto",ho=["primary","context","tasks","docs","code_comments","chat","code_review","commits"],an=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],go=40});function Qa(t=Ld){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Qa(r.groups));return e}function Md(t,e){let r=JSON.stringify(e);return Qa().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function ec(t){let e=Md(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)?{ok:!1,error:`${e.id} must be a number`}:!e.float&&!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>Xa)return{ok:!1,error:`${e.id} must have \u2264 ${Xa} entries`};let s={};for(let[a,c]of i){if(!Ze.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Ze}`};if(Bt(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>Ja)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Ja} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var e$,t$,Xa,Ja,Za,Ld,Dd=S(()=>{"use strict";Va();Ga();Na();za();e$={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat",code_review:"Code review comments",commits:"Commits & branches"},t$={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages.",code_review:"Review findings and PR comments. Empty \u21D2 follows the tracker-issues language.",commits:"Commit/PR subject & branch slug. Empty \u21D2 follows the tracker-issues language."},Xa=64,Ja=2e3,Za=2e3,Ld=[{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:[...Ba],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:[...yi],help:"Overrides the recommended defaults for every role not listed below."},...wi.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...yi],help:`recommended: ${fo[t]}`}))]},{id:"llm.effort",label:"Reasoning effort by role",help:"Reasoning effort per pipeline stage (Claude Code --effort). Empty \u21D2 the mechanical roles run lowered (build/estimate: low; draft/index/code-review-verify: medium) and every other role keeps the backend default.",fields:[{id:"llm.effort.default",file:"regimen.yaml",path:["llm","effort","default"],type:"enum",label:"default (catch-all)",nullable:!0,suggestions:[...bi],help:"Overrides the recommended lowerings for every role not listed below."},...wi.map(t=>({id:`llm.effort.${t}`,file:"regimen.yaml",path:["llm","effort",t],type:"enum",label:t,nullable:!0,suggestions:[...bi],help:mo[t]?`recommended: ${mo[t]}`:"recommended: backend default"}))]}]},{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:Za,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:Za,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{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:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"code_review",label:"Code review",help:"One review mechanism for the pipeline's own changes and for developers' branches (the review column); they differ only in where the findings go.",fields:[{id:"code_review.verify_pass",file:"regimen.yaml",path:["code_review","verify_pass"],type:"boolean",nullable:!1,label:"Verifier pass (precision)",help:"On by default, paired with the critics panel. A second, narrow agent checks every finding against the code (real? re-grade) before it costs a rework round or reaches a developer; the findings threshold below keeps small rounds cheap."},{id:"code_review.panel",file:"regimen.yaml",path:["code_review","panel"],type:"boolean",nullable:!1,label:"Critics panel",help:"On by default. The reviewer delegates to the project's critic roles (roles/ in the Context Repo, or the bundled set) as parallel subagents before its own pass. Cost grows with the number of roles."},{id:"code_review.verify_min_findings",file:"regimen.yaml",path:["code_review","verify_min_findings"],type:"number",nullable:!0,min:1,label:"Verifier threshold (findings)",help:"The verifier runs only when a round carries at least this many actionable findings \u2014 1-2 are cheap to absorb, noise scales with volume. Empty = 3; 1 = verify every round."},{id:"code_review.max_blocking",file:"regimen.yaml",path:["code_review","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (internal)",help:"Max blocker findings that keep their power in the pipeline's own review; the rest are demoted to major, weakest confidence first. Empty = 5."},{id:"code_review.external.max_blocking",file:"regimen.yaml",path:["code_review","external","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (external)",help:"The same budget for a developer's branch review \u2014 tighter by default because a human reads these. Empty = 3."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"quality",label:"Quality block",help:"Skip the whole quality block (build + code review) when a change touches only safe paths.",fields:[{id:"quality.skip_paths",file:"regimen.yaml",path:["quality","skip_paths"],type:"string_list",nullable:!0,label:"Skip paths (gitignore-style)",help:"When every changed file across all repos matches these globs, build and code review are skipped and the change goes straight to apply. One file outside the list runs both as usual. Use ! to re-include (e.g. !schema/**/*.md). Empty = never skip."}]},{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), the observer's intake plan waits for your APPROVE & START before the batch runs. Off \u21D2 conveyor: the batch starts automatically on the observer's plan. Either way every task passes the observer intake first."},{id:"observer.debounce_seconds",file:"regimen.yaml",path:["observer","debounce_seconds"],type:"number",label:"Intake window (seconds)",nullable:!0,min:5,max:3600,help:"How long the queue collects newly staged tasks before the observer reviews them as one batch. Empty \u21D2 60."},{id:"observer.fast_path",file:"regimen.yaml",path:["observer","fast_path"],type:"boolean",label:"Fast path for trivial tasks",nullable:!1,help:"On by default. A single small task with no links skips the observer's LLM pass and is routed by rules (noted in its journal as routed without review)."}]},{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:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:ho.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:e$[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[me,...an]:[...an],help:t$[t]}))},{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:"On by default. Agents are asked to record intent annotations and receive an assembled context pack built from the project map. Off \u21D2 the pipeline ignores the map entirely and behaves exactly as if the feature were absent."},{id:"context.model.pack.idf_penalty",file:"regimen.yaml",path:["context","model","pack","idf_penalty"],type:"boolean",label:"Demote ubiquitous files in the pack",nullable:!1,help:"On by default. Files that reached the pack only through STATISTICAL co-change (not direct task evidence) are ranked down in proportion to how many past tasks touched them, so the budget goes to task-specific paths. Off restores pure activation order."},{id:"context.model.prompt.pack",file:"regimen.yaml",path:["context","model","prompt","pack"],type:"boolean",nullable:!1,label:"Give agents the context pack",help:"On by default. The assembled pack costs up to ~4000 tokens on every task of the analyze / estimate / implement / rework roles. Turning it off keeps the map building and stops the spend \u2014 the way to see what the pack is actually worth on this project."},{id:"context.model.prompt.annotations",file:"regimen.yaml",path:["context","model","prompt","annotations"],type:"boolean",nullable:!1,label:"Ask agents for intent annotations",help:"On by default. Adds the annotations block to the implement and rework prompts \u2014 the layer that records WHY the code is shaped this way. Cheap, and worth accumulating even while the pack is off."},{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 ${ot.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 ${ot.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 ${ot.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 ${ot.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 ${ot.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 ${ot.topK}.`}]},{id:"rate_limit",label:"Rate limit",help:"Automatic project pause as the LLM usage window fills up.",fields:[{id:"rate_limit.auto_pause.enabled",file:"project.yaml",path:["rate_limit","auto_pause","enabled"],type:"boolean",nullable:!1,label:"Pause the project near the limit",help:"On (default): when window utilization reaches the threshold, the project is paused (same pause as the manual one) and you get an email \u2014 the remaining window stays available for your own work. Off: agents keep working until the provider actually runs out."},{id:"rate_limit.auto_pause.threshold",file:"project.yaml",path:["rate_limit","auto_pause","threshold"],type:"number",float:!0,nullable:!0,min:.05,max:1,label:"Pause threshold (share of the window)",help:"Fraction of the usage window at which the pause fires; the rest (1 \u2212 threshold) is your manual-work reserve. Empty \u21D2 0.75."}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});var Ud=S(()=>{"use strict"});function Bd(t){if(t==null)return[];if(!Array.isArray(t))return null;let e=[];for(let r of t){if(typeof r!="string"||r.trim().length===0)return null;e.push(r.trim())}return e}function rc(t){let{name:e,body:r,origin:n}=t;if(!tc.test(e))return{ok:!1,error:`role name must match ${tc} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let i=o,s=i.description;if(typeof s!="string"||s.trim().length===0)return{ok:!1,error:"description is required (one line: what this role looks for)"};if(s.length>300)return{ok:!1,error:"description must be \u2264 300 characters"};let a=Bd(i.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let d of a)if(d.startsWith("/")||d.includes(".."))return{ok:!1,error:`ref "${d}" must be a path inside the Context Repo`};let c=Bd(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let d of c){if(!vi.includes(d))return{ok:!1,error:`unknown scenario "${d}" \u2014 one of: ${vi.join(", ")}`};l.includes(d)||l.push(d)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${vi.join(", ")}`};let u=i.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=i.enabled;return p!==void 0&&typeof p!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:s.trim(),...typeof u=="string"?{model:u.trim()}:{},refs:a,scenarios:l,enabled:p!==!1,body:r.trim(),origin:n}}}function nc(t,e){let r=new Map;for(let n of t)r.set(n.name,n);for(let n of e)r.set(n.name,n);return[...r.values()].sort((n,o)=>n.name<o.name?-1:n.name>o.name?1:0)}function oc(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var vi,tc,gj,yj,Fd=S(()=>{"use strict";vi=["plan_review","code_review","council"],tc=/^[a-z][a-z0-9-]{1,39}$/,gj=10,yj=300});function ic(t){return Gd.includes(t)}function sc(t){return`prompts/${t}.md`}var Gd,Kd=S(()=>{"use strict";Gd=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","code-review-verify","config","council","draft","estimate","implement","index","observer","resolve-conflict","review-comment","rework","testing"]});function cc(t){if(!ac.test(t.name))return{ok:!1,error:`skill directory name must match ${ac}`};if(t.body.trim().length===0)return{ok:!1,error:"SKILL.md has no body \u2014 the body IS the procedure"};let e=t.frontmatter;if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"SKILL.md has no frontmatter block"};let r=e.description;return typeof r!="string"||r.trim().length===0?{ok:!1,error:"description is required \u2014 it is what decides when the skill fires"}:r.length>300?{ok:!1,error:"description must be \u2264 300 characters"}:{ok:!0,skill:{name:t.name,description:r.trim()}}}function lc(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}function Wd(t){let e=t.trim(),r=e.lastIndexOf("@"),n=r===-1?e:e.slice(0,r),o=r===-1?"":e.slice(r+1).trim();if(!r$.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let i=Hd.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!n$.test(o)?{ok:!1,error:`"${t}": pin to a full 40-character commit sha \u2014 a branch or tag can change under you`}:!i&&!o?{ok:!1,error:`"${t}": a third-party marketplace must be pinned to a commit (<owner>/<repo>@<sha>). Its skills run beside your code with the agent's token.`}:{ok:!0,source:{repo:n,sha:o,name:i?.name??n.replace("/","-").toLowerCase(),official:!!i}}}function o$(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=Wd(o);if(!i.ok){r.push(i.error);continue}n.has(i.source.name)||(n.add(i.source.name),e.push(i.source))}return{sources:e,errors:r}}function s$(t,e){let r=new Set(e.map(i=>i.name)),n={},o=[];for(let i of t){let s=i.trim();if(s){if(!i$.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var ac,kj,Hd,r$,n$,i$,qd=S(()=>{"use strict";ac=/^[a-z][a-z0-9-]{1,39}$/,kj=300;Hd=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],r$=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,n$=/^[0-9a-f]{40}$/;i$=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function Yd(t,e){if(t==null)return[];if(!Array.isArray(t)||t.length>e)return null;let r=[];for(let n of t){if(typeof n!="string"||n.trim().length===0)return null;r.push(n.trim())}return r}function a$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"queue plan must be a JSON object"};let r=new Set(e),n=t,o=Yd(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let f of o)if(!r.has(f))return{ok:!1,error:`order names ${f}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let i=e.filter(f=>!o.includes(f));if(o.length>0&&i.length>0)return{ok:!1,error:`order omits ${i.join(", ")}`};let s=n.tasks,a=[];if(s!=null){if(!Array.isArray(s))return{ok:!1,error:"tasks must be a list"};for(let f of s){if(!f||typeof f!="object")return{ok:!1,error:"each task entry must be an object"};let g=f,w=typeof g.taskKey=="string"?g.taskKey.trim():"";if(!r.has(w))return{ok:!1,error:`tasks names ${w||"(empty)"}, which is not in this batch`};let b=Yd(g.after,e.length);if(b===null)return{ok:!1,error:`${w}: after must be a list of task keys`};for(let y of b){if(!r.has(y))return{ok:!1,error:`${w}: after names ${y}, not in this batch`};if(y===w)return{ok:!1,error:`${w}: cannot come after itself`}}let v=typeof g.decisions=="string"?g.decisions.trim():"";a.push({taskKey:w,decisions:v.slice(0,4e3),after:b})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let f of l){if(!f||typeof f!="object")continue;let g=f,w=typeof g.taskKey=="string"?g.taskKey.trim():"",b=typeof g.adr=="string"?g.adr.trim():"",v=typeof g.detail=="string"?g.detail.trim():"";!r.has(w)||!v||c.push({taskKey:w,adr:b,detail:v.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let f of p){if(!f||typeof f!="object")continue;let g=f,w=typeof g.taskKey=="string"?g.taskKey.trim():"",b=typeof g.detail=="string"?g.detail.trim():"";!w||!b||u.push({taskKey:w,detail:b.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",m=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:m}}}var $j,xj,Vd=S(()=>{"use strict";$j=4e3,xj=4e3});function c$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"council verdict must be a JSON object"};let r=t,n=r.unresolved===!0,o=typeof r.fork=="string"?r.fork.trim().slice(0,4e3):"";if(n)return o?{ok:!0,verdict:{answers:[],unresolved:!0,fork:o}}:{ok:!1,error:"an unresolved verdict must describe the fork"};let i=r.answers;if(!Array.isArray(i))return{ok:!1,error:"answers must be a list"};if(i.length!==e.length)return{ok:!1,error:`expected ${e.length} answer(s), got ${i.length}`};let s=[];for(let[a,c]of i.entries()){if(!c||typeof c!="object")return{ok:!1,error:`answer ${a+1} must be an object`};let l=c,u=typeof l.answer=="string"?l.answer.trim():"";if(!u)return{ok:!1,error:`answer ${a+1} is empty`};s.push({question:typeof l.question=="string"?l.question.trim():e[a],answer:u.slice(0,4e3),rationale:typeof l.rationale=="string"?l.rationale.trim().slice(0,4e3):""})}return{ok:!0,verdict:{answers:s,unresolved:!1,fork:""}}}var Ej,zd=S(()=>{"use strict";Ej=4e3});function d$(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of l$)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function uc(t){let e=[],r=new Map,n="",o=null,i=null;for(let a of t.split(`
|
|
8
|
+
`)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=d$(n),i=null;continue}let l=u$.exec(a);if(l&&o){let u=l[1];r.set(u,(r.get(u)??0)+1),i={id:u,kind:o.kind,text:l[2].trim(),section:n},e.push(i);continue}if(i&&a.trim()&&!/^#{1,6}\s/.test(a)&&!/^\s*[-*]\s/.test(a)){i.text=`${i.text}
|
|
9
|
+
${a.trim()}`.trim();continue}a.trim()||(i=null)}let s=[...r.entries()].filter(([,a])=>a>1).map(([a])=>a);return{items:e,structured:e.length>=2&&s.length===0,duplicateIds:s}}function p$(t){let e={decision:"D",change:"C",assumption:"A",out_of_scope:"O",test:"T",procedure:"P"};return t.items.filter(r=>!r.id.startsWith(e[r.kind]))}function f$(t,e){let r=new Map(t.items.map(s=>[s.id,s])),n=e.filter(s=>!s.approved),o=e.filter(s=>s.approved).map(s=>s.id);if(n.length===0)return"";let i=["Rejected plan items:",""];for(let s of n){let a=r.get(s.id),c=a?`${s.id} \u2014 ${a.text.split(`
|
|
10
10
|
`)[0]}`:s.id;i.push(`- **${c}**`),s.remark?.trim()&&i.push(` ${s.remark.trim()}`)}return o.length>0&&i.push("",`Approved and settled: ${o.join(", ")}. Do not revisit these unless a`,"rejected item forces it \u2014 and say so explicitly if it does."),i.join(`
|
|
11
|
-
`)}function
|
|
12
|
-
`)){let i=
|
|
13
|
-
${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}function y$(t,e){let r=new Set(t);return{unreported:t.filter(n=>!(n in e.byId)),unknown:e.items.filter(n=>!r.has(n.id)).map(n=>n.id),notDone:e.items.filter(n=>n.status!=="done")}}var m$,h$,Xd=S(()=>{"use strict";m$=["done","deviated","partial","dropped"],h$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var Jd=S(()=>{"use strict"});var Zd=S(()=>{"use strict"});var Qd=S(()=>{"use strict"});function dc(t){return`codepipe-host-${t}`}function w$(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var ep=S(()=>{"use strict"});function b$(t){let e=t.toLowerCase(),r="";for(let o of e)r+=Object.prototype.hasOwnProperty.call(tp,o)?tp[o]:o;return r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50).replace(/-+$/g,"")}function k$(t,e,r){let o=(t&&t.includes("<TASK_ID>")?t:rp).replace(/<TASK_ID>/g,e.toLowerCase()).replace(/<SLUG>/g,r??"");return o=o.replace(/-{2,}/g,"-").replace(/\/{2,}/g,"/").replace(/-\//g,"/").replace(/\/-/g,"/").replace(/^[-/]+|[-/]+$/g,""),o}function v$(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function zt(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 pc(t){if(!t||typeof t!="object")return null;let e=t,r=typeof e.owner=="string"?e.owner.trim():"",n=typeof e.repo=="string"?e.repo.trim():typeof e.repoName=="string"?e.repoName.trim():"",o=typeof e.host=="string"?e.host.trim():"";return!r||!n||o!=="github"&&o!=="gitlab"&&o!=="bitbucket"?null:{host:o,owner:r,repoName:n}}function fc(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function It(t){return`${t}${np}`}var rp,Rj,tp,Xt,np,mc=S(()=>{"use strict";rp="codepipe/<TASK_ID>",Rj=50,tp={\u0430:"a",\u0431:"b",\u0432:"v",\u0433:"g",\u0434:"d",\u0435:"e",\u0451:"e",\u0436:"zh",\u0437:"z",\u0438:"i",\u0439:"y",\u043A:"k",\u043B:"l",\u043C:"m",\u043D:"n",\u043E:"o",\u043F:"p",\u0440:"r",\u0441:"s",\u0442:"t",\u0443:"u",\u0444:"f",\u0445:"h",\u0446:"c",\u0447:"ch",\u0448:"sh",\u0449:"sch",\u044A:"",\u044B:"y",\u044C:"",\u044D:"e",\u044E:"yu",\u044F:"ya"};Xt=/^[a-z][a-z0-9-]{1,30}$/,np="-codepipe-ctx"});function $$(t){return t==="simple"||t==="gitflow"||t==="release"}function hc(t){return t==="integration"||t==="stable"||t==="release_pattern"}function x$(t){let e=t.endsWith("/*")?t.slice(0,-2):t;return zt(e)}function S$(t){let e=new Set(gc[t.flow].roles);for(let r of Object.keys(t.branchTypes??{}))hc(r)&&e.add(r);return e}function an(t){if(t==null)return{config:null,errors:[]};let e=[];if(typeof t!="object"||Array.isArray(t))return{config:null,errors:["git: must be a mapping"]};let r=t,n=r.flow;if(!$$(n))return e.push(`git.flow must be one of simple | gitflow | release (got ${JSON.stringify(n)})`),{config:null,errors:e};let o=n,i={},s=r.branch_types??r.branchTypes;if(s!==void 0)if(typeof s!="object"||s===null||Array.isArray(s))e.push("git.branch_types must be a mapping of role \u2192 name/pattern");else for(let[d,m]of Object.entries(s)){if(!hc(d)){e.push(`git.branch_types: unknown role "${d}"`);continue}if(typeof m!="string"||!op(d,m)){e.push(`git.branch_types.${d}: invalid branch name/pattern ${JSON.stringify(m)}`);continue}i[d]=m}let a=new Set(gc[o].roles);for(let d of Object.keys(i))a.add(d);let c={},l=r.branches;if(l!==void 0)if(typeof l!="object"||l===null||Array.isArray(l))e.push("git.branches must be a mapping of role \u2192 branch name");else for(let[d,m]of Object.entries(l)){if(!hc(d)){e.push(`git.branches: unknown role "${d}"`);continue}if(!a.has(d)){e.push(`git.branches.${d}: role not part of flow "${o}"`);continue}if(typeof m!="string"||!op(d,m)){e.push(`git.branches.${d}: invalid branch name/pattern ${JSON.stringify(m)}`);continue}c[d]=m}let u,p=r.commit;if(p!==void 0)if(typeof p!="object"||p===null||Array.isArray(p))e.push("git.commit must be a mapping");else{let d=p.subject;d!==void 0&&typeof d!="string"?e.push("git.commit.subject must be a string"):typeof d=="string"?u={subject:d}:u={}}return e.length>0?{config:null,errors:e}:{config:{flow:o,branches:c,...Object.keys(i).length>0?{branchTypes:i}:{},...u?{commit:u}:{}},errors:[]}}function op(t,e){return t==="release_pattern"?x$(e):zt(e)}function E$(t,e,r){let n=r??"main",o=e??t;if(!o)return{flow:"simple",integration:n};let i=S$(o),s=u=>o.branches[u]??o.branchTypes?.[u],a=s("integration")??n,c=i.has("stable")?s("stable"):void 0,l=i.has("release_pattern")?s("release_pattern"):void 0;return{flow:o.flow,integration:a,...c?{stable:c}:{},...l?{releasePattern:l}:{}}}function vi(t){return t.gitFlow?.integration??t.defaultBranch??"main"}function T$(t,e){return e??vi(t)}function ip(t,e){if(e.endsWith("/*")){let r=e.slice(0,-1);return t.startsWith(r)&&t.length>r.length}return t===e}function yc(t,e){return e.flow==="simple"?!1:!!(t===e.integration||e.stable&&t===e.stable||e.releasePattern&&ip(t,e.releasePattern))}function ho(t){let e=t.branches??[],r=e.some(s=>/^release\//.test(s)),n=e.includes("develop")||e.includes("dev"),o=r?"release":n?"gitflow":"simple",i={integration:R$(o,t)};if(o!=="simple"){let s=I$(t,i.integration??"");s&&(i.stable=s)}return o==="release"&&(i.release_pattern="release/*"),{flow:o,branches:i}}function R$(t,e){let r=e.branches??[];if(t!=="simple"){if(r.includes("develop"))return"develop";if(r.includes("dev"))return"dev"}return e.defaultBranch??r[0]??""}function I$(t,e){let r=t.branches??[],n=t.defaultBranch;if(n&&(n==="main"||n==="master")&&n!==e)return n;if(r.includes("main")&&e!=="main")return"main";if(r.includes("master")&&e!=="master")return"master"}function wc(t,e){if(t.flow==="simple")return!1;if(t.flow!==e.flow)return!0;let r=t.branches,n=e.branches;return(r.integration??"")!==(n.integration??"")||(r.stable??"")!==(n.stable??"")||(r.release_pattern??"")!==(n.release_pattern??"")}var gc,sp=S(()=>{"use strict";mc();gc={simple:{roles:["integration"]},gitflow:{roles:["integration","stable"]},release:{roles:["integration","stable","release_pattern"]}}});function C$(t,e,r=72){let n=(t||ap).replace(/\{key\}/g,e.key).replace(/\{summary\}/g,e.summary).replace(/\s+/g," ").trim(),o=Number.isFinite(r)&&r>0?Math.floor(r):72;if(n.length<=o)return n;let i=n.slice(0,o),s=i.lastIndexOf(" ");return s>=Math.floor(o/2)?i.slice(0,s).trimEnd():i.trimEnd()}var ap,_j,cp=S(()=>{"use strict";ap="{key}: {summary}",_j=72});function P$(t,e){return`${t}:${e}`}var lp=S(()=>{"use strict"});function up(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)||/^write action apply_delivery failed: .*hit conflicts/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function _$(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function A$(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=_$(e)?.reason,o={kind:up(n)};return n&&(o.reason=n),o}}var dp=S(()=>{"use strict"});function Tr(t){for(let e of pp){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var pp,fp=S(()=>{"use strict";pp=[{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},{name:"fix",pattern:/^@(?:codepipe|devpipe)\s+fix\s*$/im,description:"Fix the external review remarks on the developer's branch (waiting-for-fix state only)."}]});var mp=S(()=>{"use strict"});function hp(t){let e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;let r=Math.round(e/60);if(r<60)return`${r}m`;let n=Math.round(r/60);return n<24?`${n}h`:`${Math.round(n/24)}d`}function j$(t,e=Date.now()){return`${hp((e-t)/1e3)} ago`}function N$(t){let e=Math.floor(t/86400),r=Math.floor(t%86400/3600),n=Math.floor(t%3600/60);return e>0?`${e}d ${r}h`:r>0?`${r}h ${n}m`:`${n}m`}var gp=S(()=>{"use strict"});var yp=S(()=>{"use strict"});function wp(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function kc(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=wp(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Rr.test(r))return r;let n=wp(t);return Rr.test(n)?n:$i}function vc(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 ln(t){return`tasks/${t}/issue.yaml`}var bc,go,$i,Rr,xi,O$,yo,cn,bp=S(()=>{"use strict";bc=["bug","feature","epic"],go="feature",$i="TASK",Rr=/^[A-Z][A-Z0-9]{1,9}$/;xi={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},O$=xi.backlog,yo="tracker/config.yaml",cn="tracker/counter"});function wo(t){let e=t.split(`
|
|
11
|
+
`)}function dc(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(m$))e.add(n[1]);return[...e]}var l$,u$,m$,Xd=S(()=>{"use strict";l$=[{re:/^decisions?$/i,kind:"decision",letter:"D"},{re:/^changes?$/i,kind:"change",letter:"C"},{re:/^assumptions?$/i,kind:"assumption",letter:"A"},{re:/^out of scope$/i,kind:"out_of_scope",letter:"O"},{re:/^test strategy$/i,kind:"test",letter:"T"},{re:/^procedures?$/i,kind:"procedure",letter:"P"}],u$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;m$=/`([a-z][a-z0-9-]{1,39})`/g});function y$(t){let e=[],r=null;for(let o of t.split(`
|
|
12
|
+
`)){let i=g$.exec(o);if(i){r={id:i[1],status:i[2].toLowerCase(),text:i[3].trim()},e.push(r);continue}if(/^#{1,6}\s/.test(o)||/^\s*[-*]\s/.test(o)||!o.trim()){r=null;continue}r&&(r.text=`${r.text}
|
|
13
|
+
${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}function w$(t,e){let r=new Set(t);return{unreported:t.filter(n=>!(n in e.byId)),unknown:e.items.filter(n=>!r.has(n.id)).map(n=>n.id),notDone:e.items.filter(n=>n.status!=="done")}}var h$,g$,Jd=S(()=>{"use strict";h$=["done","deviated","partial","dropped"],g$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var Zd=S(()=>{"use strict"});var Qd=S(()=>{"use strict"});var ep=S(()=>{"use strict"});function pc(t){return`codepipe-host-${t}`}function b$(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var tp=S(()=>{"use strict"});function k$(t){let e=t.toLowerCase(),r="";for(let o of e)r+=Object.prototype.hasOwnProperty.call(rp,o)?rp[o]:o;return r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50).replace(/-+$/g,"")}function v$(t,e,r){let o=(t&&t.includes("<TASK_ID>")?t:np).replace(/<TASK_ID>/g,e.toLowerCase()).replace(/<SLUG>/g,r??"");return o=o.replace(/-{2,}/g,"-").replace(/\/{2,}/g,"/").replace(/-\//g,"/").replace(/\/-/g,"/").replace(/^[-/]+|[-/]+$/g,""),o}function $$(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function Xt(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 fc(t){if(!t||typeof t!="object")return null;let e=t,r=typeof e.owner=="string"?e.owner.trim():"",n=typeof e.repo=="string"?e.repo.trim():typeof e.repoName=="string"?e.repoName.trim():"",o=typeof e.host=="string"?e.host.trim():"";return!r||!n||o!=="github"&&o!=="gitlab"&&o!=="bitbucket"?null:{host:o,owner:r,repoName:n}}function mc(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function Et(t){return`${t}${op}`}var np,Pj,rp,Jt,op,hc=S(()=>{"use strict";np="codepipe/<TASK_ID>",Pj=50,rp={\u0430:"a",\u0431:"b",\u0432:"v",\u0433:"g",\u0434:"d",\u0435:"e",\u0451:"e",\u0436:"zh",\u0437:"z",\u0438:"i",\u0439:"y",\u043A:"k",\u043B:"l",\u043C:"m",\u043D:"n",\u043E:"o",\u043F:"p",\u0440:"r",\u0441:"s",\u0442:"t",\u0443:"u",\u0444:"f",\u0445:"h",\u0446:"c",\u0447:"ch",\u0448:"sh",\u0449:"sch",\u044A:"",\u044B:"y",\u044C:"",\u044D:"e",\u044E:"yu",\u044F:"ya"};Jt=/^[a-z][a-z0-9-]{1,30}$/,op="-codepipe-ctx"});function x$(t){return t==="simple"||t==="gitflow"||t==="release"}function gc(t){return t==="integration"||t==="stable"||t==="release_pattern"}function S$(t){let e=t.endsWith("/*")?t.slice(0,-2):t;return Xt(e)}function E$(t){let e=new Set(yc[t.flow].roles);for(let r of Object.keys(t.branchTypes??{}))gc(r)&&e.add(r);return e}function cn(t){if(t==null)return{config:null,errors:[]};let e=[];if(typeof t!="object"||Array.isArray(t))return{config:null,errors:["git: must be a mapping"]};let r=t,n=r.flow;if(!x$(n))return e.push(`git.flow must be one of simple | gitflow | release (got ${JSON.stringify(n)})`),{config:null,errors:e};let o=n,i={},s=r.branch_types??r.branchTypes;if(s!==void 0)if(typeof s!="object"||s===null||Array.isArray(s))e.push("git.branch_types must be a mapping of role \u2192 name/pattern");else for(let[d,m]of Object.entries(s)){if(!gc(d)){e.push(`git.branch_types: unknown role "${d}"`);continue}if(typeof m!="string"||!ip(d,m)){e.push(`git.branch_types.${d}: invalid branch name/pattern ${JSON.stringify(m)}`);continue}i[d]=m}let a=new Set(yc[o].roles);for(let d of Object.keys(i))a.add(d);let c={},l=r.branches;if(l!==void 0)if(typeof l!="object"||l===null||Array.isArray(l))e.push("git.branches must be a mapping of role \u2192 branch name");else for(let[d,m]of Object.entries(l)){if(!gc(d)){e.push(`git.branches: unknown role "${d}"`);continue}if(!a.has(d)){e.push(`git.branches.${d}: role not part of flow "${o}"`);continue}if(typeof m!="string"||!ip(d,m)){e.push(`git.branches.${d}: invalid branch name/pattern ${JSON.stringify(m)}`);continue}c[d]=m}let u,p=r.commit;if(p!==void 0)if(typeof p!="object"||p===null||Array.isArray(p))e.push("git.commit must be a mapping");else{let d=p.subject;d!==void 0&&typeof d!="string"?e.push("git.commit.subject must be a string"):typeof d=="string"?u={subject:d}:u={}}return e.length>0?{config:null,errors:e}:{config:{flow:o,branches:c,...Object.keys(i).length>0?{branchTypes:i}:{},...u?{commit:u}:{}},errors:[]}}function ip(t,e){return t==="release_pattern"?S$(e):Xt(e)}function R$(t,e,r){let n=r??"main",o=e??t;if(!o)return{flow:"simple",integration:n};let i=E$(o),s=u=>o.branches[u]??o.branchTypes?.[u],a=s("integration")??n,c=i.has("stable")?s("stable"):void 0,l=i.has("release_pattern")?s("release_pattern"):void 0;return{flow:o.flow,integration:a,...c?{stable:c}:{},...l?{releasePattern:l}:{}}}function ln(t){return t.gitFlow?.integration??t.defaultBranch??"main"}function T$(t,e){return e??ln(t)}function sp(t,e){if(e.endsWith("/*")){let r=e.slice(0,-1);return t.startsWith(r)&&t.length>r.length}return t===e}function wc(t,e){return e.flow==="simple"?!1:!!(t===e.integration||e.stable&&t===e.stable||e.releasePattern&&sp(t,e.releasePattern))}function yo(t){let e=t.branches??[],r=e.some(s=>/^release\//.test(s)),n=e.includes("develop")||e.includes("dev"),o=r?"release":n?"gitflow":"simple",i={integration:I$(o,t)};if(o!=="simple"){let s=C$(t,i.integration??"");s&&(i.stable=s)}return o==="release"&&(i.release_pattern="release/*"),{flow:o,branches:i}}function I$(t,e){let r=e.branches??[];if(t!=="simple"){if(r.includes("develop"))return"develop";if(r.includes("dev"))return"dev"}return e.defaultBranch??r[0]??""}function C$(t,e){let r=t.branches??[],n=t.defaultBranch;if(n&&(n==="main"||n==="master")&&n!==e)return n;if(r.includes("main")&&e!=="main")return"main";if(r.includes("master")&&e!=="master")return"master"}function bc(t,e){if(t.flow==="simple")return!1;if(t.flow!==e.flow)return!0;let r=t.branches,n=e.branches;return(r.integration??"")!==(n.integration??"")||(r.stable??"")!==(n.stable??"")||(r.release_pattern??"")!==(n.release_pattern??"")}var yc,ap=S(()=>{"use strict";hc();yc={simple:{roles:["integration"]},gitflow:{roles:["integration","stable"]},release:{roles:["integration","stable","release_pattern"]}}});function P$(t,e,r=72){let n=(t||cp).replace(/\{key\}/g,e.key).replace(/\{summary\}/g,e.summary).replace(/\s+/g," ").trim(),o=Number.isFinite(r)&&r>0?Math.floor(r):72;if(n.length<=o)return n;let i=n.slice(0,o),s=i.lastIndexOf(" ");return s>=Math.floor(o/2)?i.slice(0,s).trimEnd():i.trimEnd()}var cp,Nj,lp=S(()=>{"use strict";cp="{key}: {summary}",Nj=72});function _$(t,e){return`${t}:${e}`}var up=S(()=>{"use strict"});function dp(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)||/^write action apply_delivery failed: .*hit conflicts/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function A$(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function j$(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=A$(e)?.reason,o={kind:dp(n)};return n&&(o.reason=n),o}}var pp=S(()=>{"use strict"});function Tr(t){for(let e of fp){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var fp,mp=S(()=>{"use strict";fp=[{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},{name:"fix",pattern:/^@(?:codepipe|devpipe)\s+fix\s*$/im,description:"Fix the external review remarks on the developer's branch (waiting-for-fix state only)."}]});var hp=S(()=>{"use strict"});function gp(t){let e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;let r=Math.round(e/60);if(r<60)return`${r}m`;let n=Math.round(r/60);return n<24?`${n}h`:`${Math.round(n/24)}d`}function N$(t,e=Date.now()){return`${gp((e-t)/1e3)} ago`}function O$(t){let e=Math.floor(t/86400),r=Math.floor(t%86400/3600),n=Math.floor(t%3600/60);return e>0?`${e}d ${r}h`:r>0?`${r}h ${n}m`:`${n}m`}var yp=S(()=>{"use strict"});var wp=S(()=>{"use strict"});function bp(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function vc(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=bp(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Ir.test(r))return r;let n=bp(t);return Ir.test(n)?n:$i}function $c(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 dn(t){return`tasks/${t}/issue.yaml`}var kc,wo,$i,Ir,xi,L$,bo,un,kp=S(()=>{"use strict";kc=["bug","feature","epic"],wo="feature",$i="TASK",Ir=/^[A-Z][A-Z0-9]{1,9}$/;xi={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},L$=xi.backlog,bo="tracker/config.yaml",un="tracker/counter"});function ko(t){let e=t.split(`
|
|
14
14
|
`),r=e.indexOf("---");if(r<0)return;let n=e.slice(r+1),o=n.lastIndexOf("## Attachments");o>=0&&n.slice(o+1).every(c=>c.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(c.trim()))&&(n=n.slice(0,o));let i=n.join(`
|
|
15
|
-
`).trim();if(!(!i||i==="_(no description)_"))return i}function
|
|
16
|
-
`,{mode:384})}function
|
|
17
|
-
`,{mode:384})}function
|
|
18
|
-
`,{mode:384})}function
|
|
15
|
+
`).trim();if(!(!i||i==="_(no description)_"))return i}function M$(t){return`{{ancestorExcerpt:${t}}}`}var Si,vp=S(()=>{"use strict";Si=/\{\{ancestorExcerpt:([^}]+)\}\}/g});var D$,$p=S(()=>{"use strict";D$="youtrack"});function Cr(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 vo(t){switch(t){case pn.gitlab:return"oauth2";case pn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var pn,Ft,xp=S(()=>{"use strict";pn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Ft="x-bitbucket-api-token-auth"});var Sp=S(()=>{"use strict"});var Ep=S(()=>{"use strict";$p();xp();Sp()});var Rp={};Ge(Rp,{ACTION_ID_RE:()=>Ka,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>Wa,ALL_JOB_ROLES:()=>Ma,ALL_MODEL_ROLE_KEYS:()=>wi,ANALYSIS_MAX_DRAFTS:()=>xc,ANCESTOR_EXCERPT_RE:()=>Si,ANCESTOR_EXCERPT_TOKEN:()=>M$,ANNOTATION_MAX_PER_TASK:()=>Ca,BACKFILL_MAX_DRAFTS:()=>U$,BITBUCKET_API_TOKEN_GIT_USER:()=>Ft,BRANCH_SLUG_MAX_LENGTH:()=>Pj,BUILD_DISCOVERY:()=>Ed,COCHANGE_DEFAULTS:()=>ot,CODEPIPE_COMMANDS:()=>fp,CODE_REVIEW_VERIFY:()=>Rd,COMMIT_STYLE_MAX_LENGTH:()=>Za,CONTEXT_PACK_DECAY:()=>_a,CONTEXT_PACK_DEFAULTS:()=>Sr,CONTEXT_REPO_SUFFIX:()=>op,CONTEXT_STAMP_FILE:()=>ht,CONTEXT_TEMPLATE_CHANGELOG:()=>ya,CONTEXT_TEMPLATE_VERSION:()=>ad,COUNCIL_MAX_ANSWER:()=>Ej,DEFAULT_BRANCH_PATTERN:()=>np,DEFAULT_COMMIT_SUBJECT:()=>cp,DEFAULT_HUB_URL:()=>ft,DEFAULT_INTERNAL_ISSUE_TYPE:()=>wo,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>$i,DEFAULT_LLM_PROVIDER:()=>Je,DEFAULT_REGIMEN_ALIASES:()=>Pd,DEFAULT_SUBJECT_MAX:()=>Nj,DEFAULT_TRACKER_PROVIDER:()=>D$,EFFORT_LEVELS:()=>_d,EFFORT_LEVEL_SUGGESTIONS:()=>bi,ENV_NAME_RE:()=>Ze,FALLBACK_MODEL:()=>Id,GIT_FLOW_PRESETS:()=>yc,GIT_HOST_DOMAINS:()=>pn,INTERACTIVE_ROLES:()=>xd,INTERNAL_ISSUE_TYPES:()=>kc,INTERNAL_TRACKER_CONFIG_PATH:()=>bo,INTERNAL_TRACKER_COUNTER_PATH:()=>un,INTERNAL_TRACKER_DEFAULT_STATUS:()=>L$,INTERNAL_TRACKER_PREFIX_RE:()=>Ir,INTERNAL_TRACKER_STATUSES:()=>xi,LANE_PHASES:()=>Nv,LANE_SEGMENTS:()=>La,LANGUAGE_AUTO:()=>me,LANGUAGE_SUGGESTIONS:()=>an,LANGUAGE_VALUE_MAX_LENGTH:()=>go,LEGACY_CONTEXT_STAMP_FILE:()=>en,LLM_PROVIDER_SUGGESTIONS:()=>Ba,MIN_SUPPORTED_PROTOCOL:()=>od,MODEL_ALIAS_SUGGESTIONS:()=>yi,MODEL_DERIVED_DIR:()=>Tv,MODEL_DERIVED_INDEX_PATH:()=>pi,MODEL_DIR:()=>Sv,MODEL_EDGE_KINDS:()=>Ta,MODEL_ENTITY_ID_RE:()=>dd,MODEL_FACTS_DIR:()=>Rv,MODEL_FAMILY_PREFERENCE:()=>Cd,MODEL_HAIKU:()=>gi,MODEL_LEVELS:()=>ud,MODEL_OPUS:()=>Re,MODEL_README_PATH:()=>Ev,MODEL_RELATES_PATH:()=>vr,MODEL_SEARCH_MAX_LIMIT:()=>Pa,MODEL_SEARCH_MAX_ROWS:()=>Cv,MODEL_SEARCH_ROW_TEXT_MAX:()=>mi,MODEL_SONNET:()=>sn,MODEL_SUB_ROLES:()=>Td,OBSERVER_MAX_DECISION:()=>$j,OBSERVER_MAX_SUMMARY:()=>xj,OFFICIAL_MARKETPLACES:()=>Hd,PHASES:()=>Oa,PIPELINE_COLUMNS:()=>kd,PLANNING_LANE_MAX_JOBS:()=>Dv,PLANNING_ROLES:()=>$d,PLATFORM_VERSION:()=>Xe,PROJECT_ID_RE:()=>Jt,PROJECT_LANGUAGE_SECTIONS:()=>ho,PROJECT_MODEL_FORMAT_VERSION:()=>Le,PROJECT_SETTINGS_MANIFEST:()=>Ld,PROMPT_ROLES:()=>Gd,PROTOCOL_VERSION:()=>mt,RECOMMENDED_ROLE_EFFORT:()=>mo,RECOMMENDED_ROLE_MODELS:()=>fo,RELATES_MIN_OVERLAP:()=>Ia,ROLE_MAX_DESCRIPTION:()=>yj,ROLE_MAX_REFS:()=>gj,ROLE_NAME_RE:()=>tc,ROLE_SCENARIOS:()=>vi,SKILL_MAX_DESCRIPTION:()=>kj,SKILL_NAME_RE:()=>ac,SOLUTION_STATUSES:()=>h$,STRING_MAP_MAX_ENTRIES:()=>Xa,STRING_MAP_MAX_VALUE_LENGTH:()=>Ja,additionsSince:()=>ba,ago:()=>N$,attentionFor:()=>j$,autoLanguageConfig:()=>Nd,autoModelDefault:()=>Fa,branchMatchesFlow:()=>wc,canonicalizeModelEdgeSheet:()=>pd,canonicalizeModelIdentityTable:()=>md,canonicalizeModelShard:()=>fd,canonicalizeModelTaskEvent:()=>hd,changesSince:()=>ka,classifyAttentionReason:()=>dp,compilePlanRework:()=>f$,contextRepoName:()=>Et,deserializeEffortConfig:()=>Wv,deserializeModelConfig:()=>Yv,detectGitFlowPreset:()=>yo,effectiveClusterBase:()=>T$,emptyEffortConfig:()=>on,emptyModelConfig:()=>nn,enabledPluginsSetting:()=>s$,extractLanguageConfig:()=>Zv,extractTaskMdBody:()=>ko,findSettingField:()=>Md,firstFreeInternalTrackerPrefix:()=>$c,flattenSettingFields:()=>Qa,fmtDuration:()=>gp,fmtUptime:()=>O$,ghRunnerHostLabel:()=>pc,ghRunnerRunsOnSnippet:()=>b$,gitCloneUrlDomain:()=>Cr,gitFlowDiverges:()=>bc,httpsTokenUser:()=>vo,internalIssueYamlPath:()=>dn,isAllAutoLanguage:()=>Qv,isAutoLanguage:()=>Od,isBodyEditFrozen:()=>jv,isInteractiveRole:()=>Da,isModelEntityId:()=>fi,isPromptRole:()=>ic,isProtocolCompatible:()=>so,isReservedEnvName:()=>Bt,isTerminalPhase:()=>Av,isValidBranchName:()=>Xt,jobLane:()=>Mv,laneSegmentForPhase:()=>Ov,makeTaskId:()=>_$,matchesReleasePattern:()=>sp,mergeRoles:()=>nc,mergeSkills:()=>lc,mismatchedIds:()=>p$,modelAnnotationPath:()=>xa,modelComponentSlug:()=>ld,modelCorrelatesPath:()=>Sa,modelEventPath:()=>$r,modelIdentityPath:()=>lo,modelNodeKey:()=>fe,modelShardNeedsRebuild:()=>Pv,modelStructureShardPath:()=>Ra,modelTaskNodeKey:()=>xe,modelTouchedPath:()=>Ea,parseActionDefinition:()=>qa,parseCodepipeCommand:()=>Tr,parseContextStamp:()=>wa,parseEffortConfig:()=>Kv,parseGitConfig:()=>cn,parseMarketplaceSource:()=>Wd,parseMarketplaces:()=>o$,parseModelConfig:()=>Fv,parseModelNodeKey:()=>te,parsePlanItems:()=>uc,parseRepoMirror:()=>fc,parseSolutionItems:()=>y$,pipelineColumnForPhase:()=>Lv,pipelineRepoSpec:()=>mc,prescribedSkills:()=>dc,promptOverridePath:()=>sc,renderCommitSubject:()=>P$,renderContextStamp:()=>ao,repoBaseBranch:()=>ln,resolveBranchName:()=>v$,resolveEffortForRole:()=>Gv,resolveModelForRole:()=>Uv,resolveProvider:()=>Bv,resolveRepoFlow:()=>R$,rolesForScenario:()=>oc,serializeEffortConfig:()=>Hv,serializeModelConfig:()=>qv,serializeModelEdgeSheet:()=>xr,serializeModelIdentityTable:()=>ja,serializeModelShard:()=>Aa,serializeModelTaskEvent:()=>rn,serializeModelYaml:()=>Er,slugify:()=>k$,solutionCoverage:()=>w$,suggestInternalTrackerPrefix:()=>vc,validateActionInput:()=>Ya,validateCouncilVerdict:()=>c$,validateModelEdgeSheet:()=>uo,validateModelIdentityTable:()=>po,validateModelShard:()=>Mt,validateModelTaskEvent:()=>Dt,validateObserverPlan:()=>a$,validateRoleDefinition:()=>rc,validateSettingEdit:()=>ec,validateSkill:()=>cc,youtrackIssueUrl:()=>$$,zeroUsage:()=>Ut});var xc,U$,D=S(()=>{"use strict";id();sd();cd();Na();bd();vd();Ua();Ga();Dd();Ud();za();Va();Fd();Kd();qd();Vd();zd();Xd();Jd();Zd();Qd();ep();tp();hc();ap();lp();up();pp();mp();hp();yp();wp();kp();vp();Ep();xc=20,U$=15});function Q(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ke=S(()=>{"use strict"});import{existsSync as B$,readFileSync as F$,readdirSync as G$}from"node:fs";import{dirname as K$,join as Sc}from"node:path";import{parse as H$}from"yaml";function W$(t=process.cwd()){let e=t;for(;;){if(B$(Sc(e,Qe,"project.yaml")))return e;let r=K$(e);if(r===e)return null;e=r}}function q$(t){return Sc(t,Qe)}function Pe(t=process.cwd()){let e=W$(t);if(!e)return null;let r=q$(e),n=Y$(F$(Sc(r,"project.yaml"),"utf-8"));for(let o of n.gitConfigErrors??[])console.warn(`project.yaml: invalid git config \u2014 ${o}`);return{root:e,contextDir:r,spec:n}}function Tp(t,e,r){return G$(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 fn(t,e=process.cwd()){try{let r=Pe(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Y$(t){let e=H$(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=[],s=[];s.push(...cn(e.git).errors.map(a=>`git: ${a}`));for(let a of o){if(!a||typeof a!="object")continue;let c=a,l=String(c.repo??c.repoName??""),u=String(c.name??l);if(!u||!l)continue;let p=c.host,d=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github",m=fc(c.mirror);c.git!==void 0&&c.git!==null&&s.push(...cn(c.git).errors.map(f=>`repos[${u}].git: ${f}`)),i.push({name:u,host:d,owner:String(c.owner??""),repoName:l,defaultBranch:String(c.default_branch??c.defaultBranch??"main"),mountAs:String(c.mount_as??c.mountAs??u),...m?{mirror:m}:{}})}return{projectId:r,name:n,repos:i,...s.length>0?{gitConfigErrors:s}:{}}}function Ip(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 Qe,yt=S(()=>{"use strict";D();Qe=".codepipe"});import{homedir as Cp}from"node:os";import{mkdirSync as V$,readFileSync as z$,writeFileSync as X$,existsSync as Ec}from"node:fs";import{dirname as _p,join as Ei,resolve as J$}from"node:path";import{fileURLToPath as Z$}from"node:url";function Ap(t){let e=Ei(Pp,".env");if(Ec(e)&&process.loadEnvFile(e),t){let r=Ei(Pp,"profiles",t,".env");Ec(r)&&process.loadEnvFile(r)}}function mn(t){let e=Q("CONFIG");return e||(t?Ei(Cp(),".codepipe","profiles",t,"config.json"):Ei(Cp(),".codepipe","config.json"))}function wt(t){let e=mn(t);if(!Ec(e))return null;let r=z$(e,"utf-8");return JSON.parse(r)}function Gt(t,e){let r=mn(e);V$(_p(r),{recursive:!0}),X$(r,JSON.stringify(t,null,2)+`
|
|
16
|
+
`,{mode:384})}function hn(t){if(t)return{cfg:it(t),profile:t};let e;try{e=Pe()?.spec.projectId||void 0}catch{}if(e){let r=wt(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:it(void 0),profile:void 0}}function it(t){let e=wt(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 ${mn(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Pp,He=S(()=>{"use strict";Ke();yt();Pp=J$(_p(Z$(import.meta.url)),"..")});import{homedir as jp}from"node:os";import{existsSync as Np,mkdirSync as Op,readFileSync as Lp,writeFileSync as Mp}from"node:fs";import{dirname as Dp,join as Up}from"node:path";function Bp(t,e,r){let n=V(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ae(n)}function Fp(t,e){let r=V(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ae(r),!0)}function Gp(t){return Object.keys(V(t)?.secrets??{}).sort()}function Ri(t,e,r){let n=V(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,ae(n),"pinned")}function Kp(t,e){let r=V(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ae(r),!0):!1}function Rt(t){return Up(jp(),".codepipe","secrets",`${t}.json`)}function V(t){let e=Rt(t);return Np(e)?JSON.parse(Lp(e,"utf-8")):null}function ae(t){let e=Rt(t.projectId);Op(Dp(e),{recursive:!0}),Mp(e,JSON.stringify(t,null,2)+`
|
|
17
|
+
`,{mode:384})}function Ti(){return Up(jp(),".codepipe","shared.json")}function Rc(){let t=Ti();return Np(t)?JSON.parse(Lp(t,"utf-8")):null}function Hp(t){let e=Ti();Op(Dp(e),{recursive:!0}),Mp(e,JSON.stringify(t,null,2)+`
|
|
18
|
+
`,{mode:384})}function gn(t){let e=V(t)?.claude?.oauthToken;return e||Rc()?.claude?.oauthToken}function $o(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 Tc){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function yn(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Tc,de=S(()=>{"use strict";Tc=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as Q$,existsSync as qp,mkdirSync as ex,renameSync as Yp,statSync as tx,unlinkSync as rx}from"node:fs";import{Writable as nx}from"node:stream";import{join as ox}from"node:path";function Ii(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=ix(process.env[`${t}_MAX_BYTES`]??String(Vp.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Vp.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function ix(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 Ci(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(sx(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 sx(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:ax(o)).join(" ");return`${r} ${t} ${n}`}function ax(t){try{return JSON.stringify(t)}catch{return String(t)}}var Vp,wn,Ic=S(()=>{"use strict";Vp={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},wn=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&ex(e.dir,{recursive:!0}),this.currentPath=ox(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
|
|
19
19
|
`)?e:e+`
|
|
20
|
-
`;
|
|
21
|
-
`+t.slice(t.length-e)}async function Jt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Pi);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new st(`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(_i(i.status))throw new st(`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 Ai(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Pi);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 st(`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(_i(s.status))throw new st(`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 Zt(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(),Pi);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new st(`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(_i(s.status))throw new st(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await fx(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 fx(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ji(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=Jp.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: ${Jp.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Qt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Pi);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 st(`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(_i(n.status))throw new st(`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 Zp(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 mx(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 Cc(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 vo(t,e){let r=fc(e);if(!e.mirror)return{spec:r,host:Pr(r)};let n=t?q(t)?.mirrorWrite:void 0;return{spec:r,host:Pr(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function Pr(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new _c(r)}if(t.host==="bitbucket"){let r=e?.bitbucketEmail??process.env.BITBUCKET_EMAIL,n=e?.token??process.env.BITBUCKET_API_TOKEN;if(r&&n)return new Pc(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new Ac(r)}return new jc}var Cr,st,Pi,Jp,Pc,_c,Ac,jc,er=S(()=>{"use strict";D();pe();Cr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},st=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Pi=5e3;Jp=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Pc=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 Cr(`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 addPRInlineComment(e,r,n,o,i){let s=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:i},inline:{path:n,to:o}})});if(!s.ok)throw new Error(`bitbucket inline comment PR #${r} ${n}:${o}: ${s.status} ${await s.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()}`)}},_c=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 Cr(`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 m=(await d.json()).jobs??[];for(let f of m.filter(y=>y.conclusion==="failure")){let y=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!y.ok)continue;let w=await y.text();u.push(`### CI job: ${f.name}
|
|
20
|
+
`;Q$(this.currentPath,r,"utf-8")}asWritable(){return new nx({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||!qp(this.currentPath)||tx(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;qp(n)&&(r>=this.cfg.maxFiles?rx(n):Yp(n,`${this.currentPath}.${r+1}`))}Yp(this.currentPath,`${this.currentPath}.1`)}}}});function _i(t){return t===429||t>=500}function Jp(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
21
|
+
`+t.slice(t.length-e)}async function Zt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Pi);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new st(`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(_i(i.status))throw new st(`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 Ai(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Pi);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 st(`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(_i(s.status))throw new st(`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 Qt(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(),Pi);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new st(`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(_i(s.status))throw new st(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await mx(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 mx(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ji(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=Zp.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: ${Zp.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function er(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Pi);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 st(`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(_i(n.status))throw new st(`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 Qp(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 hx(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 Pc(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 tr(t,e){let r=mc(e);if(!e.mirror)return{spec:r,host:_r(r)};let n=t?V(t)?.mirrorWrite:void 0;return{spec:r,host:_r(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function _r(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new Ac(r)}if(t.host==="bitbucket"){let r=e?.bitbucketEmail??process.env.BITBUCKET_EMAIL,n=e?.token??process.env.BITBUCKET_API_TOKEN;if(r&&n)return new _c(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new jc(r)}return new Nc}var Pr,st,Pi,Zp,_c,Ac,jc,Nc,Kt=S(()=>{"use strict";D();de();Pr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},st=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Pi=5e3;Zp=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];_c=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 Pr(`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 addPRInlineComment(e,r,n,o,i){let s=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:i},inline:{path:n,to:o}})});if(!s.ok)throw new Error(`bitbucket inline comment PR #${r} ${n}:${o}: ${s.status} ${await s.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()}`)}},Ac=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 Pr(`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 getBranchCi(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=await fetch(`${o}/commits/${encodeURIComponent(r)}`,{headers:n});if(!i.ok)return null;let s=(await i.json()).sha;return s?{ci:await this.fetchCiStatus(e,s),headSha:s}:null}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}`;try{let i=await fetch(`${o}/pulls/${r}`,{headers:n});if(!i.ok)return;let s=(await i.json()).head?.sha;return s?await this.getCiFailureLogForSha(e,s):void 0}catch{return}}async getCiFailureLogForSha(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}/actions/runs?head_sha=${r}&per_page=20`,{headers:n});if(!s.ok)return;let a=(await s.json()).workflow_runs??[],c=[];for(let l of a.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${o}/actions/runs/${l.id}/jobs?per_page=50`,{headers:n});if(!u.ok)continue;let p=(await u.json()).jobs??[];for(let d of p.filter(m=>m.conclusion==="failure")){let m=await fetch(`${o}/actions/jobs/${d.id}/logs`,{headers:n});if(!m.ok)continue;let f=await m.text();c.push(`### CI job: ${d.name}
|
|
22
22
|
|
|
23
|
-
${
|
|
23
|
+
${Jp(f,8e3)}`)}}return c.length===0?void 0:Jp(c.join(`
|
|
24
24
|
|
|
25
|
-
`),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s={Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:s});if(!a.ok)throw new Error(`github PR #${r}: ${a.status} ${await a.text()}`);let c=(await a.json()).head?.sha;if(!c)throw new Error(`github PR #${r}: no head sha`);let l=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/comments`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({body:i,commit_id:c,path:n,line:o,side:"RIGHT"})});if(!l.ok)throw new Error(`github inline comment PR #${r} ${n}:${o}: ${l.status} ${await l.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()}`)}},
|
|
26
|
-
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function wx(t,e,r){return new Promise((n,o)=>{let i=tr.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 tf(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Nc(t,e,r){return new Promise(n=>{let o=tr.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 bx(t){try{let e=await fetch(t);return e.ok?new tf(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function af(t,e=443,r=nf){let n=`${t}:${e}`,o=ef.get(n);if(o)return o;let i=kx(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return ef.set(n,i),i}async function kx(t,e,r){if(!rf)return!1;let n=8e3;if(await Nc(t,e,n))return!0;let o=await wx(t,e,n),i=tr.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=yx(o);if(!c)break;let l=await bx(c);if(!l)break;if(s.push(l.toString()),tr.setDefaultCACertificates([...i,...s]),await Nc(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 Nc(t,e,n)}var rf,Qp,ef,nf,cf=S(()=>{"use strict";He();rf=typeof tr.getCACertificates=="function"&&typeof tr.setDefaultCACertificates=="function",Qp=!1,ef=new Map,nf=t=>console.warn(t)});function pf(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function at(t,e,r){of();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(sf(s)&&await af(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function vx(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function $x(){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 Oc(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=$x(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await at(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&&vx(l.status,u)){await lf(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await lf(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function rr(t){let e;try{e=await at(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 ff(t){try{let e=await at(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function xx(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=uf.get(o);if(i)return i;let s=await at(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 uf.set(o,l.id),l.id}async function mf(t,e,r,n=$o){let o=await xx(t,e,r,n);await Oc(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 hf(t,e,r){return await(await Oc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function gf(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Oc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function yf(t,e){let r=df.get(e);if(r)return r;let n=await at(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 df.set(e,i.id),i.id}async function wf(t,e,r,n,o,i=$o){let s=await yf(t,e),a=await at(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 bf(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await at(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 $f(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 xf(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 Sf(t,e){let r=e.stageField??$o,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=${vf}&$top=200`,s=await at(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);let a=await s.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>Rf(c,r))}async function Ef(t,e,r=$o){let n=`/api/issues/${encodeURIComponent(e)}?fields=${vf}`,o=await at(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Rf(await o.json(),r)}async function Tf(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Ex}&$top=500`,o=await at(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=$f(s.attachments);return c&&(a.attachments=c),a})}function Tx(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 Rf(t,e=$o){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=$f(t.attachments);a&&(s.attachments=a);let c=Tx(t.links);return c&&(s.links=c),s}async function If(t,e){let r=await Rx(t,e);return r.length>0?r:Ix(t,e)}async function Rx(t,e){let r=await yf(t,e),n=await at(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:Cf(s.bundle)});return i}async function Ix(t,e){let r=`project: ${e}`,n=await at(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:Cf(s.projectCustomField?.bundle)});return i}function Cf(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var lf,$o,uf,df,kf,Sx,vf,Ex,_r=S(()=>{"use strict";cf();lf=t=>new Promise(e=>setTimeout(e,t));$o="Stage",uf=new Map;df=new Map;kf="attachments(id,name,url,size,mimeType)",Sx="links(direction,linkType(name),issues(idReadable))",vf=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${kf},${Sx}`,Ex=`id,text,created,author(login),${kf}`});function vt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function yn(t){return t instanceof st}async function Pf(t,e){let r=q(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 rr({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:vt(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:vt(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 Jt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){yn(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:vt(c)}),o.push({kind:"github",present:!0,ok:!1,detail:vt(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 Zt(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){yn(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:vt(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:vt(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Qt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){yn(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:vt(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:vt(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 Ai(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){yn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:vt(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Ai(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){yn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:vt(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Ai(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){yn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:vt(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=mn(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 Kt(a);if(c==="invalid"){let l="Claude refused this token \u2014 refresh it with `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 Kt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),8e3);try{let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","content-type":"application/json"},body:JSON.stringify({model:Cx,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:e.signal});return n.status===200?"valid":n.status===401||n.status===403?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function _f(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 Cx,wn=S(()=>{"use strict";pe();er();_r();Cx="claude-haiku-4-5-20251001"});import Px from"node:http";import Lc from"node:crypto";function Ni(){let t=Mc(Lc.randomBytes(32)),e=Mc(Lc.createHash("sha256").update(t).digest()),r=Mc(Lc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function Uc(t){let e=new URL(_x);return e.search=new URLSearchParams({response_type:"code",client_id:Af,redirect_uri:t.redirectUri,scope:jx,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function Ox(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 jf(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 Lx(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 Bc(t){let e=await fetch(Ax,{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:Af,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return Lx(await e.json())}async function Fc(t){let e=t.timeoutMs??Nx,r=Px.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=Uc({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 m=new URL(p.url??"/",o);if(m.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(Ox(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>Bc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Nf(t){let e=await Fc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
|
|
27
|
-
${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var
|
|
25
|
+
`),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s={Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:s});if(!a.ok)throw new Error(`github PR #${r}: ${a.status} ${await a.text()}`);let c=(await a.json()).head?.sha;if(!c)throw new Error(`github PR #${r}: no head sha`);let l=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/comments`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({body:i,commit_id:c,path:n,line:o,side:"RIGHT"})});if(!l.ok)throw new Error(`github inline comment PR #${r} ${n}:${o}: ${l.status} ${await l.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()}`)}},jc=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 Pr(`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=hx(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 addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{headers:this.headers(!1)});if(!s.ok)throw new Error(`gitlab MR !${r}: ${s.status} ${await s.text()}`);let a=(await s.json()).diff_refs;if(!a?.base_sha||!a.head_sha||!a.start_sha)throw new Error(`gitlab MR !${r}: no diff refs`);let c=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/discussions`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:i,position:{position_type:"text",new_path:n,new_line:o,base_sha:a.base_sha,head_sha:a.head_sha,start_sha:a.start_sha}})});if(!c.ok)throw new Error(`gitlab inline comment MR !${r} ${n}:${o}: ${c.status} ${await c.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()}`)}};Nc=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(Pc(e,r,"merge"))}async closePR(e,r,n){throw new Error(Pc(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Pc(e,r,"comment"))}}});import{X509Certificate as rf}from"node:crypto";import{readFileSync as gx}from"node:fs";import rr from"node:tls";function yx(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function sf(t=of){if(ef)return;ef=!0;let e=Q("EXTRA_CA_FILE");if(!(!e||!nf))try{let r=yx(gx(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}rr.setDefaultCACertificates([...rr.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 af(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 wx(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
26
|
+
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function bx(t,e,r){return new Promise((n,o)=>{let i=rr.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 rf(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Oc(t,e,r){return new Promise(n=>{let o=rr.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 kx(t){try{let e=await fetch(t);return e.ok?new rf(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function cf(t,e=443,r=of){let n=`${t}:${e}`,o=tf.get(n);if(o)return o;let i=vx(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return tf.set(n,i),i}async function vx(t,e,r){if(!nf)return!1;let n=8e3;if(await Oc(t,e,n))return!0;let o=await bx(t,e,n),i=rr.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=wx(o);if(!c)break;let l=await kx(c);if(!l)break;if(s.push(l.toString()),rr.setDefaultCACertificates([...i,...s]),await Oc(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 Oc(t,e,n)}var nf,ef,tf,of,lf=S(()=>{"use strict";Ke();nf=typeof rr.getCACertificates=="function"&&typeof rr.setDefaultCACertificates=="function",ef=!1,tf=new Map,of=t=>console.warn(t)});function ff(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function at(t,e,r){sf();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(af(s)&&await cf(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function $x(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function xx(){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 Lc(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=xx(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await at(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&&$x(l.status,u)){await uf(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await uf(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function nr(t){let e;try{e=await at(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 mf(t){try{let e=await at(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Sx(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=df.get(o);if(i)return i;let s=await at(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 df.set(o,l.id),l.id}async function hf(t,e,r,n=xo){let o=await Sx(t,e,r,n);await Lc(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 gf(t,e,r){return await(await Lc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function yf(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Lc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function wf(t,e){let r=pf.get(e);if(r)return r;let n=await at(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 pf.set(e,i.id),i.id}async function bf(t,e,r,n,o,i=xo){let s=await wf(t,e),a=await at(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 kf(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await at(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 xf(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 Sf(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 Ef(t,e){let r=e.stageField??xo,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=${$f}&$top=200`,s=await at(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);let a=await s.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>If(c,r))}async function Rf(t,e,r=xo){let n=`/api/issues/${encodeURIComponent(e)}?fields=${$f}`,o=await at(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return If(await o.json(),r)}async function Tf(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Rx}&$top=500`,o=await at(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=xf(s.attachments);return c&&(a.attachments=c),a})}function Tx(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 If(t,e=xo){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=xf(t.attachments);a&&(s.attachments=a);let c=Tx(t.links);return c&&(s.links=c),s}async function Cf(t,e){let r=await Ix(t,e);return r.length>0?r:Cx(t,e)}async function Ix(t,e){let r=await wf(t,e),n=await at(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:Pf(s.bundle)});return i}async function Cx(t,e){let r=`project: ${e}`,n=await at(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:Pf(s.projectCustomField?.bundle)});return i}function Pf(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var uf,xo,df,pf,vf,Ex,$f,Rx,Ar=S(()=>{"use strict";lf();uf=t=>new Promise(e=>setTimeout(e,t));xo="Stage",df=new Map;pf=new Map;vf="attachments(id,name,url,size,mimeType)",Ex="links(direction,linkType(name),issues(idReadable))",$f=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${vf},${Ex}`,Rx=`id,text,created,author(login),${vf}`});function bt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function bn(t){return t instanceof st}async function _f(t,e){let r=V(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 nr({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:bt(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:bt(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 Zt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){bn(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:bt(c)}),o.push({kind:"github",present:!0,ok:!1,detail:bt(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 Qt(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){bn(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:bt(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:bt(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await er(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){bn(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:bt(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:bt(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 Ai(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){bn(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:bt(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Ai(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){bn(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:bt(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Ai(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){bn(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:bt(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=gn(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 Ht(a);if(c==="invalid"){let l="Claude refused this token \u2014 refresh it with `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 Ht(t){let e=new AbortController,r=setTimeout(()=>e.abort(),8e3);try{let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","content-type":"application/json"},body:JSON.stringify({model:Px,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:e.signal});return n.status===200?"valid":n.status===401||n.status===403?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function Af(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 Px,kn=S(()=>{"use strict";de();Kt();Ar();Px="claude-haiku-4-5-20251001"});import _x from"node:http";import Mc from"node:crypto";function Ni(){let t=Dc(Mc.randomBytes(32)),e=Dc(Mc.createHash("sha256").update(t).digest()),r=Dc(Mc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function Bc(t){let e=new URL(Ax);return e.search=new URLSearchParams({response_type:"code",client_id:jf,redirect_uri:t.redirectUri,scope:Nx,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function Lx(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 Nf(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 Mx(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 Fc(t){let e=await fetch(jx,{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:jf,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return Mx(await e.json())}async function Gc(t){let e=t.timeoutMs??Ox,r=_x.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=Bc({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 m=new URL(p.url??"/",o);if(m.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(Lx(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>Fc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Of(t){let e=await Gc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
|
|
27
|
+
${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var jf,Ax,jx,Uc,Nx,Ox,Dc,Kc=S(()=>{"use strict";jf="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Ax="https://platform.claude.com/oauth/authorize",jx="https://platform.claude.com/v1/oauth/token",Uc="https://platform.claude.com/oauth/code/callback",Nx="org:create_api_key user:profile user:inference",Ox=12e4,Dc=t=>Buffer.from(t).toString("base64url")});import{spawn as Dx}from"node:child_process";function jr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Dx(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var Oi=S(()=>{"use strict"});import{existsSync as or,mkdirSync as Wf,readFileSync as qc,writeFileSync as vn}from"node:fs";import{homedir as Yx}from"node:os";import{join as Tt}from"node:path";import{simpleGit as Vx}from"simple-git";function Eo(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Tt(t,o);or(s)||(vn(s,i),r.push(o))}return r}function ir(t,e,r){let n=Tt(Yx(),".codepipe","profiles",t,"context-config");return Wf(n,{recursive:!0}),vn(Tt(n,"project.yaml"),e.projectYaml),vn(Tt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Di(t,e,r){if(or(e))for(let n of $n){let o=Tt(e,n),i=Tt(t,n);if(!(!or(o)||or(i)))try{vn(i,qc(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 xn(t){let e=Tt(t,".gitignore"),r=or(e)?qc(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if($n.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
28
28
|
`)?"":`
|
|
29
|
-
`;return
|
|
29
|
+
`;return vn(e,r+i+zx.join(`
|
|
30
30
|
`)+`
|
|
31
|
-
`),!0}async function
|
|
32
|
-
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;
|
|
33
|
-
`)){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);
|
|
31
|
+
`),!0}async function qf(t,e){try{if(!or(Tt(t,".git")))return;let r=Vx(t),n=(await r.raw(["ls-files","--",...$n])).split(`
|
|
32
|
+
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;xn(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 zc(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 Yc(t){let e=new Map;for(let r of $n){let n=Tt(t,r);or(n)&&e.set(r,qc(n))}return e}function Vc(t,e){Wf(t,{recursive:!0});for(let[r,n]of e){let o=Tt(t,r);or(o)||vn(o,n)}}var $n,zx,Wt=S(()=>{"use strict";ct();$n=["project.yaml","regimen.yaml"];zx=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Xx,mkdirSync as Jx,rmSync as Zx,writeFileSync as Xc}from"node:fs";import{dirname as Qx,isAbsolute as eS,join as zf,normalize as Fi}from"node:path";import{simpleGit as Xf}from"simple-git";async function Jc(t,e){let r=Fi(t),o=(Bi.get(r)??Promise.resolve()).catch(()=>{}).then(e);Bi.set(r,o);try{return await o}finally{Bi.get(r)===o&&Bi.delete(r)}}async function Te(t,e,r){return Jc(t,()=>Zc(t,e,r))}async function Zc(t,e,r){if(!Xx(zf(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=Se(t,a.path);if(a.deleted){Zx(c,{force:!0});continue}Jx(Qx(c),{recursive:!0}),a.encoding==="base64"?Xc(c,Buffer.from(a.content,"base64")):Xc(c,a.content)}let n=Xf(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+=Ui)await n.raw(["add","-A","-f","--",...o.slice(a,a+Ui)]);for(let a=0;a<i.length;a+=Ui)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+Ui)]);await n.raw(["reset","-q","--",...$n]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await zc(t))}async function zc(t){let e=Xf(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Yf;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 oS(e);if(i.length>0&&i.every(a=>tS.has(a)||Vf.test(a)||rS.test(a))){for(let a of i)Vf.test(a)?await nS(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 ${Yf} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function nS(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(`
|
|
33
|
+
`)){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);Xc(Se(e,r),i.join(`
|
|
34
34
|
`)+(i.length>0?`
|
|
35
|
-
`:""))}async function
|
|
36
|
-
`).map(r=>r.trim()).filter(Boolean)}function
|
|
37
|
-
`)),(a.written.length>0||a.removed.length>0)&&r.info(`[skills] context \u2192 .claude/skills: ${a.written.length} written`+(a.removed.length>0?`, ${a.removed.length} removed`:""));for(let u of a.skipped)r.warn(`[skills] "${u}" exists in .claude/skills but is not managed by CodePipe \u2014 your copy wins; rename one of them to get the context version`);return a}function
|
|
35
|
+
`:""))}async function oS(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
36
|
+
`).map(r=>r.trim()).filter(Boolean)}function Se(t,e){if(eS(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Fi(zf(t,e)),n=Fi(t+"/");if(r!==Fi(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Yf,tS,rS,Vf,Ui,Bi,ct=S(()=>{"use strict";Wt();Yf=3,tS=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),rS=/^model\/derived\//,Vf=/^tasks\/[^/]+\/comments\.jsonl$/,Ui=500,Bi=new Map});import{cpSync as fS,existsSync as Ro,mkdirSync as em,readFileSync as mS,readdirSync as hS,rmSync as tm,statSync as gS,writeFileSync as yS}from"node:fs";import{join as sr}from"node:path";function Sn(t,e,r){let n=sr(t,"skills"),o=sr(e,".claude","skills"),i=sr(o,wS),s=bS(i),a={written:[],removed:[],skipped:[]},c=kS(n);for(let u of s)c.includes(u)||(tm(sr(o,u),{recursive:!0,force:!0}),a.removed.push(u));let l=[];for(let u of c){let p=sr(o,u);if(Ro(p)&&!s.includes(u)){a.skipped.push(u);continue}em(o,{recursive:!0}),tm(p,{recursive:!0,force:!0}),fS(sr(n,u),p,{recursive:!0}),l.push(u),a.written.push(u)}(l.length>0||a.removed.length>0||Ro(i))&&(em(o,{recursive:!0}),yS(i,JSON.stringify({managed:l.sort()},null,2)+`
|
|
37
|
+
`)),(a.written.length>0||a.removed.length>0)&&r.info(`[skills] context \u2192 .claude/skills: ${a.written.length} written`+(a.removed.length>0?`, ${a.removed.length} removed`:""));for(let u of a.skipped)r.warn(`[skills] "${u}" exists in .claude/skills but is not managed by CodePipe \u2014 your copy wins; rename one of them to get the context version`);return a}function bS(t){if(!Ro(t))return[];try{let e=JSON.parse(mS(t,"utf-8"));return Array.isArray(e.managed)?e.managed.filter(r=>typeof r=="string"):[]}catch{return[]}}function kS(t){return Ro(t)?hS(t).filter(e=>{if(e.startsWith("."))return!1;let r=sr(t,e);try{return gS(r).isDirectory()&&Ro(sr(r,"SKILL.md"))}catch{return!1}}):[]}var wS,Gi=S(()=>{"use strict";wS=".codepipe-managed.json"});import{existsSync as ar,readFileSync as En,readdirSync as im}from"node:fs";import{join as el}from"node:path";import{simpleGit as sm}from"simple-git";import{parse as am}from"yaml";function cm(t){try{let e=Se(t,bo);if(!ar(e))return null;let r=am(En(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Ir.test(n)?null:{prefix:n}}catch{return null}}function lm(t){return`# Built-in tracker configuration \u2014 shared by every team member.
|
|
38
38
|
# The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
|
|
39
39
|
# later would orphan existing tasks/<KEY>/ directories.
|
|
40
40
|
prefix: ${t}
|
|
@@ -42,13 +42,13 @@ prefix: ${t}
|
|
|
42
42
|
# Statuses are the built-in default set for now:
|
|
43
43
|
# Backlog | To Do | In Progress | Review | Done | Rejected
|
|
44
44
|
# A configurable status set / pipeline mapping is a planned extension.
|
|
45
|
-
`}function
|
|
46
|
-
`}function
|
|
45
|
+
`}function tl(t=0){return`${t}
|
|
46
|
+
`}function SS(t){return t==="depends_on"||t==="subtask"}function ES(t){let e;try{e=am(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=kc.includes(r.type)?r.type:wo,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;SS(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 rl(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(`
|
|
47
47
|
`)+`
|
|
48
|
-
`}function
|
|
48
|
+
`}function Io(t,e){let r=Se(t,dn(e));return ar(r)?ES(En(r,"utf-8")):null}function um(t){let e=el(t,"tasks");if(!ar(e))return[];let r=[];for(let n of im(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Io(t,n.name);o&&r.push(o)}return r}function RS(t,e){let r=Se(t,`tasks/${e}/task.md`);if(ar(r))return ko(En(r,"utf-8"))}function Co(t,e,r={}){let n=r.withDescription?RS(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:TS(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function TS(t){return t.charAt(0).toUpperCase()+t.slice(1)}function IS(t){let e=Se(t,un);if(!ar(e))return 0;let r=Number.parseInt(En(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function CS(t,e){let r=el(t,"tasks");if(!ar(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of im(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 PS(t,e){return Math.max(IS(t),CS(t,e))+1}async function dm(t,e,r,n){return Jc(t,()=>_S(t,e,r,n))}async function _S(t,e,r,n){if(!ar(el(t,".git")))throw new Error(`context repo clone not found at ${t}`);await To(t);let o=null;for(let i=0;i<om;i++){let s=PS(t,e),a=`${e}-${s}`,c=[...r(a),{path:un,content:tl(s)}];try{return await Zc(t,c,n(a)),a}catch(l){if(o=l,await jS(t,n(a)),await To(t),AS(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${om} attempts: ${o instanceof Error?o.message:String(o)}`)}function AS(t,e){for(let r of e){let n=Se(t,r.path);if(!ar(n)||(r.encoding==="base64"?En(n).toString("base64"):En(n,"utf-8"))!==r.content)return!1}return!0}async function To(t){let e=sm(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 jS(t,e){let r=sm(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
|
|
49
49
|
`)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
|
|
50
50
|
`).some(i=>i.trim()===e.split(`
|
|
51
|
-
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var
|
|
51
|
+
`)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var om,Hi=S(()=>{"use strict";D();ct();om=5});function Rn(t,e,r,n){return[{path:"README.md",content:YS(t,e)},{path:".gitignore",content:US()},{path:"CLAUDE.md",content:FS(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:BS()},{path:"knowledge/README.md",content:GS()},{path:"knowledge/build.yaml",content:qS()},{path:"actions/README.md",content:KS()},{path:"roles/README.md",content:HS()},{path:"skills/README.md",content:WS()},{path:"model/README.md",content:NS()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:DS()},{path:"adr/README.md",content:OS()},{path:"adr/0000-template.md",content:LS()},{path:"adr/INDEX.md",content:MS()},{path:ht,content:ao()},...t.trackerProvider==="internal"?[{path:bo,content:lm(t.youtrackProjectKey??$i)},{path:un,content:tl()}]:[]]}function NS(){return`# model/ \u2014 the project map
|
|
52
52
|
|
|
53
53
|
A graph of the project built from **git history and task artifacts**: files
|
|
54
54
|
and directories connected by the fact of changing together and the fact of
|
|
@@ -75,7 +75,7 @@ asset \u2014 treat it like \`knowledge/\`.
|
|
|
75
75
|
|
|
76
76
|
Every YAML file carries \`modelFormatVersion\`; a reader that meets a
|
|
77
77
|
different version treats it as "rebuild needed", not as an error.
|
|
78
|
-
`}function
|
|
78
|
+
`}function OS(){return`# ADR \u2014 architecture decision records
|
|
79
79
|
|
|
80
80
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
81
81
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -103,7 +103,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
103
103
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
104
104
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
105
105
|
open a PR to this repository.
|
|
106
|
-
`}function
|
|
106
|
+
`}function LS(){return`# ADR-NNNN: <title>
|
|
107
107
|
|
|
108
108
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
109
109
|
- **Date:** YYYY-MM-DD
|
|
@@ -125,12 +125,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
125
125
|
## Alternatives considered
|
|
126
126
|
|
|
127
127
|
- **<alternative>** \u2014 why it was rejected.
|
|
128
|
-
`}function
|
|
128
|
+
`}function MS(){return`# ADR index
|
|
129
129
|
|
|
130
130
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
131
131
|
|
|
132
132
|
(no accepted ADRs yet)
|
|
133
|
-
`}function
|
|
133
|
+
`}function DS(){return`# Audit
|
|
134
134
|
|
|
135
135
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
136
136
|
project appends only to its own file \u2014
|
|
@@ -139,14 +139,14 @@ project appends only to its own file \u2014
|
|
|
139
139
|
|
|
140
140
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
141
141
|
shared aggregate here.
|
|
142
|
-
`}function
|
|
142
|
+
`}function It(t,e,r,n,o=Je,i){let s=t.trackerProvider==="internal";return{projectYaml:s?VS(t):zS(t,r,n),regimenYaml:XS(t.automationLevel,s?!0:e,s,o,i)}}function US(){return`# codepipe project config is local to each member's workspace
|
|
143
143
|
project.yaml
|
|
144
144
|
regimen.yaml
|
|
145
145
|
|
|
146
146
|
# codepipe runtime
|
|
147
147
|
session.log
|
|
148
148
|
apply-queue.json
|
|
149
|
-
`}function
|
|
149
|
+
`}function BS(){return`# Index prompt
|
|
150
150
|
|
|
151
151
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
152
152
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -203,7 +203,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
203
203
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
204
204
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
205
205
|
empty or unavailable, say so briefly rather than inventing content.
|
|
206
|
-
`}function
|
|
206
|
+
`}function FS(t){return`# Project context for the CodePipe agent
|
|
207
207
|
|
|
208
208
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
209
209
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -231,7 +231,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
231
231
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
232
232
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
233
233
|
only after the analysis is approved.
|
|
234
|
-
`}function
|
|
234
|
+
`}function GS(){return`# Knowledge
|
|
235
235
|
|
|
236
236
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
237
237
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -248,7 +248,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
248
248
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
249
249
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
250
250
|
any merge conflict in it as noise (either side converges on the next run).
|
|
251
|
-
`}function
|
|
251
|
+
`}function KS(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
|
|
252
252
|
|
|
253
253
|
One \`<id>.yml\` per action. Every file here appears as a button on the
|
|
254
254
|
project's **RUN** tab; an action with \`params\` opens a small wizard first.
|
|
@@ -287,7 +287,7 @@ steps:
|
|
|
287
287
|
Parameter values are passed to the commands **only as env vars** \u2014 reference
|
|
288
288
|
them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
|
|
289
289
|
command text itself.
|
|
290
|
-
`}function
|
|
290
|
+
`}function HS(){return`# roles/ \u2014 who reviews your work
|
|
291
291
|
|
|
292
292
|
A **role** is a critic with a narrow view and its own curated context: one
|
|
293
293
|
\`<name>.md\` per role. Roles review a plan before the work starts, review the
|
|
@@ -315,7 +315,7 @@ You are the security critic. \u2026the body is the role's prompt\u2026
|
|
|
315
315
|
|
|
316
316
|
Keep \`refs\` short and specific: the value of a role is a NARROW view, and
|
|
317
317
|
"give it everything" is exactly the failure this design avoids.
|
|
318
|
-
`}function
|
|
318
|
+
`}function WS(){return`# skills/ \u2014 procedures the agent can invoke
|
|
319
319
|
|
|
320
320
|
A **skill** is a directory with a \`SKILL.md\`: a description of when to use it,
|
|
321
321
|
a body with the steps, and any files the steps need beside it (scripts,
|
|
@@ -374,7 +374,7 @@ A third-party marketplace **must** name a full commit sha: its skills run beside
|
|
|
374
374
|
your checked-out code with the agent's credentials, and a branch would let that
|
|
375
375
|
code change between two runs of the same task. Nothing from a marketplace is
|
|
376
376
|
active until it is listed in \`plugins\`.
|
|
377
|
-
`}function
|
|
377
|
+
`}function qS(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
378
378
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
379
379
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
380
380
|
#
|
|
@@ -390,7 +390,7 @@ active until it is listed in \`plugins\`.
|
|
|
390
390
|
# - name: test
|
|
391
391
|
# run: npm test
|
|
392
392
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
393
|
-
`}function
|
|
393
|
+
`}function YS(t,e){return`# ${e.name}
|
|
394
394
|
|
|
395
395
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
396
396
|
|
|
@@ -416,7 +416,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
416
416
|
pipeline \u2014 don't edit them by hand.
|
|
417
417
|
|
|
418
418
|
Automation level: **${t.automationLevel}**.
|
|
419
|
-
`}function
|
|
419
|
+
`}function VS(t){return`# Project description for CodePipe.
|
|
420
420
|
id: ${t.projectId}
|
|
421
421
|
name: ${t.name}
|
|
422
422
|
|
|
@@ -441,9 +441,9 @@ adapters:
|
|
|
441
441
|
# Branch (must keep the <TASK_ID> placeholder).
|
|
442
442
|
branch:
|
|
443
443
|
pattern: codepipe/<TASK_ID>
|
|
444
|
-
${
|
|
444
|
+
${pm()}${fm(t)}
|
|
445
445
|
repos:
|
|
446
|
-
${
|
|
446
|
+
${mm(t)}
|
|
447
447
|
# A repo may declare a mirror \u2014 a repository CodePipe owns that stands in for
|
|
448
448
|
# origin for the whole pipeline: task branches, PRs and merges happen there and
|
|
449
449
|
# your own repository is never written. All-or-nothing: either every repo
|
|
@@ -453,7 +453,7 @@ ${fm(t)}
|
|
|
453
453
|
# host: github
|
|
454
454
|
# owner: your-org
|
|
455
455
|
# repo: <project>-api-mirror
|
|
456
|
-
`}function
|
|
456
|
+
`}function pm(){return`
|
|
457
457
|
# Git workflow. Omit this whole section for the default single-branch flow
|
|
458
458
|
# (\`simple\`) \u2014 nothing changes from today. Presets bind branch ROLES to your
|
|
459
459
|
# real branch names (names differ across projects: develop vs dev, main vs a
|
|
@@ -468,21 +468,21 @@ ${fm(t)}
|
|
|
468
468
|
# integration: develop
|
|
469
469
|
# stable: master
|
|
470
470
|
# # release_pattern: "release/*" # with flow: release
|
|
471
|
-
`}function
|
|
471
|
+
`}function fm(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
|
|
472
472
|
# Languages the agent writes in, per area. \`auto\` = mirror the language of
|
|
473
473
|
# the user's material. Also editable from the dashboard: project card \u2192
|
|
474
474
|
# Settings \u2192 Language.
|
|
475
475
|
language:
|
|
476
476
|
${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
|
|
477
477
|
`)}
|
|
478
|
-
`}function
|
|
478
|
+
`}function mm(t){return t.repos.length===0?` [] # add repos here
|
|
479
479
|
`:t.repos.map(e=>` - name: ${e.name}
|
|
480
480
|
host: ${e.host}
|
|
481
481
|
owner: ${e.owner}
|
|
482
482
|
repo: ${e.repoName}
|
|
483
483
|
mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
|
|
484
484
|
default_branch: ${e.defaultBranch}`:"")).join(`
|
|
485
|
-
`)}function
|
|
485
|
+
`)}function zS(t,e,r){let n=e?`
|
|
486
486
|
tracker_url: ${e}`:`
|
|
487
487
|
# tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
|
|
488
488
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -530,7 +530,7 @@ ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
|
|
|
530
530
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
531
531
|
${o}`:` # project_key: \u2026
|
|
532
532
|
# tracker_url: https://your.youtrack.cloud
|
|
533
|
-
poll_interval_sec: 60`,s=
|
|
533
|
+
poll_interval_sec: 60`,s=mm(t);return`# Project description for CodePipe.
|
|
534
534
|
id: ${t.projectId}
|
|
535
535
|
name: ${t.name}
|
|
536
536
|
|
|
@@ -562,10 +562,10 @@ adapters:
|
|
|
562
562
|
# Branch (must keep the <TASK_ID> placeholder).
|
|
563
563
|
branch:
|
|
564
564
|
pattern: codepipe/<TASK_ID>
|
|
565
|
-
${
|
|
565
|
+
${pm()}${fm(t)}
|
|
566
566
|
repos:
|
|
567
567
|
${s}
|
|
568
|
-
`}function
|
|
568
|
+
`}function XS(t,e,r=!1,n=Je,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
|
|
569
569
|
# model in the recommended per-role split, so CodePipe set a single default
|
|
570
570
|
# your subscription can serve for all roles. Tune per role later from the
|
|
571
571
|
# dashboard (Project Settings \u2192 llm.models) or by editing this file.
|
|
@@ -762,36 +762,36 @@ ${a}
|
|
|
762
762
|
# sandbox quota (how many runners the account may occupy), enforced by the HUB
|
|
763
763
|
# and sized on the farm. A solo 'codepipe up' runs one worker. (ADR-0030)
|
|
764
764
|
|
|
765
|
-
`}var
|
|
766
|
-
${u.trim()}`)}}let i=
|
|
767
|
-
${l.trim()}`)}let a=e.defaultBranch??"main";return await i.checkout(["-B",a,`origin/${a}`]).catch(()=>{}),i}async function
|
|
768
|
-
${
|
|
765
|
+
`}var Nr=S(()=>{"use strict";D();Hi()});function vm(t){km=t}function lt(t,e="info"){km(t,e)}var km,qi=S(()=>{"use strict";km=t=>console.log(t)});import{homedir as pE,tmpdir as BO}from"node:os";import{existsSync as fE,mkdirSync as mE,mkdtempSync as GO,rmSync as KO}from"node:fs";import{join as ol}from"node:path";import{simpleGit as il}from"simple-git";function _e(t,e,r){let n=r??ol(pE(),".codepipe","repos");return ol(n,t,e)}async function cr(t,e,r={}){let n=_e(t,e.name,r.baseDir),o=r.cloneUrlOverride??al(e);if(!fE(ol(n,".git"))){mE(n,{recursive:!0});let c=il();lt(`[git] clone ${o} \u2192 ${n}`);try{await c.clone(o,n)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`git clone failed: ${o}
|
|
766
|
+
${u.trim()}`)}}let i=il(n),s=(await i.remote(["get-url","origin"]).catch(()=>"")||"").toString().trim();s&&s!==o&&(lt(`[git] ${e.name}: origin ${s} \u2192 ${o} (spec changed)`),await i.remote(["set-url","origin",o]));try{await i.fetch()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git fetch failed in ${n}
|
|
767
|
+
${l.trim()}`)}let a=e.defaultBranch??"main";return await i.checkout(["-B",a,`origin/${a}`]).catch(()=>{}),i}async function Tn(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function hE(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&<(`[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 Tn(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Tn(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([...sl,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function gE(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await Tn(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Tn(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 xm(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 gE(t,i,()=>hE(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;await Tn(t,m)||(m=`origin/${u??c}`);let f=(await t.revparse([m])).trim(),g=0;if(f===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{g=parseInt((await t.raw(["rev-list","--count",`${s}..${f}`]).catch(()=>"1")).trim(),10)||1,await t.checkout(["-B",a,m]);try{await t.raw([...sl,"cherry-pick",d])}catch(v){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=v instanceof Error?v.message:String(v);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
768
|
+
${y.trim()}`)}}let w=(await t.revparse(["HEAD"])).trim(),b=r.push!==!1;if(b){let v=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(v)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:w,pushed:b,...g>0?{baseMoved:g}:{}}}async function Sm(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 Em(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await Tn(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(`
|
|
769
769
|
`).map(m=>m.trim()).filter(m=>m.length>0),l=new Set(o.map(m=>m.toUpperCase())),u=[],p=0;for(let m of c)(await t.raw(["show","-s","--format=%(trailers:key=CodePipe-Task,valueonly)",m])).split(`
|
|
770
|
-
`).map(w=>w.trim().toUpperCase()).filter(w=>w.length>0).some(w=>l.has(w))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...
|
|
771
|
-
${
|
|
772
|
-
`).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 Tm(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var
|
|
773
|
-
`))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),m=l.slice(2),f=
|
|
774
|
-
`)){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:
|
|
775
|
-
`))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 ts(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=te(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=te(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function
|
|
776
|
-
`).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 gh(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 yh=S(()=>{"use strict"});function ns(t){return he("container",t,zE)}function wh(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function bh(t,e,r,n){let o=[],i=u=>{let p=he("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:wh(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,XE)}},s=(u,p)=>{let d=he("component",t,u),m=n.get(d);return{key:d,level:"component",label:wh(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],y=[p,...m.map(i)],w=[...m.map(h=>({kind:"contains",from:p.key,to:he("code",t,h.path)})),...f.map(h=>({kind:"contains",from:p.key,to:he("component",t,h)}))];c(u,y,w)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Mt(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:Ea(t,u),content:_a(m)})},l={key:ns(t),level:"container",label:t,...n.get(ns(t))?{entityId:n.get(ns(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 kh(t,e){let r=[ns(t)];for(let n of e.components)r.push(he("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(he("code",t,o.path));return r.sort()}var zE,XE,vh=S(()=>{"use strict";D();zE=".";XE=12});import{simpleGit as xh}from"simple-git";function Nr(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 Eh(t,e="HEAD"){let r=xh(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 jo(t,n)}}async function jo(t,e){let n=await xh(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 $h(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Th(t,e){let r=[...t].sort((f,y)=>f.path<y.path?-1:f.path>y.path?1:0),n=new Map,o=new Map;for(let f of r){let y=$h(f.path);n.has(y)||n.set(y,[]),n.get(y).push(f);let w=y;for(;w!=="";){let h=$h(w);o.has(h)||o.set(h,new Set),o.get(h).add(w),w=h}}let i=f=>[...o.get(f)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),y=(n.get(f)??[]).length+i(f).length;if(y<=s)s-=y,c.add(f),l.push(...i(f));else{if(f==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(f)}}let u=[],p=new Map,d=new Map,m=0;for(let f of[...c].sort()){let y=n.get(f)??[];p.set(f,y),d.set(f,i(f)),m+=y.length,f!==""&&u.push(f)}for(let f of a)u.push(f);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:m}}}var Sh,No=S(()=>{"use strict";Sh=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Rh,readFileSync as Ih}from"node:fs";import{join as Ch}from"node:path";import{simpleGit as JE}from"simple-git";import{parse as Ph}from"yaml";function Or(t){let e={ignore:Sh,containerNodeCap:ZE,cochange:{...ot},issueKeyPattern:null,enabled:!0},r=Ch(t,"regimen.yaml");if(!Rh(r))return e;let n;try{n=Ph(Ih(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(m=>typeof m=="string"&&m.trim().length>0):e.ignore,c=(m,f)=>typeof m=="number"&&Number.isInteger(m)&&m>0?m:f,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,enabled:s.enabled!==!1}}function bl(t,e){let r=Ch(t,ao(e));if(!Rh(r))return null;let n=Ph(Ih(r,"utf-8")),o=lo(n);if(!o.ok)throw new Error(`model: ${ao(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function kl(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await Eh(r,t.ref??"HEAD"),s=Nr(o.ignore),a=i.files.filter(k=>!s(k.path)),c=Th(a,o.containerNodeCap),l=bl(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await JE(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=gh(await hh(r,l.builtFromCommit,i.commit)),p=new Map((await jo(r,l.builtFromCommit)).map(b=>[b.path,b.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(k=>[k.path,k.blobHash])));let d=new Map(a.map(k=>[k.path,k.blobHash])),m=fh({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:kh(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=bh(e,i.commit,c,m.byKey),y=Nr([...o.ignore,...Pn]),w=ph({repo:e,headTimeSec:i.commitTimeSec,filesets:await dh(r,i.commit,o.cochange.windowCommits),pathToCurrent:ts(m.table),currentPaths:new Set(a.map(k=>k.path)),ignored:y,settings:o.cochange}),h=[{path:ao(e),content:Aa(m.table)},...f.files.map(k=>({path:k.path,content:k.content})),{path:xa(e),content:$r({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:w})}];return{repo:e,headCommit:i.commit,files:h,emittedShardPaths:new Set(f.files.map(k=>k.path)),counts:{...f.counts,correlates:w.length},identityTable:m.table,entityByKey:m.byKey}}var ZE,vl=S(()=>{"use strict";D();rs();mh();yh();vh();No();ZE=1500});import{existsSync as Ah,readFileSync as jh,readdirSync as QE}from"node:fs";import{join as $l}from"node:path";import{parse as Nh}from"yaml";function eT(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 Oh(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<Ra)return null;let s=i/Math.min(n.size,o.size),a=eT(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*_h)/_h;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[Ee(t.taskKey),Ee(e.taskKey)]:[Ee(e.taskKey),Ee(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Lh(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=Oh(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 Mh(t,e,r,n){let o=Ee(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=Oh(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 os(t){let e=$l(t,"model/facts/events");if(!Ah(e))return[];let r=[];for(let n of QE(e).sort())if(n.endsWith(".yaml"))try{let o=Dt(Nh(jh($l(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Dh(t){let e=$l(t,kr);if(!Ah(e))return[];try{let r=co(Nh(jh(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function is(t){return $r({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var _h,xl=S(()=>{"use strict";D();_h=1e4});var Oo={};Ke(Oo,{collectSearchRows:()=>Bh,readContextIndexHub:()=>tT,rebuildSearchIndex:()=>Fh,searchIndexPath:()=>ls,searchModelIndex:()=>rT,toFtsQuery:()=>Gh});import{existsSync as An,readFileSync as _n,readdirSync as as}from"node:fs";import{join as $t}from"node:path";import{parse as cs}from"yaml";function ls(t){return $t(t,".git","codepipe-model-index.sqlite")}function tT(t){let e=$t(t,"regimen.yaml");if(!An(e))return"off";try{let n=cs(_n(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 Uh(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function ss(t){return t.length>fi?t.slice(0,fi):t}function Sl(t){if(!An(t))return[];let e=[];for(let r of as(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=$t(t,r.name);r.isDirectory()?e.push(...Sl(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Bh(t){let e=[];for(let i of Sl($t(t,"model/derived/structure"))){let s;try{s=cs(_n(i,"utf-8"))}catch{continue}let a=Mt(s);if(a.ok)for(let c of a.value.nodes){let l=te(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:ss(`${l.path} ${c.label??""}`.trim())})}}let r=$t(t,"model/facts/events");if(An(r)){for(let i of as(r).sort())if(i.endsWith(".yaml"))try{let s=Dt(cs(_n($t(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:ss(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=$t(t,"model/facts/annotations");if(An(n)){let i=new Map;for(let s of Sl($t(t,"model/facts/identity")))try{let a=cs(_n(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 as(n).sort())if(s.endsWith(".md"))try{let a=_n($t(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:ss(c[2].trim())})}catch{}}let o=$t(t,"adr");if(An(o))for(let i of as(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=_n($t(o,i),"utf-8").split(`
|
|
777
|
-
`).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:ss(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function
|
|
770
|
+
`).map(w=>w.trim().toUpperCase()).filter(w=>w.length>0).some(w=>l.has(w))?p++:u.push(m);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let m of u)try{await t.raw([...sl,"cherry-pick","--allow-empty","--keep-redundant-commits",m])}catch(f){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let g=f instanceof Error?f.message:String(f);throw new Error(`rewrite_cluster_branch: replaying ${m.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
|
|
771
|
+
${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 Rm(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 al(t){return t.mirror?$m(t.mirror.host,t.mirror.owner,t.mirror.repoName):$m(t.host,t.owner,t.repoName)}function $m(t,e,r){return t==="github"?`git@github.com:${e}/${r}.git`:t==="gitlab"?`git@gitlab.com:${e}/${r}.git`:`git@bitbucket.org:${e}/${r}.git`}function In(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 Yi(t){return(await il().listRemote(["--heads",t])).split(`
|
|
772
|
+
`).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 Tm(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var sl,Cn=S(()=>{"use strict";qi();sl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as yE,createDecipheriv as wE,createHash as bE,createPrivateKey as kE,createPublicKey as cl,diffieHellman as Im,generateKeyPairSync as Cm,hkdfSync as Pm,randomBytes as vE}from"node:crypto";function Vi(){let{publicKey:t,privateKey:e}=Cm("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function We(t){let e=Buffer.from(t,"base64");return(bE("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function qt(t,e){let r=cl({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Cm("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Im({privateKey:o,publicKey:r}),c=Buffer.from(Pm("sha256",a,Buffer.concat([i,s]),_m,32)),l=vE(12),u=yE("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),m=u.getAuthTag(),f={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:m.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(f),"utf-8").toString("base64")}function Pn(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=kE({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=cl({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=cl(n).export({type:"spki",format:"der"}),a=Im({privateKey:n,publicKey:o}),c=Buffer.from(Pm("sha256",a,Buffer.concat([i,s]),_m,32)),l=wE("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 _m,ut=S(()=>{"use strict";_m=Buffer.from("devpipe-sealedbox-v1","utf-8")});function _o(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 Ao(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 jo(t,e=process.env){if(!t)return!1;let r=`https://${Ft}:${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 ll(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 jm(t,e=process.env){return ll(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>_o(t,e),e)}function Nm(t,e=process.env){return ll(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Ao(t,e),e)}function Om(t,e=process.env){return ll(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Ft}:${encodeURIComponent(t)}@bitbucket.org/`,()=>jo(t,e),e)}var zi=S(()=>{"use strict";D()});import{existsSync as qm,readFileSync as Ym,writeFileSync as Vm}from"node:fs";import{join as zm}from"node:path";import{isMap as Wm,parseDocument as Xm}from"yaml";async function Jm(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||!Xt(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=zm(t,"project.yaml");if(!qm(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Xm(Ym(o,"utf-8"));return Xi(i,r).set("default_branch",n),Vm(o,i.toString()),{repoName:r,defaultBranch:n}}function Zm(t,e,r){let n=zm(t,"project.yaml");if(!qm(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=Xm(Ym(n,"utf-8"));Xi(o,e).set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}),Vm(n,o.toString())}function Xi(t,e){let r=t.get("repos"),o=(r&&typeof r=="object"&&"items"in r?r.items:[]).find(i=>Wm(i)&&String(i.get("name")??i.get("repo")??"")===e);if(!Wm(o))throw new Error(`repo "${e}" not found in project.yaml repos[]`);return o}var Ji=S(()=>{"use strict";D()});import{existsSync as ml,readFileSync as hl}from"node:fs";import{join as gl}from"node:path";import{simpleGit as oh}from"simple-git";import{parse as yl}from"yaml";function sh(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(FE.source,"g")}function ah(t){let e=gl(t,"project.yaml");if(ml(e))try{let o=yl(hl(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=gl(t,"tracker","config.yaml");if(ml(r))try{let o=yl(hl(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function ch(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 GE(t,e,r){let o=await oh(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
|
|
773
|
+
`))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),m=l.slice(2),f=wl.exec(u)??ih.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:f?Number(f[1]):null,isMerge:m.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:ch(c[3]),churn:l+u})}return i}async function KE(t,e){let n=await oh(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
|
|
774
|
+
`)){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:ch(s[3]),churn:a+c})}return o}function HE(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(wl,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(wl,"").replace(ih,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let w of c.files){let b=o.get(w.path)??w.path;s(b)||m.set(b,(m.get(b)??0)+w.churn)}if(m.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[w,b]of m){let v=fe("code",e,w),y=g.files.find(k=>k.key===v);if(y)y.churn=(y.churn??0)+b;else{let k=i.get(v);g.files.push({key:v,...k?{entityId:k}:{},churn:b})}}if(d.length>0){let w=new Set([...g.links?.tasks??[],...d]);w.delete(u),g.links={...g.links??{},tasks:[...w].sort()}}a.set(u,g)}return a}function nh(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 lh(t){let e=await GE(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 KE(t.repoDir,r.sha))}return HE({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function uh(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?nh(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=nh(es(t,i),s);if(!a){o++;continue}n.push({path:$r(i),content:rn(a)})}return{files:n,skippedPipeline:o}}function es(t,e){let r=gl(t,$r(e));if(!ml(r))return null;try{let n=Dt(yl(hl(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var FE,wl,ih,bl=S(()=>{"use strict";D();FE=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,wl=/\(#(\d+)\)\s*$/,ih=/^Merge pull request #(\d+)\b/});import{simpleGit as WE}from"simple-git";async function ph(t,e,r){let o=await WE(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
|
|
775
|
+
`))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 ts(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=te(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=te(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function fh(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 b of n){let v=new Set;for(let E of b.files){let $=o.get(E)??E;!i.has($)||s($)||v.add($)}if(v.size<2||v.size>a.commitFileCap)continue;let y=Math.max(0,r-b.timeSec),k=Math.pow(.5,y/c),C=[...v].sort();for(let E of C)l.set(E,(l.get(E)??0)+k);for(let E=0;E<C.length;E++)for(let $=E+1;$<C.length;$++){let _=`${C[E]}\0${C[$]}`;u.set(_,(u.get(_)??0)+k),p.set(_,(p.get(_)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[b,v]of u){if((p.get(b)??0)<a.supportMin)continue;let[y,k]=b.split("\0"),C=(l.get(y)??0)+(l.get(k)??0)-v,E=C>0?v/C:0;E<m||d.push({a:y,b:k,weight:Math.round(E*dh)/dh})}let f=new Map;for(let b of d)for(let v of[b.a,b.b])f.has(v)||f.set(v,[]),f.get(v).push(b);let g=new Map;for(let[,b]of f)b.sort((v,y)=>y.weight-v.weight||(v.a<y.a?-1:v.a>y.a?1:v.b<y.b?-1:1)).slice(0,a.topK).forEach(v=>g.set(v,(g.get(v)??0)+1));return[...g.entries()].filter(([,b])=>b===2).map(([b])=>b).map(b=>({kind:"correlates",from:fe("code",e,b.a),to:fe("code",e,b.b),weight:b.weight})).sort((b,v)=>b.from<v.from?-1:b.from>v.from?1:b.to<v.to?-1:1)}var An,dh,rs=S(()=>{"use strict";D();An=["package-lock.json","pnpm-lock.yaml","yarn.lock"];dh=1e4});import{createHash as qE}from"node:crypto";function VE(t,e,r,n){for(let o=0;;o++){let s=`e_${qE("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function mh(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,m=[],f=new Map,g=($,_)=>{d.add(_),f.set(_,$.entityId),m.push($)},w=[];for(let $ of u)l.has($.currentKey)&&!d.has($.currentKey)?g({...$,status:"active",lastSeen:r},$.currentKey):w.push($);let b=[],v=[];for(let $ of w){let _=te($.currentKey),j=_?i.get(_.path):void 0;if(_&&j){let B=fe(_.level,e,j.finalPath);if(l.has(B)&&!d.has(B)){b.push({entity:$,newKey:B,untilCommit:j.commit}),d.add(B);continue}}v.push($)}let y=[];if(s){let $=new Map;for(let j of c){if(d.has(j))continue;let B=te(j);if(B?.level!=="code")continue;let K=a.get(B.path);K&&$.set(K,$.has(K)?null:j)}let _=new Map;for(let j of v){let B=te(j.currentKey);if(B?.level!=="code")continue;let K=s.get(B.path);K&&_.set(K,_.has(K)?null:j)}for(let j of v){let B=te(j.currentKey),K=B?.level==="code"?s.get(B.path):void 0,A=K?$.get(K):void 0;K&&A&&_.get(K)===j&&!d.has(A)?(b.push({entity:j,newKey:A,untilCommit:r}),d.add(A)):y.push(j)}}else y.push(...v);let k=new Map;for(let $ of b){let _=te($.entity.currentKey),j=te($.newKey);if(_?.level!=="code"||!j)continue;let B=_.path,K=j.path;for(let A=B.lastIndexOf("/");A>0;A=B.lastIndexOf("/",A-1)){let h=B.slice(0,A),F=B.slice(A+1);if(!K.endsWith(`/${F}`))continue;let L=K.slice(0,K.length-F.length-1);if(L===h)continue;let q=`${h}\0${L}`,ee=k.get(q);k.set(q,{count:(ee?.count??0)+1,commit:ee&&ee.commit>$.untilCommit?ee.commit:$.untilCommit})}}let C=[...k.entries()].filter(([,$])=>$.count>=YE).map(([$,_])=>{let[j,B]=$.split("\0");return{from:j,to:B,commit:_.commit}}).sort(($,_)=>_.from.length-$.from.length||($.from<_.from?-1:1)),E=[];for(let $ of y){let _=te($.currentKey),j=!1;if(_?.level==="component")for(let B of C){let K=null;if(_.path===B.from?K=B.to:_.path.startsWith(`${B.from}/`)&&(K=B.to+_.path.slice(B.from.length)),K===null)continue;let A=fe("component",e,K);l.has(A)&&!d.has(A)&&(b.push({entity:$,newKey:A,untilCommit:B.commit}),d.add(A),j=!0);break}j||E.push($)}for(let $ of b.sort((_,j)=>_.newKey<j.newKey?-1:1))g({...$.entity,currentKey:$.newKey,aliases:[...$.entity.aliases??[],{key:$.entity.currentKey,until:$.untilCommit}],status:"active",lastSeen:r},$.newKey);for(let $ of E)m.push({...$,status:"orphaned"});for(let $ of c){if(d.has($))continue;let _=VE(e,$,r,p);p.add(_),g({entityId:_,currentKey:$,firstSeen:n,lastSeen:r,status:"active"},$)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}var YE,hh=S(()=>{"use strict";D();YE=5});import{simpleGit as zE}from"simple-git";async function gh(t,e,r){let n=zE(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
|
|
776
|
+
`).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 yh(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 wh=S(()=>{"use strict"});function ns(t){return fe("container",t,XE)}function bh(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function kh(t,e,r,n){let o=[],i=u=>{let p=fe("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:bh(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,JE)}},s=(u,p)=>{let d=fe("component",t,u),m=n.get(d);return{key:d,level:"component",label:bh(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],g=[p,...m.map(i)],w=[...m.map(b=>({kind:"contains",from:p.key,to:fe("code",t,b.path)})),...f.map(b=>({kind:"contains",from:p.key,to:fe("component",t,b)}))];c(u,g,w)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Mt(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:Ra(t,u),content:Aa(m)})},l={key:ns(t),level:"container",label:t,...n.get(ns(t))?{entityId:n.get(ns(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 vh(t,e){let r=[ns(t)];for(let n of e.components)r.push(fe("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(fe("code",t,o.path));return r.sort()}var XE,JE,$h=S(()=>{"use strict";D();XE=".";JE=12});import{simpleGit as Sh}from"simple-git";function Or(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 Rh(t,e="HEAD"){let r=Sh(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 No(t,n)}}async function No(t,e){let n=await Sh(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 xh(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Th(t,e){let r=[...t].sort((f,g)=>f.path<g.path?-1:f.path>g.path?1:0),n=new Map,o=new Map;for(let f of r){let g=xh(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let w=g;for(;w!=="";){let b=xh(w);o.has(b)||o.set(b,new Set),o.get(b).add(w),w=b}}let i=f=>[...o.get(f)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),g=(n.get(f)??[]).length+i(f).length;if(g<=s)s-=g,c.add(f),l.push(...i(f));else{if(f==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(f)}}let u=[],p=new Map,d=new Map,m=0;for(let f of[...c].sort()){let g=n.get(f)??[];p.set(f,g),d.set(f,i(f)),m+=g.length,f!==""&&u.push(f)}for(let f of a)u.push(f);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:m}}}var Eh,Oo=S(()=>{"use strict";Eh=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Ih,readFileSync as Ch}from"node:fs";import{join as Ph}from"node:path";import{simpleGit as ZE}from"simple-git";import{parse as _h}from"yaml";function Lr(t){let e={ignore:Eh,containerNodeCap:QE,cochange:{...ot},issueKeyPattern:null,enabled:!0},r=Ph(t,"regimen.yaml");if(!Ih(r))return e;let n;try{n=_h(Ch(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(m=>typeof m=="string"&&m.trim().length>0):e.ignore,c=(m,f)=>typeof m=="number"&&Number.isInteger(m)&&m>0?m:f,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,enabled:s.enabled!==!1}}function kl(t,e){let r=Ph(t,lo(e));if(!Ih(r))return null;let n=_h(Ch(r,"utf-8")),o=po(n);if(!o.ok)throw new Error(`model: ${lo(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function vl(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await Rh(r,t.ref??"HEAD"),s=Or(o.ignore),a=i.files.filter(v=>!s(v.path)),c=Th(a,o.containerNodeCap),l=kl(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await ZE(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=yh(await gh(r,l.builtFromCommit,i.commit)),p=new Map((await No(r,l.builtFromCommit)).map(k=>[k.path,k.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(v=>[v.path,v.blobHash])));let d=new Map(a.map(v=>[v.path,v.blobHash])),m=mh({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:vh(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=kh(e,i.commit,c,m.byKey),g=Or([...o.ignore,...An]),w=fh({repo:e,headTimeSec:i.commitTimeSec,filesets:await ph(r,i.commit,o.cochange.windowCommits),pathToCurrent:ts(m.table),currentPaths:new Set(a.map(v=>v.path)),ignored:g,settings:o.cochange}),b=[{path:lo(e),content:ja(m.table)},...f.files.map(v=>({path:v.path,content:v.content})),{path:Sa(e),content:xr({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:w})}];return{repo:e,headCommit:i.commit,files:b,emittedShardPaths:new Set(f.files.map(v=>v.path)),counts:{...f.counts,correlates:w.length},identityTable:m.table,entityByKey:m.byKey}}var QE,$l=S(()=>{"use strict";D();rs();hh();wh();$h();Oo();QE=1500});import{existsSync as jh,readFileSync as Nh,readdirSync as eR}from"node:fs";import{join as xl}from"node:path";import{parse as Oh}from"yaml";function tR(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 Lh(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<Ia)return null;let s=i/Math.min(n.size,o.size),a=tR(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*Ah)/Ah;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[xe(t.taskKey),xe(e.taskKey)]:[xe(e.taskKey),xe(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Mh(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=Lh(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 Dh(t,e,r,n){let o=xe(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=Lh(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 os(t){let e=xl(t,"model/facts/events");if(!jh(e))return[];let r=[];for(let n of eR(e).sort())if(n.endsWith(".yaml"))try{let o=Dt(Oh(Nh(xl(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Uh(t){let e=xl(t,vr);if(!jh(e))return[];try{let r=uo(Oh(Nh(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function is(t){return xr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Ah,Sl=S(()=>{"use strict";D();Ah=1e4});var Lo={};Ge(Lo,{collectSearchRows:()=>Fh,readContextIndexHub:()=>rR,rebuildSearchIndex:()=>Gh,searchIndexPath:()=>ls,searchModelIndex:()=>nR,toFtsQuery:()=>Kh});import{existsSync as Nn,readFileSync as jn,readdirSync as as}from"node:fs";import{join as kt}from"node:path";import{parse as cs}from"yaml";function ls(t){return kt(t,".git","codepipe-model-index.sqlite")}function rR(t){let e=kt(t,"regimen.yaml");if(!Nn(e))return"off";try{let n=cs(jn(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 Bh(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function ss(t){return t.length>mi?t.slice(0,mi):t}function El(t){if(!Nn(t))return[];let e=[];for(let r of as(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=kt(t,r.name);r.isDirectory()?e.push(...El(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Fh(t){let e=[];for(let i of El(kt(t,"model/derived/structure"))){let s;try{s=cs(jn(i,"utf-8"))}catch{continue}let a=Mt(s);if(a.ok)for(let c of a.value.nodes){let l=te(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:ss(`${l.path} ${c.label??""}`.trim())})}}let r=kt(t,"model/facts/events");if(Nn(r)){for(let i of as(r).sort())if(i.endsWith(".yaml"))try{let s=Dt(cs(jn(kt(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:ss(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=kt(t,"model/facts/annotations");if(Nn(n)){let i=new Map;for(let s of El(kt(t,"model/facts/identity")))try{let a=cs(jn(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 as(n).sort())if(s.endsWith(".md"))try{let a=jn(kt(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:ss(c[2].trim())})}catch{}}let o=kt(t,"adr");if(Nn(o))for(let i of as(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=jn(kt(o,i),"utf-8").split(`
|
|
777
|
+
`).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:ss(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function Gh(t){let e=Fh(t),r=await Bh();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(ls(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 Kh(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 nR(t,e,r){let n=await Bh();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");Nn(ls(t))||await Gh(t);let o=Kh(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),Pa),s=new n.DatabaseSync(ls(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
|
|
778
778
|
bm25(model_fts) AS rank
|
|
779
|
-
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
|
|
780
|
-
`)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function
|
|
781
|
-
`).map(r=>r.trim()).filter(r=>r.startsWith(`${
|
|
782
|
-
`)){let[a,c]=s.trim().split(/\s+/);!a||!c||!/^[0-9a-f]{40}$/.test(a)||c.startsWith("refs/heads/")&&i.set(c.slice(11),a)}return i}var
|
|
783
|
-
`,{mode:384})}function CT(t){return ng()[t]}function hs(t,e){let r=ng();r[t]=e,IT(r)}function gs(t,e){let r=qe(e),n=CT(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 ${Cl()}.`);return r}var Pl=S(()=>{"use strict";He();ut()});import{setTimeout as PT}from"node:timers/promises";import _T from"ws";function ys(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new _T(r)}async function cr(t,e,r){return lr(t,e,"/projects",r)}async function og(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function ws(t,e,r,n){return lr(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function ig(t,e,r,n){return lr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function sg(t,e,r,n){return lr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function ag(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 K(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function bs(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function _l(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new K(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function cg(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await _l(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 PT(r.delayMs??1500)}throw o}async function lg(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 Fo(e)}if(!r.ok)throw new K(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function ug(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new K(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function dg(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function pg(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 K(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function fg(t,e,r,n,o){return lr(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Go(t,e,r,n){return lr(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Al(t,e,r,n){await lr(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function mg(t,e,r,n){return lr(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function hg(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 K(o.status,s,a)}return s}async function se(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function lr(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 K(o.status,s,a)}return s}async function ks(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new K(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var K,Fo,Ne=S(()=>{"use strict";K=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};Fo=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{existsSync as Mg,readFileSync as XT,readdirSync as JT}from"node:fs";import{join as Dg}from"node:path";import{simpleGit as ZT}from"simple-git";import{parse as QT}from"yaml";function Es(t){let e=new Map,r=Dg(t,di);if(!Mg(r))return e;let n;try{n=QT(XT(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 Sr({modelFormatVersion:2,repos:e})}function Ug(t,e){let r=Dg(t,e);if(!Mg(r))return[];let n=[];for(let o of JT(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Ug(t,i)):n.push(i)}return n}async function Ts(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let m=`model/derived/structure/${d.repo}`;for(let f of Ug(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=Es(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:di,content:eR(i)});let s=os(t),a=Lh(s,r.halfLifeDays??ot.halfLifeDays);n.push({path:kr,content:is(a)});for(let d of e){let m=[];for(let f of s)for(let y of f.files)te(y.key)?.repo===d.repo&&m.push({kind:"touched_by",from:Ee(f.taskKey),to:y.key,...y.churn!==void 0?{weight:y.churn}:{}});n.push({path:Sa(d.repo),content:$r({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=ZT(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Ce(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(Lo(),Oo));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var Bg=S(()=>{"use strict";D();xl();ct()});var Cs={};Ke(Cs,{bootstrapDaemonModel:()=>rR,bootstrapModelForTargets:()=>Fl,bootstrapWorkspaceModel:()=>Wg,modelBootstrapCommand:()=>Bl,modelBuildCommand:()=>Ul,modelIndexExists:()=>Yg,rebuildWorkspaceModelIfStale:()=>oR,shouldAutoBootstrapModel:()=>nR,syncWorkspaceMirrors:()=>qg});import{existsSync as Is}from"node:fs";import{join as ur}from"node:path";import{cancel as tR,intro as Fg,log as Ll,outro as Ml}from"@clack/prompts";import{simpleGit as Dl}from"simple-git";function Rs(t){tR(t),process.exit(1)}function Gg(t,e,r){let n=t.spec.repos.filter(i=>!e||i.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let i of n){let s=i.mountAs==="."?t.root:ur(t.root,i.mountAs);if(!Is(ur(s,".git"))){r(`${i.name}: no local clone at ${s} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:i.name,dir:s,defaultBranch:i.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function Kg(t){let e=Dl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function Hg(t,e,r,n){let o=[];for(let i of e)try{let s=await kl({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await Kg(i)});o.push(s),n(`${i.name}: ${s.counts.code} files, ${s.counts.component} components, ${s.counts.correlates} co-change edges @ ${s.headCommit.slice(0,10)}`)}catch(s){throw new Error(`${i.name}: ${s instanceof Error?s.message:String(s)}`)}return o}async function Ul(t){Fg("codepipe model build");let e=_e();e||Rs("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=Or(e.contextDir),n=Gg(e,t.repo,s=>Ll.warn(s)),o=await Hg(e.contextDir,n,r,s=>Ll.info(s)),i=await Ts(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?Ml(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):Ml("model already up to date (no changes)")}catch(r){Rs(r instanceof Error?r.message:String(r))}}async function Bl(t){Fg("codepipe model bootstrap");let e=_e();e||Rs("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await Wg(e,t.repo,{onLog:r=>Ll.info(r)})}catch(r){Rs(r instanceof Error?r.message:String(r))}Ml("bootstrap complete")}async function Wg(t,e,r){let n=Gg(t,e,r.onLog);return Fl(t.contextDir,n,r)}async function Fl(t,e,r){let n=Or(t),o=await Hg(t,e,n,r.onLog),i=sh(t),s=ih(n.issueKeyPattern,i),a=Nr([...n.ignore,...Pn]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await ch({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:ts(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(m),r.onLog(`${p.repo}: ${m.size} task events mined from history`)}let{files:l,skippedPipeline:u}=lh(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Ce(t,l,`model: bootstrap ${l.length} task events from history`),await Ts(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function rR(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let s of r){let a=s.mountAs??s.name,c=a==="."?e.root:ur(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&Is(ur(c,".git"))?(await Dl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await ar(t,s),o.push({name:s.name,dir:je(t,s.name),defaultBranch:l}))}let i=await Fl(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function qg(t,e){let r=new Map;for(let n of t.repos){if(!n.mirror)continue;let o=n.mountAs==="."?t.root:ur(t.root,n.mountAs);if(!Is(ur(o,".git")))continue;let{syncUpstream:i}=await Promise.resolve().then(()=>(fs(),ps)),s=await i(n,o,{info:a=>e(`[mirror] ${a}`),warn:a=>e(`[mirror] ${a}`)});if(s.error||!s.upstreamHead){e(`[mirror] ${n.name}: sync failed (${s.error??"no upstream head"})`);continue}r.set(n.name,s.upstreamHead)}return r}function Yg(t){return Es(t).size>0}function nR(t){return Or(t).enabled&&!Yg(t)}async function oR(t,e={}){let r=e.onLog??(()=>{}),n=Or(t.contextDir),o=await qg(t,r);if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=Es(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:ur(t.root,l.mountAs);if(!Is(ur(u,".git")))continue;let p=Dl(u),d=l.defaultBranch||"main",m=null;if(l.mirror){if(m=o.get(l.name)??null,!m){r(`[mirror] ${l.name}: map not rebuilt \u2014 sync did not complete`);continue}}else e.fetch&&await p.fetch(["origin",d]).catch(()=>{});let f=m??await Kg({name:l.name,dir:u,defaultBranch:d}),y=(await p.revparse([f]).catch(()=>"")).trim();if(y){if(a.get(l.name)?.builtFromCommit===y){s.push(l.name);continue}try{c.push(await kl({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:y})),i.push(l.name)}catch(w){r(`[model] rebuild of ${l.name} failed: ${w instanceof Error?w.message:String(w)}`)}}}return c.length>0&&(await Ts(t.contextDir,c,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${i.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:i,skipped:s}}var Ko=S(()=>{"use strict";ct();Bg();vl();wl();rs();No();Rn();bt()});var zg={};Ke(zg,{computeDriftReport:()=>lR,supersededAdrIds:()=>Vg});import{existsSync as Gl,readFileSync as Kl,readdirSync as Hl}from"node:fs";import{join as jn}from"node:path";import{parse as iR}from"yaml";import{simpleGit as sR}from"simple-git";function cR(t,e){let r=jn(t,`model/derived/structure/${e}`),n=[],o="";if(!Gl(r))return{nodes:n,builtFromCommit:o};for(let i of Hl(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Mt(iR(Kl(jn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=te(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function Vg(t){let e=new Set,r=jn(t,"adr");if(!Gl(r))return e;for(let n of Hl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=Kl(jn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function lR(t,e,r){let{nodes:n,builtFromCommit:o}=cR(e,r),i=(await sR(t).revparse(["HEAD"])).trim(),s=await jo(t,i),a=new Map(s.map(k=>[k.path,k.blobHash])),c=[],l=[],u=new Set,p=[];for(let k of n){if(k.level==="component"){p.push(k);continue}u.add(k.path);let x=a.get(k.path);x?k.contentHash&&x.slice(0,aR)!==k.contentHash&&c.push(k.key):l.push(k.key)}let d=0,m=new Map,f=new Set;for(let k of s){let x=k.path.lastIndexOf("/"),b=x<0?"":k.path.slice(0,x);m.has(b)||m.set(b,new Set),m.get(b).add(k.path),u.has(k.path)||d++;let R=b;for(;R!==""&&!f.has(R);)f.add(R),R=R.includes("/")?R.slice(0,R.lastIndexOf("/")):""}let y=new Map;for(let k of u){let x=k.lastIndexOf("/"),b=x<0?"":k.slice(0,x);y.has(b)||y.set(b,new Set),y.get(b).add(k)}for(let k of p){if(!f.has(k.path)){l.push(k.key);continue}let x=y.get(k.path)??new Set,b=m.get(k.path)??new Set;(x.size!==b.size||[...x].some(E=>!b.has(E)))&&c.push(k.key)}let w=[],h=Vg(e);if(h.size>0){let k=jn(e,"model/facts/annotations"),x=new Map(n.filter(b=>b.entityId).map(b=>[b.entityId,b.key]));if(Gl(k))for(let b of Hl(k).sort()){if(!b.endsWith(".md"))continue;let R=b.replace(/\.md$/,""),E=x.get(R);if(E)try{(Kl(jn(k,b),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(A=>`ADR-${A.slice(4).padStart(4,"0")}`).some(A=>h.has(A))&&w.push(E)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(w)].sort(),newFiles:d}}var aR,Xg=S(()=>{"use strict";D();No();aR=12});import{execFileSync as wR}from"node:child_process";import{mkdtempSync as bR,mkdirSync as kR,readFileSync as Zg,rmSync as vR,writeFileSync as $R}from"node:fs";import{tmpdir as xR}from"node:os";import{dirname as SR,join as Qg}from"node:path";function ey(t="codepipe-context"){let e=bR(Qg(xR(),"codepipe-ssh-")),r=Qg(e,"id_ed25519");try{return wR("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Zg(r,"utf-8"),publicKey:Zg(`${r}.pub`,"utf-8").trim()}}finally{vR(e,{recursive:!0,force:!0})}}async function ty(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 ry(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 ny(t,e){kR(SR(t),{recursive:!0});let r=e.endsWith(`
|
|
779
|
+
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 Mo=S(()=>{"use strict";D()});var ps={};Ge(ps,{mirrorLag:()=>kR,syncUpstream:()=>bR});import{simpleGit as Qh}from"simple-git";async function bR(t,e,r,n){let o=Qh(e),i=t.defaultBranch??"main",s=n?.upstream??eg(t);if(!s)return{repo:t.name,upstreamHead:null,updated:!1,error:"repo spec has no host/owner/repo"};try{await o.fetch(s,`+refs/heads/*:${Mr}/*`,["--prune"]);let a=(await o.revparse([`${Mr}/${i}`]).catch(()=>"")).trim()||null;if(!a)return{repo:t.name,upstreamHead:null,updated:!1,error:`upstream has no branch '${i}'`};let c=n?.mirror??(t.mirror?tg(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await vR(o),u=await Cl(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let m=(await o.revparse([`${Mr}/${d}`]).catch(()=>"")).trim();!m||u.get(d)===m||p.push(`+${m}:refs/heads/${d}`)}return p.length===0?{repo:t.name,upstreamHead:a,updated:!1}:(await o.push([c,...p]),r.info(`${t.name}: mirror \u2190 ${p.length} branch(es), ${i} @ ${a.slice(0,10)}`),{repo:t.name,upstreamHead:a,updated:!0})}catch(a){let c=a instanceof Error?a.message.split(`
|
|
780
|
+
`)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function kR(t,e,r){let n=r?.mirror??(t.mirror?tg(t.mirror):null);if(!n)return null;let o=r?.upstream??eg(t);if(!o)return null;let i=Qh(e),s=t.defaultBranch??"main";try{let a=(await Cl(i,n,s)).get(s);if(!a)return null;let c=(await Cl(i,o,s)).get(s);if(!c)return null;if(c===a)return 0;let l=async()=>{let p=await i.raw(["rev-list","--count",`${a}..${c}`]).catch(()=>null);if(p===null)return null;let d=parseInt(p.trim(),10);return Number.isFinite(d)?d:null},u=await l();return u!==null?u:(await i.fetch(o,`+refs/heads/${s}:${Mr}/${s}`),await l())}catch{return null}}function eg(t){return!t.host||!t.owner||!t.repoName?null: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`}function tg(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 vR(t){return(await t.raw(["for-each-ref",Mr,"--format=%(refname)"]).catch(()=>"")).split(`
|
|
781
|
+
`).map(r=>r.trim()).filter(r=>r.startsWith(`${Mr}/`)).map(r=>r.slice(Mr.length+1))}async function Cl(t,e,r){let n=r?["--heads",e,r]:["--heads",e],o=await t.listRemote(n),i=new Map;for(let s of o.split(`
|
|
782
|
+
`)){let[a,c]=s.trim().split(/\s+/);!a||!c||!/^[0-9a-f]{40}$/.test(a)||c.startsWith("refs/heads/")&&i.set(c.slice(11),a)}return i}var Mr,fs=S(()=>{"use strict";Mr="refs/codepipe/upstream"});import{homedir as $R}from"node:os";import{existsSync as xR,mkdirSync as SR,readFileSync as ER,writeFileSync as RR}from"node:fs";import{dirname as TR,join as IR}from"node:path";function Pl(){return Q("FARM_PINS")??IR($R(),".codepipe","farm-pins.json")}function og(){let t=Pl();if(!xR(t))return{};try{return JSON.parse(ER(t,"utf-8"))}catch{return{}}}function CR(t){let e=Pl();SR(TR(e),{recursive:!0}),RR(e,JSON.stringify(t,null,2)+`
|
|
783
|
+
`,{mode:384})}function PR(t){return og()[t]}function hs(t,e){let r=og();r[t]=e,CR(r)}function gs(t,e){let r=We(e),n=PR(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 ${Pl()}.`);return r}var _l=S(()=>{"use strict";Ke();ut()});import{setTimeout as _R}from"node:timers/promises";import AR from"ws";function ys(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new AR(r)}async function lr(t,e,r){return ur(t,e,"/projects",r)}async function ig(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function ws(t,e,r,n){return ur(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function sg(t,e,r,n){return ur(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function ag(t,e,r,n){return ur(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function cg(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 W(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function bs(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Al(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new W(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function lg(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Al(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 _R(r.delayMs??1500)}throw o}async function ug(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 Go(e)}if(!r.ok)throw new W(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function dg(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new W(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function pg(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function fg(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 W(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function mg(t,e,r,n,o){return ur(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Ko(t,e,r,n){return ur(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function jl(t,e,r,n){await ur(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function hg(t,e,r,n){return ur(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function gg(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 W(o.status,s,a)}return s}async function ie(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function ur(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 W(o.status,s,a)}return s}async function ks(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new W(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var W,Go,Ae=S(()=>{"use strict";W=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};Go=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{existsSync as Dg,readFileSync as QR,readdirSync as eT}from"node:fs";import{join as Ug}from"node:path";import{simpleGit as tT}from"simple-git";import{parse as rT}from"yaml";function Rs(t){let e=new Map,r=Ug(t,pi);if(!Dg(r))return e;let n;try{n=rT(QR(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 nT(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return Er({modelFormatVersion:2,repos:e})}function Bg(t,e){let r=Ug(t,e);if(!Dg(r))return[];let n=[];for(let o of eT(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Bg(t,i)):n.push(i)}return n}async function Ts(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let m=`model/derived/structure/${d.repo}`;for(let f of Bg(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=Rs(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:pi,content:nT(i)});let s=os(t),a=Mh(s,r.halfLifeDays??ot.halfLifeDays);n.push({path:vr,content:is(a)});for(let d of e){let m=[];for(let f of s)for(let g of f.files)te(g.key)?.repo===d.repo&&m.push({kind:"touched_by",from:xe(f.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:Ea(d.repo),content:xr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=tT(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Te(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(Mo(),Lo));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var Fg=S(()=>{"use strict";D();Sl();ct()});var Ps={};Ge(Ps,{bootstrapDaemonModel:()=>iT,bootstrapModelForTargets:()=>Gl,bootstrapWorkspaceModel:()=>qg,modelBootstrapCommand:()=>Fl,modelBuildCommand:()=>Bl,modelIndexExists:()=>Vg,rebuildWorkspaceModelIfStale:()=>aT,shouldAutoBootstrapModel:()=>sT,syncWorkspaceMirrors:()=>Yg});import{existsSync as Cs}from"node:fs";import{join as dr}from"node:path";import{cancel as oT,intro as Gg,log as Ml,outro as Dl}from"@clack/prompts";import{simpleGit as Ul}from"simple-git";function Is(t){oT(t),process.exit(1)}function Kg(t,e,r){let n=t.spec.repos.filter(i=>!e||i.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let i of n){let s=i.mountAs==="."?t.root:dr(t.root,i.mountAs);if(!Cs(dr(s,".git"))){r(`${i.name}: no local clone at ${s} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:i.name,dir:s,defaultBranch:i.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function Hg(t){let e=Ul(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function Wg(t,e,r,n){let o=[];for(let i of e)try{let s=await vl({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await Hg(i)});o.push(s),n(`${i.name}: ${s.counts.code} files, ${s.counts.component} components, ${s.counts.correlates} co-change edges @ ${s.headCommit.slice(0,10)}`)}catch(s){throw new Error(`${i.name}: ${s instanceof Error?s.message:String(s)}`)}return o}async function Bl(t){Gg("codepipe model build");let e=Pe();e||Is("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=Lr(e.contextDir),n=Kg(e,t.repo,s=>Ml.warn(s)),o=await Wg(e.contextDir,n,r,s=>Ml.info(s)),i=await Ts(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?Dl(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):Dl("model already up to date (no changes)")}catch(r){Is(r instanceof Error?r.message:String(r))}}async function Fl(t){Gg("codepipe model bootstrap");let e=Pe();e||Is("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await qg(e,t.repo,{onLog:r=>Ml.info(r)})}catch(r){Is(r instanceof Error?r.message:String(r))}Dl("bootstrap complete")}async function qg(t,e,r){let n=Kg(t,e,r.onLog);return Gl(t.contextDir,n,r)}async function Gl(t,e,r){let n=Lr(t),o=await Wg(t,e,n,r.onLog),i=ah(t),s=sh(n.issueKeyPattern,i),a=Or([...n.ignore,...An]),c=[];for(let p of o){let d=e.find(f=>f.name===p.repo),m=await lh({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:ts(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(m),r.onLog(`${p.repo}: ${m.size} task events mined from history`)}let{files:l,skippedPipeline:u}=uh(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Te(t,l,`model: bootstrap ${l.length} task events from history`),await Ts(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function iT(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let s of r){let a=s.mountAs??s.name,c=a==="."?e.root:dr(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&Cs(dr(c,".git"))?(await Ul(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await cr(t,s),o.push({name:s.name,dir:_e(t,s.name),defaultBranch:l}))}let i=await Gl(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function Yg(t,e){let r=new Map;for(let n of t.repos){if(!n.mirror)continue;let o=n.mountAs==="."?t.root:dr(t.root,n.mountAs);if(!Cs(dr(o,".git")))continue;let{syncUpstream:i}=await Promise.resolve().then(()=>(fs(),ps)),s=await i(n,o,{info:a=>e(`[mirror] ${a}`),warn:a=>e(`[mirror] ${a}`)});if(s.error||!s.upstreamHead){e(`[mirror] ${n.name}: sync failed (${s.error??"no upstream head"})`);continue}r.set(n.name,s.upstreamHead)}return r}function Vg(t){return Rs(t).size>0}function sT(t){return Lr(t).enabled&&!Vg(t)}async function aT(t,e={}){let r=e.onLog??(()=>{}),n=Lr(t.contextDir),o=await Yg(t,r);if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=Rs(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:dr(t.root,l.mountAs);if(!Cs(dr(u,".git")))continue;let p=Ul(u),d=l.defaultBranch||"main",m=null;if(l.mirror){if(m=o.get(l.name)??null,!m){r(`[mirror] ${l.name}: map not rebuilt \u2014 sync did not complete`);continue}}else e.fetch&&await p.fetch(["origin",d]).catch(()=>{});let f=m??await Hg({name:l.name,dir:u,defaultBranch:d}),g=(await p.revparse([f]).catch(()=>"")).trim();if(g){if(a.get(l.name)?.builtFromCommit===g){s.push(l.name);continue}try{c.push(await vl({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:g})),i.push(l.name)}catch(w){r(`[model] rebuild of ${l.name} failed: ${w instanceof Error?w.message:String(w)}`)}}}return c.length>0&&(await Ts(t.contextDir,c,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${i.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:i,skipped:s}}var Ho=S(()=>{"use strict";ct();Fg();$l();bl();rs();Oo();Cn();yt()});var Xg={};Ge(Xg,{computeDriftReport:()=>pT,supersededAdrIds:()=>zg});import{existsSync as Kl,readFileSync as Hl,readdirSync as Wl}from"node:fs";import{join as On}from"node:path";import{parse as cT}from"yaml";import{simpleGit as lT}from"simple-git";function dT(t,e){let r=On(t,`model/derived/structure/${e}`),n=[],o="";if(!Kl(r))return{nodes:n,builtFromCommit:o};for(let i of Wl(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Mt(cT(Hl(On(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=te(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function zg(t){let e=new Set,r=On(t,"adr");if(!Kl(r))return e;for(let n of Wl(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=Hl(On(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function pT(t,e,r){let{nodes:n,builtFromCommit:o}=dT(e,r),i=(await lT(t).revparse(["HEAD"])).trim(),s=await No(t,i),a=new Map(s.map(v=>[v.path,v.blobHash])),c=[],l=[],u=new Set,p=[];for(let v of n){if(v.level==="component"){p.push(v);continue}u.add(v.path);let y=a.get(v.path);y?v.contentHash&&y.slice(0,uT)!==v.contentHash&&c.push(v.key):l.push(v.key)}let d=0,m=new Map,f=new Set;for(let v of s){let y=v.path.lastIndexOf("/"),k=y<0?"":v.path.slice(0,y);m.has(k)||m.set(k,new Set),m.get(k).add(v.path),u.has(v.path)||d++;let C=k;for(;C!==""&&!f.has(C);)f.add(C),C=C.includes("/")?C.slice(0,C.lastIndexOf("/")):""}let g=new Map;for(let v of u){let y=v.lastIndexOf("/"),k=y<0?"":v.slice(0,y);g.has(k)||g.set(k,new Set),g.get(k).add(v)}for(let v of p){if(!f.has(v.path)){l.push(v.key);continue}let y=g.get(v.path)??new Set,k=m.get(v.path)??new Set;(y.size!==k.size||[...y].some(E=>!k.has(E)))&&c.push(v.key)}let w=[],b=zg(e);if(b.size>0){let v=On(e,"model/facts/annotations"),y=new Map(n.filter(k=>k.entityId).map(k=>[k.entityId,k.key]));if(Kl(v))for(let k of Wl(v).sort()){if(!k.endsWith(".md"))continue;let C=k.replace(/\.md$/,""),E=y.get(C);if(E)try{(Hl(On(v,k),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(j=>`ADR-${j.slice(4).padStart(4,"0")}`).some(j=>b.has(j))&&w.push(E)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(w)].sort(),newFiles:d}}var uT,Jg=S(()=>{"use strict";D();Oo();uT=12});import{execFileSync as vT}from"node:child_process";import{mkdtempSync as $T,mkdirSync as xT,readFileSync as Qg,rmSync as ST,writeFileSync as ET}from"node:fs";import{tmpdir as RT}from"node:os";import{dirname as TT,join as ey}from"node:path";function ty(t="codepipe-context"){let e=$T(ey(RT(),"codepipe-ssh-")),r=ey(e,"id_ed25519");try{return vT("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Qg(r,"utf-8"),publicKey:Qg(`${r}.pub`,"utf-8").trim()}}finally{ST(e,{recursive:!0,force:!0})}}async function ry(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 ny(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 oy(t,e){xT(TT(t),{recursive:!0});let r=e.endsWith(`
|
|
784
784
|
`)?e:e+`
|
|
785
|
-
`;return
|
|
786
|
-
`,{mode:384})}var
|
|
787
|
-
`}async function
|
|
788
|
-
`))!==-1;){let
|
|
789
|
-
`)){let
|
|
790
|
-
${i}`.includes("--effort"))})}),
|
|
785
|
+
`;return ET(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var zl=S(()=>{"use strict"});import{existsSync as iy,mkdirSync as sy}from"node:fs";import{dirname as ay}from"node:path";import{simpleGit as Ln}from"simple-git";function IT(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 CT(t,e){return e?.contextWrite?.token?{user:vo(t),secret:e.contextWrite.token}:t===pn.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===pn.bitbucket?e?.bitbucket?.apiToken?{user:Ft,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function cy(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 As))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 js(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await ie(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new As(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=CT(Cr(s.cloneUrl),r);if(a){let c=await PT({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 _T({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 PT(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=IT(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(iy(`${r}/.git`)){let l=Ln(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Yc(r);await l.reset(["--hard",`origin/${s}`]),Vc(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else sy(ay(r),{recursive:!0}),await Ln().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await ly(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 _T(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=oy(i,n),a=ny(e.cloneUrl),c=e.branch;try{if(iy(`${r}/.git`)){let l=Ln(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=Yc(r);await l.reset(["--hard",`origin/${c}`]),Vc(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else sy(ay(r),{recursive:!0}),await Ln().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ln(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await ly(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 ly(t){let e=Ln(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 As,Xl=S(()=>{"use strict";D();Ae();Wt();zl();As=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as AT}from"node:child_process";function jT(){try{return AT("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function dy(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:jT(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var py=S(()=>{"use strict"});import{homedir as NT}from"node:os";import{mkdirSync as OT,readFileSync as LT,writeFileSync as MT,existsSync as fy}from"node:fs";import{dirname as DT,join as Zl}from"node:path";function UT(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function vt(t){let e=Q("SANDBOX_CONFIG");if(e)return e;let r=Zl(NT(),".codepipe","worker");return t?Zl(r,"profiles",t,"config.json"):Zl(r,"config.json")}function my(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Me(t){let e=vt(t),r=null;return fy(e)&&(r=JSON.parse(LT(e,"utf-8"))),r?(r.planningLane=UT(),r):null}function hy(t,e){let r=vt(e);OT(DT(r),{recursive:!0}),MT(r,JSON.stringify(t,null,2)+`
|
|
786
|
+
`,{mode:384})}var Ns=S(()=>{"use strict";Ke();fy(".env")&&process.loadEnvFile(".env")});import BT from"ws";var Mn,Ql=S(()=>{"use strict";Mn=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 BT(e)}}});import{hostname as FT}from"node:os";async function Ur(t){let e=Me(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${vt(t.profile)}.`),process.exit(1));let r=t.name??FT(),n=dy({projects:t.projects??[],llm:t.llm??null}),o=new Mn(t.hub.replace(/\/$/,"")),i=Vi(),s=We(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});hy({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 ${vt(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 gy=S(()=>{"use strict";ut();py();Ns();Ql()});function yy(t){return t?`Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in ${t}, regardless of the language the user writes in (the project pinned ${t} for the chat).`:"Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in the language of the user's most recent chat message. When the user switches language mid-conversation, switch with them. Judge the language by the human prose only: ignore code snippets, file paths and identifiers. If a message is too short to tell (a bare keyword, pure code), keep the language of the conversation so far."}function Os(t){return t?`Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in ${t} (the project's configured language), unless your prompt pins a different language for a specific output. In-repo content (code, code comments, commit messages) follows the project's existing conventions and any explicit instructions in your prompt.`:"Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in the language of the task description and user input embedded in your prompt, NOT the language the surrounding instructions are written in. Judge that language by the human prose only, ignoring code snippets, file paths and identifiers. In-repo content (code, code comments, commit messages) follows the project's existing conventions instead."}function wy(t){return t?`[Session note: the instructions from the start of this conversation remain in force. Reply in ${t} \u2014 including the brief status notes between tool calls.]`:"[Session note: the instructions from the start of this conversation remain in force. Reply in the language of the user's message above \u2014 including the brief status notes between tool calls. Judge the language by the human prose, ignoring code snippets and identifiers.]"}function Dn(t){let e=t?.responseLanguage;if(typeof e!="string")return;let r=e.trim();return r.length>0&&r.toLowerCase()!=="auto"?r:void 0}var Ls=S(()=>{"use strict"});import{spawn as GT}from"node:child_process";function eu(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function HT(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 WT(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Br(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function tu(t,e){let r=[{type:"text",text:t}];return e&&r.push({type:"text",text:e}),JSON.stringify({type:"user",message:{role:"user",content:r}})+`
|
|
787
|
+
`}async function $y(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Yt;let r=Dn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",yy(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim()),e.effort&&e.effort.trim().length>0&&(await ru(t)?n.push("--effort",e.effort.trim()):console.warn(`[claude] effort '${e.effort.trim()}' requested but this Claude Code does not support --effort \u2014 running at the default effort`));for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,i=l=>{if(o)try{o(l)}catch{}},s=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let m of d?.content??[]){let f=m.type;if(f==="text"){let g=String(m.text??"").trim();g&&i({ts:u,kind:"text",author:"agent",text:eu(g,by)})}else if(f==="tool_use"){let g=String(m.name??""),w=m.input?.file_path??m.input?.path,b=HT(w,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:g,...b?{file:b}:{}})}}return}if(p==="user"){let d=l.message;for(let m of d?.content??[])if(m.type==="tool_result"){let f=m.is_error===!0,g=f?eu(WT(m.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:f,...g?{text:g}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();i({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&i({ts:u,kind:"system",author:"agent",text:d})}};return i({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=GT(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,m=!1,f=null,g=()=>{d=!0,p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),ky)};e.signal?.addEventListener("abort",g,{once:!0});let w=null,b=()=>{w&&clearTimeout(w),w=setTimeout(()=>{m=!0,console.warn(`[claude:chat] idle for ${vy}ms \u2014 ending session`),p.kill("SIGTERM"),f=setTimeout(()=>p.kill("SIGKILL"),ky)},vy)},v=()=>{f&&clearTimeout(f),w&&clearTimeout(w),e.signal?.removeEventListener("abort",g)},y=!0,k=$=>{if(!(!y||p.stdin.destroyed))try{p.stdin.write($)}catch{}};k(tu(e.prompt)),b(),(async()=>{try{for await(let $ of e.interactive.inbox){if(d||!y)break;if(b(),$.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:eu($.text,by)}),k(tu($.text,wy(r)));else{k(tu(KT)),y=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let C="",E=$=>{let _;try{_=JSON.parse($)}catch{return}c(_)};p.stdout.on("data",$=>{s.push($),b(),C+=$;let _;for(;(_=C.indexOf(`
|
|
788
|
+
`))!==-1;){let j=C.slice(0,_).trim();C=C.slice(_+1),j&&E(j)}}),p.stderr.on("data",$=>{s.push($);for(let _ of $.split(`
|
|
789
|
+
`)){let j=_.trim();j&&console.warn(`[claude:chat:stderr] ${j}`)}}),p.on("error",$=>{v(),u($)}),p.on("close",$=>{if(v(),d){u(new Yt);return}if(m){u(new Error("chat session ended: idle for too long without a reply"));return}C.trim()&&E(C.trim()),console.log(`[claude:chat] exit code=${$}`),l({artifactPaths:[],log:s.join(""),usage:qT(a)})})})}function qT(t){let e=Ut();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Br(r.input_tokens),e.outputTokens=Br(r.output_tokens),e.cacheReadInputTokens=Br(r.cache_read_input_tokens),e.cacheCreationInputTokens=Br(r.cache_creation_input_tokens)),e.totalCostUsd=Br(t.total_cost_usd),e.numTurns=Br(t.num_turns),e.durationMs=Br(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var by,ky,vy,KT,xy=S(()=>{"use strict";D();Fr();Ls();by=16e3,ky=5e3,vy=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),KT="The user has finished the conversation. Now, based on everything discussed, write the DRAFT.md file in your current working directory following the contract from your instructions (line 1 \u2014 the issue title, \u2264 80 chars; line 2 \u2014 blank; lines 3+ \u2014 the body in Markdown), in the language of the conversation, and end your turn. Write nothing else."});import{execFile as YT,spawn as VT}from"node:child_process";import{existsSync as zT}from"node:fs";function XT(t,e,r,n){let o=e??"",i=/hit your (session|weekly|usage) limit/i.exec(o);if(t!==429&&!i)return null;let s={};if(/weekly limit/i.test(o)||r?.rateLimitType==="seven_day"?s.kind="weekly":(/session limit/i.test(o)||r?.rateLimitType==="five_hour")&&(s.kind="session"),r&&r.resetsAt>0){let u=Math.round(r.resetsAt*1e3);if(u>n)return s.resetAtMs=u,s}let a=/resets(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s*\(UTC\)/i.exec(o);if(a){let u=Number(a[1])%12;a[3].toLowerCase()==="pm"&&(u+=12);let p=a[2]?Number(a[2]):0,d=new Date(n);return d.setUTCHours(u,p,0,0),d.getTime()<=n&&d.setUTCDate(d.getUTCDate()+1),s.resetAtMs=d.getTime(),s}let c=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(o),l=c?Number(c[1]??c[2]):NaN;return Number.isFinite(l)&&l>0&&(s.resetAtMs=n+l*1e3),s}function ZT(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function ru(t){let e=nu.get(t);return e||(e=new Promise(r=>{YT(t,["--help"],{timeout:15e3},(n,o,i)=>{if(n){nu.delete(t),r(!1);return}r(`${o}
|
|
790
|
+
${i}`.includes("--effort"))})}),nu.set(t,e)),e}function Sy(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: ${pr(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=tI(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=Ty(o.content);console.log(`[claude] tool_result (error)${i?`: ${pr(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)} ${pr(JSON.stringify(e),200)}`),e}function QT(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(pr(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(pr(r.trim().split(`
|
|
791
791
|
`).slice(-5).join(`
|
|
792
|
-
`),500)),n.join(" \u2014 ")}function
|
|
793
|
-
`))!==-1;){let
|
|
794
|
-
`)){let
|
|
792
|
+
`),500)),n.join(" \u2014 ")}function eI(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 Ty(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function tI(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=${pr(r,80)}`}return""}function pr(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function qe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function rI(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=qe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:qe(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 Ey(t,e,r,n){let o=Ut(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=qe(i.input_tokens),o.outputTokens=qe(i.output_tokens),o.cacheReadInputTokens=qe(i.cache_read_input_tokens),o.cacheCreationInputTokens=qe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=qe(t?.total_cost_usd),o.numTurns=t&&qe(t.num_turns)>0?qe(t.num_turns):r,o.durationMs=qe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function nI(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:pr(c,Ry)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=oI(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?pr(Ty(s.content),Ry):"";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 oI(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 dt,Yt,JT,nu,qo,Ry,Fr=S(()=>{"use strict";D();xy();Ls();dt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}};Yt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},JT=5e3;nu=new Map;qo=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return $y(this.binary,e);if(e.signal?.aborted)throw new Yt;let r=["-p",ZT(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Os(Dn(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());let n=null;e.effort&&e.effort.trim().length>0&&(await ru(this.binary)?(n=e.effort.trim(),r.push("--effort",n)):console.warn(`[claude] effort '${e.effort.trim()}' requested but this Claude Code does not support --effort \u2014 running at the default effort`));for(let g of e.addDirs??[])r.push("--add-dir",g);e.settings&&Object.keys(e.settings).length>0&&r.push("--settings",JSON.stringify(e.settings));let o=[],i=[],s=null,a={input:0,output:0,cacheRead:0,cacheCreate:0},c=0,l="",u=null,p=g=>{if(g){if(g.type==="result"){s=g;return}if(g.type==="rate_limit_event"){let w=rI(g.rate_limit_info);w&&(!u||w.utilization>u.utilization)&&(u=w);return}if(g.type==="assistant"){let w=g.message;typeof w?.model=="string"&&(l=w.model);let b=w?.usage;b&&(c+=1,a.input+=qe(b.input_tokens),a.output+=qe(b.output_tokens),a.cacheRead+=qe(b.cache_read_input_tokens),a.cacheCreate+=qe(b.cache_creation_input_tokens))}}},d=e.role,m=e.onActivity,f=g=>{if(m)for(let w of nI(g,e.workspaceDir))try{m(w)}catch{}};return m?.({ts:Date.now(),kind:"start",text:`${d} job started`}),console.log(`[claude] spawn ${this.binary} role=${d}`+(e.model?` model=${e.model}`:"")+(n?` effort=${n}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((g,w)=>{let b=VT(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"}});b.stdout.setEncoding("utf-8"),b.stderr.setEncoding("utf-8");let v=!1,y=null,k=()=>{v=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${d}`),b.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),b.kill("SIGKILL")},JT)};e.signal?.addEventListener("abort",k,{once:!0});let C=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",k)},E="";b.stdout.on("data",$=>{o.push($),E+=$;let _;for(;(_=E.indexOf(`
|
|
793
|
+
`))!==-1;){let j=E.slice(0,_).trim();if(E=E.slice(_+1),j){let B=Sy(j);p(B),B&&f(B)}}}),b.stderr.on("data",$=>{o.push($),i.push($);for(let _ of $.split(`
|
|
794
|
+
`)){let j=_.trim();j&&console.warn(`[claude:stderr] ${j}`)}}),b.on("error",$=>{C(),w($)}),b.on("close",$=>{if(C(),v){w(new Yt);return}if(E.trim()){let j=Sy(E.trim());p(j),j&&f(j)}let _=s?.is_error===!0;if($!==0||_){let j=typeof s?.api_error_status=="number"?s.api_error_status:void 0,B=typeof s?.subtype=="string"?s.subtype:void 0,K=typeof s?.result=="string"?s.result:void 0,A=XT(j,K,u,Date.now());w(new dt(QT($,s,i.join("")),{code:$,apiErrorStatus:j,subtype:B,resultText:K,retryAfterMs:eI(s),...A?{rateLimited:A}:{},usage:Ey(s,a,c,l)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:Ey(s,a,c,l),...u?{rateLimit:u}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&zT(n))}};Ry=200});import{mkdirSync as iI,writeFileSync as Gr}from"node:fs";import{dirname as sI,join as Kr}from"node:path";function Iy(t,e,r){let n=Kr(t,e);iI(sI(n),{recursive:!0}),Gr(n,r)}function aI(t,e,r){return`# ${t} \u2014 Estimate
|
|
795
795
|
|
|
796
796
|
**Title:** ${e}
|
|
797
797
|
|
|
@@ -812,7 +812,7 @@ production-grade estimates.)
|
|
|
812
812
|
${r.split(`
|
|
813
813
|
`).slice(0,8).join(`
|
|
814
814
|
`).trim()||"(empty)"}
|
|
815
|
-
`}function
|
|
815
|
+
`}function cI(t,e,r,n){let o=n?`
|
|
816
816
|
## Reviewer rework instruction
|
|
817
817
|
|
|
818
818
|
> ${n.split(`
|
|
@@ -841,10 +841,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
841
841
|
${r.split(`
|
|
842
842
|
`).slice(0,8).join(`
|
|
843
843
|
`).trim()||"(empty)"}
|
|
844
|
-
`}function
|
|
844
|
+
`}function lI(t){return`# ${t} \u2014 Open questions
|
|
845
845
|
|
|
846
846
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
847
|
-
`}function
|
|
847
|
+
`}function uI(t,e,r){let n=r?` (rework: ${r.split(`
|
|
848
848
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
849
849
|
index 0000000..1111111 100644
|
|
850
850
|
--- a/CHANGELOG.md
|
|
@@ -855,7 +855,7 @@ index 0000000..1111111 100644
|
|
|
855
855
|
+- mock-runner placeholder change for slice 5 testing.
|
|
856
856
|
+
|
|
857
857
|
# Changelog
|
|
858
|
-
`}function
|
|
858
|
+
`}function dI(t,e,r){return`# ${t} \u2014 Diff summary
|
|
859
859
|
|
|
860
860
|
**Title:** ${e}
|
|
861
861
|
${r?`
|
|
@@ -866,206 +866,206 @@ ${r?`
|
|
|
866
866
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
867
867
|
|
|
868
868
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
869
|
-
`}var
|
|
870
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:Ut()}}async runInteractive(e){let r=e.role==="config",n=e.onActivity,o=s=>{n?.({ts:Date.now(),kind:"text",author:"agent",text:s}),n?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};n?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),o(r?"Hi! Describe the configuration change you'd like to make.":"Hi! Describe the task you'd like to formulate.");let i=r?"Config from chat":"Draft from chat";for await(let s of e.interactive.inbox){if(e.signal?.aborted)throw new
|
|
869
|
+
`}var Yo,ou=S(()=>{"use strict";D();Fr();Yo=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=aI(n,o,i);Gr(Kr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Gr(Kr(e.workspaceDir,"PLAN.md"),cI(n,o,i,a)),s.push("PLAN.md"),Gr(Kr(e.workspaceDir,"QUESTIONS.md"),lI(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Iy(e.workspaceDir,"changes/sample.patch",uI(n,o,a)),s.push("changes/sample.patch"),Iy(e.workspaceDir,"SOLUTION.md",dI(n,o,a)),s.push("SOLUTION.md")}else e.role==="rework"&&(Gr(Kr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
870
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:Ut()}}async runInteractive(e){let r=e.role==="config",n=e.onActivity,o=s=>{n?.({ts:Date.now(),kind:"text",author:"agent",text:s}),n?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};n?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),o(r?"Hi! Describe the configuration change you'd like to make.":"Hi! Describe the task you'd like to formulate.");let i=r?"Config from chat":"Draft from chat";for await(let s of e.interactive.inbox){if(e.signal?.aborted)throw new Yt;if(s.kind==="user")n?.({ts:Date.now(),kind:"text",author:"user",text:s.text}),s.text.trim()&&(i=s.text.trim().slice(0,80)),o(`Got it: **${s.text.trim()}**. Anything else to clarify?`);else break}if(r){let s={file:"project.yaml",section:["branch"],edits:[{file:"project.yaml",path:["branch","pattern"],value:"codepipe/<TASK_ID>"}],explanation:`Proposed by the interactive config chat (mock runner): ${i}`,diff:[{path:"branch",before:`branch:
|
|
871
871
|
pattern: <TASK_ID>
|
|
872
872
|
`,after:`branch:
|
|
873
873
|
pattern: codepipe/<TASK_ID>
|
|
874
|
-
`}]};return
|
|
874
|
+
`}]};return Gr(Kr(e.workspaceDir,"PROPOSAL.json"),JSON.stringify(s,null,2)),{artifactPaths:["PROPOSAL.json"],log:"mock config session finalized PROPOSAL.json",usage:Ut()}}return Gr(Kr(e.workspaceDir,"DRAFT.md"),`${i}
|
|
875
875
|
|
|
876
876
|
Produced by the interactive chat (mock runner).
|
|
877
|
-
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Ut()}}}});function
|
|
877
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Ut()}}}});function Cy(t){switch(t){case"mock":return new Yo;case"claude-headless":return new qo;default:return null}}function Py(t,e){let r=e&&e.trim().length>0?e.trim():Je;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var _y=S(()=>{"use strict";D();Fr();ou();Fr();ou()});function Ny(t=process.env){return{maxAttempts:Ms(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Ms(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Ms(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Ms(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function hI(t){if(t instanceof dt){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return fI.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&mI.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!1,reason:"api_status=429 (rate limit)",retryAfterMs:i}:pI.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Ay.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 Ay.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Oy(t){if(t instanceof dt){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&jy.test(n)}let e=t instanceof Error?t.message:String(t);return jy.test(e)}function gI(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 Ly(t,e,r){let n=r.sleep??(a=>new Promise(c=>setTimeout(c,a))),o=Date.now()+r.policy.totalBudgetMs,i="",s=[];for(let a=1;;a++)try{let c=await t.run(e);for(let l of s)iu(c.usage,l);return c}catch(c){i=c instanceof Error?c.message:String(c);let l=hI(c),u=a>=r.policy.maxAttempts;if(!l.retryable||u||r.aborted()){if(c instanceof dt){if(c.details.usage)for(let d of s)iu(c.details.usage,d);throw a>1&&(c.message=`agent failed after ${a} attempts: ${i}`),c}throw a>1?new Error(`agent failed after ${a} attempts: ${i}`):c}let p=gI(a,r.policy,l.retryAfterMs);if(Date.now()+p>o){if(c instanceof dt){if(c.details.usage)for(let d of s)iu(c.details.usage,d);throw c.message=`agent failed after ${a} attempts (retry budget exhausted): ${i}`,c}throw new Error(`agent failed after ${a} attempts (retry budget exhausted): ${i}`)}c instanceof dt&&c.details.usage&&s.push(c.details.usage),console.warn(`[job] ${r.jobId} agent attempt ${a}/${r.policy.maxAttempts} failed (retryable: ${l.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await n(p)}}function Ms(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}function iu(t,e){t.inputTokens+=e.inputTokens,t.outputTokens+=e.outputTokens,t.cacheReadInputTokens+=e.cacheReadInputTokens,t.cacheCreationInputTokens+=e.cacheCreationInputTokens,t.totalCostUsd+=e.totalCostUsd,t.numTurns+=e.numTurns}var pI,Ay,fI,mI,jy,My=S(()=>{"use strict";Fr();pI=new Set([500,502,503,529]),Ay=/(\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,fI=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,mI=new Set(["error_max_turns"]);jy=/(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{mkdirSync as yI,writeFileSync as wI}from"node:fs";import{homedir as bI}from"node:os";import{join as Dy}from"node:path";function By(t,e=process.env){let r=(e.CODEPIPE_DEBUG??"").trim().toLowerCase();return r?r==="1"||r==="true"||r==="all"?!0:r.split(",").map(n=>n.trim()).includes(t):!1}function Fy(t,e,r,n){try{let o=Dy(bI(),".codepipe","debug",Uy(t));yI(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=Dy(o,`${i}-${Uy(e)}-${r}.md`);return wI(s,n),s}catch{return null}}var Uy,Gy=S(()=>{"use strict";Uy=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as kI,rmSync as vI,writeFileSync as Ky}from"node:fs";import{tmpdir as $I}from"node:os";import{join as su}from"node:path";function Ds(t){return`[url "https://${t}/"]
|
|
878
878
|
insteadOf = git@${t}:
|
|
879
879
|
insteadOf = ssh://git@${t}/
|
|
880
|
-
`}function
|
|
880
|
+
`}function Yy(t,e){if(t.length===0)return null;let r=kI(su($I(),"devpipe-gitcreds-")),n=su(r,"credentials"),o=su(r,"gitconfig");return Ky(n,t.join(`
|
|
881
881
|
`)+`
|
|
882
|
-
`,{mode:384}),
|
|
882
|
+
`,{mode:384}),Ky(o,`[credential]
|
|
883
883
|
helper = store --file=${n}
|
|
884
|
-
`+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{
|
|
885
|
-
`).map(n=>n.trim()).filter(n=>n.length>0)}async function
|
|
886
|
-
`).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.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 m}async function
|
|
887
|
-
`).map(l=>l.trim()).filter(l=>l.length>0),c=await
|
|
888
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function
|
|
889
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
890
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=
|
|
891
|
-
`+e.subarray(e.length-
|
|
892
|
-
\u2026 [${r.length-e} bytes elided]`}function
|
|
893
|
-
`)){if(n.startsWith("+++ ")){let o=n.slice(4).trim();r=o==="/dev/null"?null:o.replace(/^b\//,""),r&&!e.has(r)&&e.set(r,[]);continue}if(r&&n.startsWith("@@")){let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(n);if(!o)continue;let i=Number(o[1]),s=o[2]!==void 0?Number(o[2]):1,a=s===0?Math.max(1,i):i,c=s===0?Math.max(1,i):i+s-1;e.get(r).push([a,c])}}return e}function
|
|
884
|
+
`+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{vI(r,{recursive:!0,force:!0})}catch{}}}}function au(t){let e=[],r=[];if(t.mirrorWrite?.token){let n=t.mirrorWrite.host;(!n||n==="github")&&(e.push(`https://x-access-token:${t.mirrorWrite.token}@github.com`),r.push(Hy)),(!n||n==="gitlab")&&(e.push(`https://oauth2:${t.mirrorWrite.token}@gitlab.com`),r.push(qy)),(!n||n==="bitbucket")&&(e.push(`https://${Ft}:${encodeURIComponent(t.mirrorWrite.token)}@bitbucket.org`),r.push(Wy))}return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Hy)),t.bitbucket?.apiToken&&(e.push(`https://${Ft}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Wy)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(qy)),Yy(e,r)}function Vy(t,e){if(t.contextWrite?.token){let r=Cr(e)??"github.com",n=vo(r);return Yy([`https://${n}:${t.contextWrite.token}@${r}`],[Ds(r)])}return au(t)}var Hy,Wy,qy,zy=S(()=>{"use strict";D();Hy=Ds("github.com"),Wy=Ds("bitbucket.org"),qy=Ds("gitlab.com")});import{spawn as Jy}from"node:child_process";import{existsSync as Us,mkdirSync as Vo,readFileSync as xI,rmSync as cu,symlinkSync as SI}from"node:fs";import{homedir as EI}from"node:os";import{dirname as Bn,join as fr}from"node:path";function Zy(t){let e=fr(EI(),".codepipe-sandbox","repos");return t?fr(e,t):e}function Qy(t,e){let n=(Un.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Un.get(t)===o&&Un.delete(t)},()=>{Un.get(t)===o&&Un.delete(t)});return Un.set(t,o),n}function Xy(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 RI(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 ew(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||!Xy(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Us(t)&&cu(t,{recursive:!0,force:!0}),Vo(Bn(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||!Xy(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Us(t)&&cu(t,{recursive:!0,force:!0}),Vo(Bn(t),{recursive:!0}),await ne(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Us(fr(t,".git")))try{return await s()}catch(c){if(!RI(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 tw(t){await ne(t.workspacePath,["reset","--hard",t.baseSha]),await ne(t.workspacePath,["clean","-fdx"])}async function rw(t,e){let r=t.workspacePath;await ne(r,["add","-A"]);let n=(await ke(r,["write-tree"])).trim(),o=(await ke(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Fn,GIT_AUTHOR_EMAIL:Gn,GIT_COMMITTER_NAME:Fn,GIT_COMMITTER_EMAIL:Gn};return(await ke(r,["commit-tree",n,"-m",e],i)).trim()}async function nw(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 Cr(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 ow(t,e){return ke(t.workspacePath,["diff","--binary",t.baseSha,e])}async function iw(t,e){return(await ke(t.workspacePath,["diff","--name-only",t.baseSha,e])).split(`
|
|
885
|
+
`).map(n=>n.trim()).filter(n=>n.length>0)}async function sw(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 aw(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 ke(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=f=>ke(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await ke(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:Fn,GIT_AUTHOR_EMAIL:Gn,GIT_COMMITTER_NAME:Fn,GIT_COMMITTER_EMAIL:Gn},u=(await ke(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await ke(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(f){d=f instanceof Error?f.message:String(f)}let m=(await ke(s,["diff","--name-only","--diff-filter=U"])).split(`
|
|
886
|
+
`).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.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 m}async function lu(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Fn,GIT_AUTHOR_EMAIL:Gn,GIT_COMMITTER_NAME:Fn,GIT_COMMITTER_EMAIL:Gn};(await ke(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 ke(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
887
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await ke(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}async function lw(t,e){return ke(t.workspacePath,["diff","--unified=0",`${cw}..HEAD`],e)}async function uu(t,e,r){await ne(t.workspacePath,["update-ref",cw,e],r)}async function uw(t,e,r){let n=t.workspacePath,o=[`+refs/heads/${e}:refs/remotes/origin/${e}`,...t.ref!==e?[`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`]:[]];await ne(n,["fetch","--depth=1","origin",...o],r).catch(a=>{console.warn(`[git] review-base ${t.name}: base fetch failed: ${String(a)}`)});let i=()=>ke(n,["merge-base",`origin/${e}`,"HEAD"],r).then(a=>a.trim()||null).catch(()=>null),s=await i();for(let a of[64,256,1024]){if(s)break;await ne(n,["fetch",`--deepen=${a}`,"origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --deepen=${a} failed: ${String(c)}`)}),s=await i()}return s||(await ke(n,["rev-parse","--is-shallow-repository"],r)).trim()==="true"&&(await ne(n,["fetch","--unshallow","origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --unshallow failed: ${String(c)}`)}),s=await i()),s&&await uu(t,s,r),s}function ne(t,e,r){return new Promise((n,o)=>{let i=Jy("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}):
|
|
888
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function ke(t,e,r){return new Promise((n,o)=>{let i=Jy("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}):
|
|
889
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function dw(t,e){Us(t)&&cu(t,{recursive:!0,force:!0}),Vo(Bn(t),{recursive:!0}),SI(e,t,"dir")}async function pw(t,e,r){await ne(t,["worktree","prune"]).catch(()=>{}),Vo(Bn(r),{recursive:!0}),await ne(t,["worktree","add","--detach",r,`origin/${e}`])}async function TI(t,e,r){Vo(Bn(r),{recursive:!0}),await ne(Bn(r),["clone","--quiet","--no-checkout",t,r]),await ne(r,["checkout","--force","--detach",e])}async function fw(t,e,r,n="worktree",o,i){return r.length===0?[]:Qy(e,async()=>{let s=[];for(let a of r){let c=fr(Zy(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await ew(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 ke(c,["rev-parse","HEAD"])).trim(),p=fr(t,"code",a.name);n==="direct"?(dw(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await TI(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await pw(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 mw(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return Qy(e,async()=>{let a=fr(Zy(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await ew(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=fr(t,"context");n==="direct"?(dw(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await pw(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await ke(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function hw(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ne(r,["add","-A",...n]).catch(()=>{});let o;try{o=await ke(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
|
|
890
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=xI(fr(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var Un,Fn,Gn,cw,gw=S(()=>{"use strict";D();Un=new Map;Fn="CodePipe Agent",Gn="codepipe@codepartner.ee";cw="refs/worktree/codepipe/review-base"});import{existsSync as II,readFileSync as CI}from"node:fs";import{join as PI}from"node:path";import{parse as _I}from"yaml";function yw(t){if(!t)return!1;let e=PI(t,du);if(!II(e))return!1;try{let r=_I(CI(e,"utf-8"));if(!r||typeof r!="object")return!1;let n=r.steps;return!Array.isArray(n)||n.length===0?!1:n.some(o=>o!=null&&typeof o=="object"&&typeof o.run=="string"&&o.run.trim().length>0)}catch{return!1}}var du,ww=S(()=>{"use strict";du="knowledge/build.yaml"});import{readFileSync as AI}from"node:fs";import{join as jI}from"node:path";function bw(t){let e=jI(t,zo),r;try{r=AI(e,"utf-8")}catch{throw new mr(`BUILD produced no ${zo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new mr(`${zo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new mr(`${zo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new mr(`${zo}: "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,m=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||m===null)return[];let f={name:d,exitCode:m};return typeof p.durationMs=="number"&&(f.durationMs=p.durationMs),[f]}),c=typeof o.logTail=="string"?NI(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 NI(t){let e=Buffer.from(t,"utf-8");return e.length<=pu?t:`\u2026 [${e.length-pu} bytes elided] \u2026
|
|
891
|
+
`+e.subarray(e.length-pu).toString("utf-8")}var pu,mr,zo,kw=S(()=>{"use strict";pu=8*1024,mr=class extends Error{},zo="meta/build-result.json"});var vw={};Ge(vw,{REVIEW_RESULT_PATH:()=>Hr,ReviewVerdictError:()=>Pt,markFindingScope:()=>GI,parseChangedRanges:()=>FI,readCodeReviewResult:()=>fu});import{readFileSync as OI}from"node:fs";import{join as LI}from"node:path";function fu(t){let e=LI(t,Hr),r;try{r=OI(e,"utf-8")}catch{throw new Pt(`code review produced no ${Hr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(l){throw new Pt(`${Hr} is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!n||typeof n!="object")throw new Pt(`${Hr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Pt(`${Hr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?hr(o.remarks,MI):"";if(!i&&s.trim().length===0)throw new Pt(`${Hr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?hr(o.summary,DI):"",c=BI(o.findings);return{approved:i,remarks:s,summary:a,...c.length>0?{findings:c}:{}}}function BI(t){if(!Array.isArray(t))return[];let e=[];for(let r of t.slice(0,UI)){if(!r||typeof r!="object")continue;let n=r,o=typeof n.title=="string"?hr(n.title,512).trim():"",i=typeof n.problem=="string"?hr(n.problem,Bs).trim():"";if(!o||!i)continue;let s=typeof n.line=="number"&&Number.isInteger(n.line)&&n.line>0?n.line:void 0,a=n.severity==="blocker"||n.severity==="major"||n.severity==="minor"?n.severity:"other",c=typeof n.scenario=="string"&&n.scenario.trim()?hr(n.scenario,Bs):void 0;a==="blocker"&&!c&&(console.warn(`[review] blocker "${o.slice(0,80)}" carries no scenario \u2014 demoted to major`),a="major"),e.push({severity:a,title:o,problem:i,...typeof n.repo=="string"&&n.repo?{repo:n.repo}:{},...typeof n.file=="string"&&n.file?{file:hr(n.file,1024)}:{},...s!==void 0?{line:s}:{},...c?{scenario:c}:{},...typeof n.suggestion=="string"&&n.suggestion.trim()?{suggestion:hr(n.suggestion,Bs)}:{},...n.confidence==="high"||n.confidence==="medium"||n.confidence==="low"?{confidence:n.confidence}:{},...n.rule_source==="adr"||n.rule_source==="convention"||n.rule_source==="build"||n.rule_source==="judgment"?{ruleSource:n.rule_source}:{},...typeof n.out_of_diff_reason=="string"&&n.out_of_diff_reason.trim()?{outOfDiffReason:hr(n.out_of_diff_reason,Bs)}:{}})}return e}function hr(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
|
|
892
|
+
\u2026 [${r.length-e} bytes elided]`}function FI(t){let e=new Map,r=null;for(let n of t.split(`
|
|
893
|
+
`)){if(n.startsWith("+++ ")){let o=n.slice(4).trim();r=o==="/dev/null"?null:o.replace(/^b\//,""),r&&!e.has(r)&&e.set(r,[]);continue}if(r&&n.startsWith("@@")){let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(n);if(!o)continue;let i=Number(o[1]),s=o[2]!==void 0?Number(o[2]):1,a=s===0?Math.max(1,i):i,c=s===0?Math.max(1,i):i+s-1;e.get(r).push([a,c])}}return e}function GI(t,e,r){for(let n of t.findings??[]){if(!n.file)continue;let o=n.repo??r;if(!o)continue;let i=e.get(o);if(!i)continue;let s=i.get(n.file);if(!s){n.scope="outside";continue}if(n.line===void 0||s.length===0){n.scope="diff";continue}let a=n.line;n.scope=s.some(([c,l])=>a>=c&&a<=l)?"diff":"file"}}var MI,DI,Pt,Hr,Bs,UI,mu=S(()=>{"use strict";MI=16*1024,DI=4*1024,Pt=class extends Error{},Hr="meta/review-result.json";Bs=8*1024,UI=50});import{readFileSync as KI,statSync as HI}from"node:fs";import{join as $w}from"node:path";function JI(t){return t.startsWith("meta/")||XI.has(t)}function ZI(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 QI(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function xw(t,e,r){let n=r?.maxBytes??WI,o=r?.totalBytes??qI,i=r?.maxCount??YI,s=e.map((f,g)=>{let w=null;try{w=HI($w(t,f)).size}catch{}return{path:f,index:g,size:w}}),a=[...s].sort((f,g)=>{let w=b=>JI(b.path)?0:1;return w(f)!==w(g)?w(f)-w(g):(f.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((f,g)=>f.index-g.index).map(f=>f.path),u=new Array(s.length),p=[],d=0;for(let f of c){let g=null;if(f.size!==null&&f.size<=n&&d+f.size<=o)try{g=KI($w(t,f.path))}catch{}if(g!==null){d+=g.length,u[f.index]={path:f.path,contentBase64:g.toString("base64")};continue}let w=f.size===null?QI(f.path):ZI(f.path,f.size,n,o),b=Buffer.from(w,"utf-8");d+=b.length,u[f.index]={path:f.path,contentBase64:b.toString("base64")},p.push({path:f.path,bytes:f.size??0})}let m=u.filter(f=>f!==void 0);if(l.length>0){let f=l.slice(0,zI),g=`# Artifacts omitted from upload
|
|
894
894
|
|
|
895
895
|
${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.
|
|
896
896
|
|
|
897
897
|
`+f.map(w=>`- ${w}
|
|
898
898
|
`).join("")+(l.length>f.length?`
|
|
899
899
|
\u2026and ${l.length-f.length} more.
|
|
900
|
-
`:"");m.push({path:
|
|
901
|
-
`),r=e.findIndex(a=>
|
|
900
|
+
`:"");m.push({path:VI,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var WI,qI,YI,VI,zI,XI,Sw=S(()=>{"use strict";WI=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),qI=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),YI=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),VI="artifacts-omitted.md",zI=500,XI=new Set(["QUESTIONS.md","PLAN.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","SOLUTION.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as eC,mkdtempSync as tC,readFileSync as rC,readdirSync as Rw,rmSync as Ew}from"node:fs";import{tmpdir as nC}from"node:os";import{join as Fs,relative as oC}from"node:path";function Tw(t){let e=tC(Fs(nC(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Ew(e,{recursive:!0,force:!0}),listFiles:()=>Iw(e,e),readFile:r=>rC(Fs(e,r),"utf-8"),clean:()=>{for(let r of Rw(e))sC.has(r)||Ew(Fs(e,r),{recursive:!0,force:!0})}}}function Iw(t,e){let r=[];for(let n of Rw(e)){let o=Fs(e,n),i=eC(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&iC.has(n))continue;r.push(...Iw(t,o))}else r.push(oC(t,o))}return r}var iC,sC,Cw=S(()=>{"use strict";iC=new Set(["code","context","scratch",".claude"]),sC=new Set(["code","context"])});import{readFileSync as aC}from"node:fs";import{join as cC}from"node:path";function fC(t,e){let r=ko(t);return r?_w(mC(r),e):""}function Pw(t,e,r={}){let n=r.perAncestorBudget??lC,o=r.totalBudget??uC,i=[...t.matchAll(Si)];if(i.length===0)return t;let s=i.map(l=>{let u=l[1],p=hC(e,u),d=p!=null?fC(p,n):"";return{key:u,text:d||`(\u0442\u0435\u043B\u043E \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u2014 \u0441\u043C. tasks/${u}/task.md)`}}),a=o,c=new Map;for(let l of s){let u=Math.max(0,Math.min(l.text.length,a));c.set(l.key,_w(l.text,u)),a-=u}return t.replace(Si,(l,u)=>c.get(u)??"")}function mC(t){let e=t.split(`
|
|
901
|
+
`),r=e.findIndex(a=>pC.test(a));if(r<0)return t;let n=e.slice(0,r).join(`
|
|
902
902
|
`).trim(),o=(e[r]??"").match(/^#+/)?.[0].length??1,i=e.length;for(let a=r+1;a<e.length;a++){let c=(e[a]??"").match(/^(#{1,6})\s/);if(c&&(c[1]?.length??0)<=o){i=a;break}}let s=e.slice(r,i).join(`
|
|
903
903
|
`).trim();return[n,s].filter(Boolean).join(`
|
|
904
904
|
|
|
905
|
-
`)}function
|
|
905
|
+
`)}function _w(t,e){return t.length<=e?t:t.slice(0,e).trimEnd()+dC}function hC(t,e){if(!t)return null;try{return aC(cC(t,"tasks",e,"task.md"),"utf-8")}catch{return null}}var lC,uC,dC,pC,Aw=S(()=>{"use strict";D();lC=1200,uC=3e3,dC=`
|
|
906
906
|
|
|
907
|
-
\u2026(\u043E\u0431\u0440\u0435\u0437\u0430\u043D\u043E)`,
|
|
908
|
-
${n}`.match(
|
|
909
|
-
${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let m of c){let f=m.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!f||!f.includes("/")&&!f.includes("."))continue;let
|
|
910
|
-
${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&s(f,
|
|
911
|
-
${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let
|
|
912
|
-
`));let u=
|
|
907
|
+
\u2026(\u043E\u0431\u0440\u0435\u0437\u0430\u043D\u043E)`,pC=/^#{1,6}\s.*(приёмк|acceptance|критери)/i});import{existsSync as Ks,readFileSync as jw,readdirSync as hu}from"node:fs";import{join as Vt}from"node:path";import{parse as gC}from"yaml";function Hs(t){if(!Ks(t))return[];let e=[];for(let r of hu(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Vt(t,r.name);r.isDirectory()?e.push(...Hs(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Gs(t){try{return gC(jw(t,"utf-8"))}catch{return null}}function Nw(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 Hs(Vt(t,"model/derived/structure"))){let s=Mt(Gs(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[...Hs(Vt(t,"model/derived/correlates")),Vt(t,"model/derived/relates.yaml")]){if(!Ks(i))continue;let s=uo(Gs(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Vt(t,"model/facts/events");if(Ks(n))for(let i of hu(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Dt(Gs(Vt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=xe(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,xe(l),"references",1)}for(let i of Hs(Vt(t,"model/facts/identity"))){let s=po(Gs(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=Vt(t,"model/facts/annotations");if(Ks(o)){for(let i of hu(o).sort())if(i.endsWith(".md"))try{let s=jw(Vt(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 Ow=S(()=>{"use strict";D()});function Mw(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function xC(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 Dw(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(m,f)=>{(i.get(m)??0)<f&&i.set(m,f)};(o.events.has(e)||o.adjacency.has(xe(e)))&&s(xe(e),Lw);for(let m of`${r}
|
|
908
|
+
${n}`.match($C)??[]){if(m===e)continue;let f=xe(m);(o.events.has(m)||o.adjacency.has(f))&&s(f,Lw)}let a=new Map;for(let m of o.nodes.keys()){let f=te(m);if(f?.level!=="code")continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);for(let w of[f.path,g])a.has(w)||a.set(w,[]),a.get(w).push(m)}let c=`${r}
|
|
909
|
+
${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let m of c){let f=m.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!f||!f.includes("/")&&!f.includes("."))continue;let g=a.get(f)??[];g.length===1&&s(g[0],yC)}let l=new Map,u=(m,f)=>{let g=m.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==f?null:f)};for(let m of o.nodes.keys()){let f=te(m);if(!f)continue;let g=f.path.slice(f.path.lastIndexOf("/")+1);f.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),m),f.level==="component"&&u(g,m)}for(let m of`${r}
|
|
910
|
+
${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&s(f,wC)}let p=Mw(`${r}
|
|
911
|
+
${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let g=xC(p,Mw(f.title));g>=kC&&d.push({key:xe(m),score:g})}return d.sort((m,f)=>f.score-m.score||(m.key<f.key?-1:1)).slice(0,vC).forEach(m=>s(m.key,bC)),i}var Lw,yC,wC,bC,kC,vC,$C,Uw=S(()=>{"use strict";D();Lw=1,yC=.9,wC=.7,bC=.5,kC=.15,vC=3,$C=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function Bw(t,e,r={}){let n=r.cutoff??Sr.activationCutoff,o=r.topK??Sr.topKPerNode,i=r.nodeCap??Sr.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=_a[p.kind]??.3,m=l.activation*d*Math.min(p.weight,1);if(m<n)continue;let f=s.get(p.to);(!f||f.activation<m)&&(s.set(p.to,{activation:m,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:m}))}}return s}var Fw=S(()=>{"use strict";D()});import{existsSync as yu,readFileSync as Gw,readdirSync as SC}from"node:fs";import{join as Ws}from"node:path";function gu(t){return Math.ceil(t.length/4)}function Kn(t,e,r){let n=o=>o.via?.kind==="correlates"?r?.get(o.key)??1:1;return[...t.entries()].filter(([o])=>e(o)).map(([o,i])=>({key:o,activation:i.activation,via:i.via})).sort((o,i)=>i.activation*n(i)-o.activation*n(o)||(o.key<i.key?-1:1))}function $t(t){let e=te(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function Xo(t){if(!t.via)return"matched from the task text";let e=$t(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 Kw(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=Ws(t,"adr");if(!yu(n))return null;let o=r.padStart(4,"0");for(let i of SC(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:Gw(Ws(n,i),"utf-8").trim()}}catch{return null}return null}function Hw(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??Sr.budgetTokens,a=[],c=0,l=E=>{let $=gu(E);return c+$>s?!1:(a.push(E),c+=$,!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(`
|
|
912
|
+
`));let u=Kn(i,E=>E.startsWith("adr::")),p=!1;for(let E of u){let $=Kw(n,$t(E.key));if(!$)continue;let _=`${p?"":`
|
|
913
913
|
## Governing decisions
|
|
914
914
|
`}
|
|
915
|
-
### ${
|
|
915
|
+
### ${$t(E.key)} (\`${$.file}\`, ${Xo(E)})
|
|
916
916
|
|
|
917
|
-
${
|
|
918
|
-
`;if(!l(
|
|
917
|
+
${$.content}
|
|
918
|
+
`;if(!l(_))break;p=!0}let d=Kn(i,E=>o.nodes.get(E)?.entityId!==void 0).filter(E=>o.annotations.has(o.nodes.get(E.key).entityId)),m=t.staleKeys??new Set,f=!1;for(let E of d){let $=o.nodes.get(E.key).entityId,_=o.annotations.get($),j=m.has(E.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has($)?" \u2014 \u26A0 the file no longer exists":"",B=`${f?"":`
|
|
919
919
|
## Why the code is shaped this way (intent notes)
|
|
920
920
|
`}
|
|
921
|
-
### \`${
|
|
921
|
+
### \`${$t(E.key)}\`${j}
|
|
922
922
|
|
|
923
|
-
${
|
|
924
|
-
`;if(!l(
|
|
925
|
-
> ${
|
|
926
|
-
> _(full text: \`${
|
|
923
|
+
${_}
|
|
924
|
+
`;if(!l(B))break;f=!0}let g=xe(e),w=Kn(i,E=>E.startsWith("task::")&&E!==g).slice(0,EC),b=!1;for(let E of w){let $=o.events.get($t(E.key));if(!$)continue;let _=[...$.files].filter(h=>!m.has(h.key)&&(!h.entityId||!o.orphanedEntities.has(h.entityId))).sort((h,F)=>(F.churn??0)-(h.churn??0)||(h.key<F.key?-1:1)).slice(0,3).map(h=>`\`${$t(h.key)}\``).join(", "),j="",B=$.links?.solution??[`tasks/${$.taskKey}/PLAN.md`,`tasks/${$.taskKey}/SOLUTION.md`].find(h=>yu(Ws(n,h)))??`tasks/${$.taskKey}/PLAN.md`,K=Ws(n,B);if(yu(K))try{j=`
|
|
925
|
+
> ${Gw(K,"utf-8").trim().slice(0,TC).replace(/\n+/g," ").trim()}\u2026
|
|
926
|
+
> _(full text: \`${B}\`)_`}catch{}let A=`${b?"":`
|
|
927
927
|
## Related past tasks
|
|
928
928
|
`}
|
|
929
|
-
- **${
|
|
930
|
-
`))+
|
|
931
|
-
`))}let
|
|
929
|
+
- **${$.taskKey}**${$.title?` \u2014 ${$.title}`:""}${$.date?` (${$.date})`:""}, ${Xo(E)}. Files: ${_||"\u2014"}.${j}`;if(!l(A))break;b=!0}let v=E=>{if(m.has(E.key))return!1;let $=o.nodes.get(E.key)?.entityId;return!$||!o.orphanedEntities.has($)},y=Kn(i,E=>E.startsWith("code:"),t.fileWeights),k=y.filter(v).slice(0,RC);if(k.length>0){let E=["","## Files likely involved",""];for(let $ of k){let _=`- \`${$t($.key)}\` \u2014 ${Xo($)}`;if(c+gu(E.join(`
|
|
930
|
+
`))+gu(_)>s)break;E.push(_)}E.length>3&&l(E.join(`
|
|
931
|
+
`))}let C=y.filter(E=>!v(E)).slice(0,10);if(C.length>0){let E=["","## Possibly stale (verify before trusting)","","These entries reference files that changed after the map was built or","no longer exist at their recorded location. Useful as history, wrong","as current fact.","",...C.map($=>`- \`${$t($.key)}\` \u2014 ${Xo($)}${m.has($.key)?" (changed since the map was built)":" (file gone)"}`)];l(E.join(`
|
|
932
932
|
`))}return a.length<=1?null:a.join(`
|
|
933
933
|
`)+`
|
|
934
|
-
`}function
|
|
935
|
-
`)}var
|
|
934
|
+
`}function Ww(t){let{model:e,activated:r}=t,n=t.staleKeys??new Set,o=t.maxPaths??18,i=1600,s=Kn(r,u=>u.startsWith("adr::")).filter(u=>Kw(t.contextDir,$t(u.key))!==null).slice(0,6).map(u=>$t(u.key)),a=u=>{if(n.has(u.key))return!1;let p=e.nodes.get(u.key)?.entityId;return!p||!e.orphanedEntities.has(p)},c=Kn(r,u=>u.startsWith("code:"),t.fileWeights).filter(a).slice(0,o);if(s.length===0&&c.length===0)return null;let l=["Top of the pack (the full brief with reasons and decision bodies is in","`meta/context-pack.md` \u2014 still read it):"];if(s.length>0&&l.push("",`Governing decisions: ${s.join(", ")} (bodies under \`adr/\`).`),c.length>0){l.push("","Files most likely involved:");let u=0;for(let p of c){let d=`- \`${$t(p.key)}\` \u2014 ${Xo(p)}`;if(u+d.length>i)break;l.push(d),u+=d.length+1}}return l.join(`
|
|
935
|
+
`)}var EC,RC,TC,qw=S(()=>{"use strict";D();EC=5,RC=300,TC=400});var Jw={};Ge(Jw,{assembleContextPack:()=>AC,computeIdfWeights:()=>Xw});import{createHash as IC}from"node:crypto";import{existsSync as Yw,readFileSync as Vw}from"node:fs";import{join as zw}from"node:path";function Xw(t){let e=new Map,r=t.events.size;if(r<CC)return e;let n=new Map;for(let i of t.events.values()){let s=new Set;for(let a of i.files){let c=a.entityId?`e:${a.entityId}`:`k:${a.key}`;s.has(c)||(s.add(c),n.set(c,(n.get(c)??0)+1))}}let o=Math.log(r+1);for(let[i,s]of n){let a=i.startsWith("e:")?t.keyByEntity.get(i.slice(2))??null:i.slice(2);a&&e.set(a,Math.max(.15,Math.log((r+1)/(s+1))/o))}return e}function PC(t){return IC("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function _C(t,e,r){let n=new Set;for(let o of e.keys()){let i=te(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=zw(a,i.path);try{if(!Yw(c)){n.add(o);continue}PC(Vw(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function AC(t){let e=Nw(t.contextDir);if(e.empty)return null;let r="",n=zw(t.contextDir,`tasks/${t.taskKey}/task.md`);if(Yw(n))try{r=Vw(n,"utf-8")}catch{r=""}let o=Dw({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=Bw(e,o),s=t.repoDirs?_C(e,i,t.repoDirs):new Set,a=t.idfPenalty===!1?new Map:Xw(e),c=Hw({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,fileWeights:a,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}});return c?{markdown:c,top:Ww({model:e,activated:i,contextDir:t.contextDir,staleKeys:s,fileWeights:a})}:null}var CC,Zw=S(()=>{"use strict";D();Ow();Uw();Fw();qw();CC=30});var rb={};Ge(rb,{SKILLS_DIR:()=>wu,loadSkills:()=>GC,materializeSkills:()=>KC,renderSkillsBlock:()=>HC,resolveBundledSkillsDir:()=>tb});import{cpSync as jC,existsSync as Qw,mkdirSync as NC,readFileSync as OC,readdirSync as eb}from"node:fs";import{dirname as LC,join as gr}from"node:path";import{fileURLToPath as MC}from"node:url";import{parse as DC}from"yaml";function tb(t){for(let e of[t,gr(t,"skills")])try{if(eb(e,{withFileTypes:!0}).some(n=>n.isDirectory()&&Qw(gr(e,n.name,"SKILL.md"))))return e}catch{}return t}function BC(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
|
|
936
936
|
---`,3);return r===-1?null:{yaml:e.slice(e.indexOf(`
|
|
937
937
|
`,3)+1,r),body:e.slice(e.indexOf(`
|
|
938
|
-
`,r+1)+1)}}function
|
|
939
|
-
`)}var
|
|
940
|
-
`),{dir:o,ready:r,errors:e}}function
|
|
938
|
+
`,r+1)+1)}}function FC(t,e,r){let n=[],o=[];if(!Qw(t))return{skills:n,errors:o};let i;try{i=eb(t,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name).sort()}catch(s){return{skills:n,errors:[{source:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){let a=gr(t,s),c=`${r}/${s}`,l;try{l=OC(gr(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=BC(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=DC(u.yaml)}catch(m){o.push({source:c,error:`frontmatter is not valid YAML: ${String(m)}`});continue}let d=cc({name:s,frontmatter:p,body:u.body});d.ok?n.push({...d.skill,dir:a,origin:e}):o.push({source:c,error:d.error})}return{skills:n,errors:o}}function GC(t){let e=[],r=(s,a,c)=>{let l=FC(s,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(UC,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(gr(t.contextDir,"skills"),"context","skills"):[],i=t.sources.repo?t.repoDirs.flatMap(s=>r(gr(s,".claude","skills"),"repo","repo")):[];return{skills:lc(n,o,i),errors:e}}function KC(t,e){if(e.length===0)return[];let r=gr(t,wu);NC(r,{recursive:!0});let n=[];for(let o of e)jC(o.dir,gr(r,o.name),{recursive:!0}),n.push(`${wu}/${o.name}`);return n}function HC(t,e=[]){let r=new Set(t.map(s=>s.name)),n=e.filter(s=>!r.has(s));if(t.length===0&&n.length===0)return"";let o=[];t.length>0&&o.push("## Skills available to you","",...t.map(s=>`- **${s.name}** \u2014 ${s.description}`),"","Only these lines are in context; a skill's steps load when you invoke it.","When one covers what you are about to do, use it: it was written down","because the obvious approach was wrong or costly.","");let i=e.filter(s=>r.has(s));return i.length>0&&o.push("**The approved plan requires this task to follow: "+i.map(s=>`\`${s}\``).join(", ")+".**","This is not a suggestion \u2014 a reviewer approved it as a requirement.",""),n.length>0&&o.push("**The plan prescribes "+n.map(s=>`\`${s}\``).join(", ")+", which is not available here.**","Proceed without it and say so in your result \u2014 do not invent the procedure.",""),o.join(`
|
|
939
|
+
`)}var wu,UC,nb=S(()=>{"use strict";D();wu=".claude/skills";UC=tb(LC(MC(import.meta.url)))});var ab={};Ge(ab,{seedMarketplaces:()=>eP});import{spawn as WC}from"node:child_process";import{cpSync as qC,existsSync as ob,mkdirSync as ib,rmSync as bu,symlinkSync as YC,writeFileSync as VC}from"node:fs";import{homedir as zC}from"node:os";import{join as yr}from"node:path";function sb(){return yr(zC(),".codepipe-sandbox","plugins")}function ZC(t){return yr(sb(),"src",`${t.name}@${t.sha||"head"}`)}function Jo(t,e){return new Promise((r,n)=>{let o=WC("git",t,{cwd:e,stdio:["ignore","ignore","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"}}),i=[];o.stderr.setEncoding("utf-8"),o.stderr.on("data",s=>i.push(s)),o.on("error",n),o.on("close",s=>{if(s===0)return r();n(new Error(`git ${t[0]} failed (exit ${s}): ${i.join("").trim().slice(0,400)}`))})})}async function QC(t){let e=ZC(t);if(ob(yr(e,".claude-plugin","marketplace.json")))return e;bu(e,{recursive:!0,force:!0}),ib(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await Jo(["init","--quiet"],e),await Jo(["remote","add","origin",r],e),await Jo(["fetch","--quiet","--depth","1","origin",t.sha],e),await Jo(["checkout","--quiet","FETCH_HEAD"],e)):await Jo(["clone","--quiet","--depth","1",r,e]),!ob(yr(e,".claude-plugin","marketplace.json")))throw bu(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function eP(t){if(t.length===0)return{dir:null,ready:[],errors:[]};let e=[],r=[],n=new Map;for(let a of t)try{n.set(a.name,await QC(a)),r.push(a)}catch(c){e.push({repo:a.repo,error:c instanceof Error?c.message:String(c)})}if(r.length===0)return{dir:null,ready:r,errors:e};let o=yr(sb(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),i=yr(o,XC);ib(i,{recursive:!0});let s={};for(let a of r){let c=yr(i,a.name);bu(c,{recursive:!0,force:!0}),tP(n.get(a.name),c),s[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return VC(yr(o,JC),`${JSON.stringify(s,null,2)}
|
|
940
|
+
`),{dir:o,ready:r,errors:e}}function tP(t,e){try{YC(t,e,"dir")}catch{qC(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var XC,JC,cb=S(()=>{"use strict";XC="marketplaces",JC="known_marketplaces.json"});var pb={};Ge(pb,{loadRoles:()=>lP,resolveBundledRolesDir:()=>db});import{existsSync as rP,readFileSync as nP,readdirSync as ub}from"node:fs";import{dirname as oP,join as ku}from"node:path";import{fileURLToPath as iP}from"node:url";import{parse as sP}from"yaml";function db(t){for(let e of[t,ku(t,"roles")])try{if(ub(e).some(r=>r.endsWith(".md")))return e}catch{}return t}function cP(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
|
|
941
941
|
---`,3);if(r===-1)return null;let n=e.slice(e.indexOf(`
|
|
942
942
|
`,3)+1,r),o=e.indexOf(`
|
|
943
|
-
`,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function
|
|
944
|
-
`),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${
|
|
943
|
+
`,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function lb(t,e,r){let n=[],o=[];if(!rP(t))return{roles:n,errors:o};let i;try{i=ub(t).sort()}catch(s){return{roles:n,errors:[{file:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){if(!s.endsWith(".md"))continue;let a=`${r}/${s}`,c;try{c=nP(ku(t,s),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=cP(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=sP(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=rc({name:s.slice(0,-3),frontmatter:u,body:l.body,origin:e});p.ok?n.push(p.role):o.push({file:a,error:p.error})}return{roles:n,errors:o}}function lP(t){let e=lb(aP,"bundled","bundled"),r=t?lb(ku(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:nc(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var aP,fb=S(()=>{"use strict";D();aP=db(oP(iP(import.meta.url)))});var mb={};Ge(mb,{ROLE_AGENTS_DIR:()=>$u,materializeRoleAgents:()=>fP,renderRolesBlock:()=>mP});import{mkdirSync as uP,writeFileSync as dP}from"node:fs";import{join as vu}from"node:path";function pP(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
|
|
944
|
+
`),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${vu(e,o)}\``),"","They are this role's curated context. If one is missing, say so in a line and continue \u2014","its absence is not an error.",""].join(`
|
|
945
945
|
`):"";return`${r}${t.body}
|
|
946
|
-
${n}`}function
|
|
946
|
+
${n}`}function fP(t,e,r,n){let o=oc(e,r);if(o.length===0)return{roles:[],files:[]};let i=vu(t,$u);uP(i,{recursive:!0});let s=[];for(let a of o)dP(vu(i,`${a.name}.md`),pP(a,n)),s.push(`${$u}/${a.name}.md`);return{roles:o,files:s}}function mP(t,e){return t.roles.length===0?"":["## The panel \u2014 run these critics first","","This project reviews through a panel of roles. Each is available to you as a","subagent with its own narrow view and its own reading list:","",t.roles.map(n=>`- **${n.name}** \u2014 ${n.description}`).join(`
|
|
947
947
|
`),"","Delegate to **every** role above \u2014 **in parallel**, all Task calls in one","turn. Give each role the SAME briefing (DEV-651 \u2014 the panel's quality is","the briefing's quality, not the coordinator's mood):","","- the review subject: `git diff refs/worktree/codepipe/review-base..HEAD`"," in each repo under `code/` \u2014 the base ref is pinned, do not diff against"," a branch tip;","- the finding contract: every finding names file + line, the concrete"," failing scenario, and stays within the diff \u2014 or states explicitly how"," the change broke an untouched place;","- established facts the role must not re-derive (the BUILD verdict when"," your prompt carries one).","","The roles are independent read-only views that never wait on each other,","so the panel costs the time of its slowest member, not the sum. Then do","your own job on what comes back:","",`1. Save each role's findings verbatim as \`${e}/<role>.md\`.`,"2. **Deduplicate.** Two roles reporting the same defect is one finding, not two.","3. **Filter.** A finding earns a round-trip only if it is a real defect, a"," regression or a convention the project actually enforces. Taste-level notes"," go in the summary, never in the remarks.","4. **Decide.** The verdict is yours, not a vote: a role can be wrong, and you"," are the one who read the code. When you overrule a role, say why in the"," summary.","","A role that returns nothing is a normal outcome \u2014 do not manufacture findings","to justify the panel.",""].join(`
|
|
948
|
-
`)}var
|
|
948
|
+
`)}var $u,hb=S(()=>{"use strict";D();$u=".claude/agents"});var yb={};Ge(yb,{COUNCIL_ANSWER_PATH:()=>gb,readCouncilVerdict:()=>yP});import{readFileSync as hP}from"node:fs";import{join as gP}from"node:path";function yP(t){let e;try{e=hP(gP(t,gb),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var gb,wb=S(()=>{"use strict";gb="meta/council-answer.json"});var kb={};Ge(kb,{QUEUE_PLAN_PATH:()=>bb,readQueuePlan:()=>kP});import{readFileSync as wP}from"node:fs";import{join as bP}from"node:path";function kP(t){let e;try{e=wP(bP(t,bb),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var bb,vb=S(()=>{"use strict";bb="meta/queue-plan.json"});import{mkdirSync as $b,readFileSync as qs,readdirSync as vP,writeFileSync as xb}from"node:fs";import{homedir as $P}from"node:os";import{dirname as xP,join as _t}from"node:path";function EP(t){let e=Buffer.from(t,"utf-8");if(e.length<=Ys)return t;let r=Math.floor(Ys/4),n=Ys-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}
|
|
949
949
|
|
|
950
|
-
\u2026 [${s} bytes elided \u2014 log capped at ${
|
|
950
|
+
\u2026 [${s} bytes elided \u2014 log capped at ${Ys} bytes for upload] \u2026
|
|
951
951
|
|
|
952
|
-
${i}`}function
|
|
952
|
+
${i}`}function RP(){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 Zo(t={}){let e=Me(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=my(t.profile,e.sandboxId,!!Q("SANDBOX_CONFIG")),s=_t($P(),".codepipe","logs"),a=Ii("SANDBOX_LOG",i,s);if(a.enabled){let A=new wn(a);Ci(A),console.log(`[log] file logging \u2192 ${A.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Xe} (protocol ${mt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Cy(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=Ny();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new Mn(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,w=!1,b=()=>{let A=u.openControlSocket();return f=A,A.on("open",()=>{console.log("[ws] connected");let h={type:"sandbox_hello",platformVersion:Xe,protocolVersion:mt};A.send(JSON.stringify(h))}),A.on("message",h=>{let F=h.toString("utf-8"),L=null;try{let q=JSON.parse(F);q&&typeof q=="object"&&(L=q)}catch{}if(L&&L.type==="hello"){let q=L;g=so(q.protocolVersion);let ee=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${q.platformVersion} (protocol ${q.protocolVersion}) \u2014 ${ee}`),g&&(w=!1);return}if(L&&L.type==="pause_job"){let q=typeof L.jobId=="string"?L.jobId:"",ee=q?m.get(q):void 0;ee?(console.warn(`[ws] pause_job ${q} \u2014 aborting agent`),ee.paused=!0,ee.abort.abort()):console.log(`[ws] pause_job ${q} \u2014 not a running job, ignoring`),q&&A.send(JSON.stringify({type:"job_paused",jobId:q}));return}if(L&&(L.type==="chat_user_message"||L.type==="chat_finalize")){let q=typeof L.jobId=="string"?L.jobId:"",ee=q?m.get(q):void 0;if(ee?.chatInbox)if(L.type==="chat_user_message"){let se=typeof L.text=="string"?L.text:"";se.trim()&&ee.chatInbox.push({kind:"user",text:se})}else ee.chatInbox.finalize();else console.log(`[ws] ${String(L.type)} ${q} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${F}`)}),A.on("close",(h,F)=>{console.log(`[ws] closed code=${h} reason=${F?.toString()||""}`),f===A&&(f=null),!p&&setTimeout(b,2e3)}),A.on("error",h=>console.warn(`[ws] error: ${h.message}`)),A},v=b(),y=async A=>{for(;!p;){if(g===!1){w||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Xe}, protocol ${mt}) \u2014 not claiming jobs until versions align.`),w=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await u.claim(d.signal,A);if(h.status===204)continue;if(h.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,p=!0;break}if(!h.ok){console.warn(`[claim:${A}] ${h.status} \u2014 backoff 5s`),await new Promise(L=>setTimeout(L,5e3));continue}let F=await h.json();await k(u,F)}catch(h){if(d.signal.aborted)break;let F=h instanceof Error?h.message:String(h);console.warn(`[claim:${A}] error: ${F} \u2014 backoff 5s`),await new Promise(L=>setTimeout(L,5e3))}}};async function k(A,h){let F={abort:new AbortController,paused:!1};Da(h.role)&&(F.chatInbox=RP()),m.set(h.jobId,F);let L=!1,q=null,ee=null,se=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),Nt=async()=>{try{await A.heartbeat(h.jobId)==="claim_lost"&&(L=!0,console.warn(`[job] ${h.jobId} claim lost \u2014 HUB sweeper took it`))}catch(R){let x=R instanceof Error?R.message:String(R);console.warn(`[job] ${h.jobId} heartbeat error: ${x}`)}};Nt();let Be=setInterval(()=>{Nt()},se),Ne=new Date().toISOString();console.log(`[job] ${h.jobId} claimed \u2014 role=${h.role} task=${h.taskId} phase=${h.phase}`),console.log(`[job] ${h.jobId} prompt (${h.prompt.length} chars):`),console.log(E(h.prompt," \u2502 "));let Ce=[],Oe=null,Ee=400,rt=25,Ot=500,Lt=()=>{if(Oe&&(clearTimeout(Oe),Oe=null),Ce.length===0)return;let R=Ce.splice(0,Ce.length),x=f;if(!x||x.readyState!==x.OPEN)return;let I={type:"agent_activity",jobId:h.jobId,taskId:h.taskId,projectId:h.projectId,role:h.role,phase:h.phase,events:R};try{x.send(JSON.stringify(I))}catch{}},U=R=>{Ce.push(R),Ce.length>Ot&&Ce.shift(),Ce.length>=rt?Lt():Oe||(Oe=setTimeout(Lt,Ee))},G=h.role==="analysis"&&h.taskId.startsWith("draft::")?h.taskId.slice(7):null,M=new Set,T=null;try{if(!c){L||await A.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:Ne,finishedAt:new Date().toISOString()});return}if(!Py(o,h.provider??null)){L||await A.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${h.provider??"claude"}"`},startedAt:Ne,finishedAt:new Date().toISOString()});return}let R=Tw(h.jobId);console.log(`[job] ${h.jobId} workspace=${R.dir}`);let x=C(h,r);q=x.gitCreds,ee=x.contextGitCreds;let I=q?.env,X=x.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:x.claudeOauthToken}:void 0,H=[],re=null,la=null;try{let O=h.role==="build"?"clone":"worktree";H=await fw(R.dir,h.projectId,h.projectRepos,O,I,n);let N=await mw(R.dir,h.projectId,h.contextRepo,"worktree",I,n);la=N,re=N?.workspacePath??null}catch(O){let N=O instanceof Error?O.message:String(O);console.warn(`[job] ${h.jobId} materialize failed: ${N}`),L||await A.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${N}`},startedAt:Ne,finishedAt:new Date().toISOString()}),R.dispose();return}let ro=h.model,ui=h.effort;h.role==="build"&&h.modelDiscovery&&!yw(re)&&(ro=h.modelDiscovery,ui=h.effortDiscovery,console.log(`[job] ${h.jobId} BUILD discovery (no steps in ${du}) \u2014 model=${ro}`));let Xu=async()=>{if(!h.deliveries||h.deliveries.length===0)return[];let O=h.contextRepo?.cloneUrl;if(!O||!I)throw new Error(O?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let N=[];for(let Y of h.deliveries){let z=H.find(oe=>oe.name===Y.name);if(z){if(h.role==="implement"&&Y.baseSha&&Y.baseSha!==z.baseSha){let oe=await aw(z,Y.deliveryRef,Y.deliverySha,Y.baseSha,O,I);console.log(`[job] ${h.jobId} ${z.name}: base moved ${Y.baseSha.slice(0,10)} \u2192 ${z.baseSha.slice(0,10)} \u2014 re-applied delivery ${Y.deliverySha.slice(0,10)} (${oe.length} conflicted file(s))`),oe.length>0&&N.push(`- **${z.name}**:`,...oe.map($e=>` - \`${$e}\``));continue}await sw(z,Y.deliveryRef,Y.deliverySha,O,I),console.log(`[job] ${h.jobId} ${z.name}: checked out delivery ${Y.deliverySha.slice(0,10)} for ${h.role}`)}}return N},ua=[];if(h.role==="build"||h.role==="implement"||h.role==="code-review")try{ua=await Xu()}catch(O){let N=O instanceof Error?O.message:String(O);console.warn(`[job] ${h.jobId} delivery checkout failed: ${N}`),L||await A.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${N}`},startedAt:Ne,finishedAt:new Date().toISOString()}),R.dispose();return}if(h.role==="code-review"){let O=h.metadata?.externalReview===!0;for(let N of H)try{if(O){let Y=h.projectRepos.find(oe=>oe.name===N.name)?.defaultBranch??N.ref,z=await uw(N,Y,I);z?console.log(`[job] ${h.jobId} ${N.name}: review base ${z.slice(0,10)} (merge-base with ${Y})`):console.warn(`[job] ${h.jobId} ${N.name}: no merge-base with ${Y} \u2014 review base not pinned (agent falls back to manual deepen)`)}else await uu(N,N.baseSha,I),console.log(`[job] ${h.jobId} ${N.name}: review base ${N.baseSha.slice(0,10)} (pre-delivery)`)}catch(Y){let z=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${h.jobId} ${N.name}: review-base pin failed: ${z}`)}}let da=h.role==="resolve-conflict"?h.metadata?.mergeBranchByRepo??h.metadata?.taskBranchByRepo??{}:{},Ju="";if(h.role==="resolve-conflict"){if(!H.some(O=>da[O.name])){let O="resolve-conflict job carries no branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${h.jobId} ${O}`),L||await A.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:Ne,finishedAt:new Date().toISOString()}),R.dispose();return}try{let O=[];for(let N of H){let Y=da[N.name];if(!Y)continue;let z=await lu(N,Y,I);console.log(`[job] ${h.jobId} ${N.name}: merged ${Y} into ${N.ref} \u2014 ${z.length} conflicted file(s)`),z.length>0?O.push(`- **${N.name}**:`,...z.map(oe=>` - \`${oe}\``)):O.push(`- **${N.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Ju=`
|
|
953
953
|
|
|
954
954
|
## Conflicts to resolve
|
|
955
955
|
|
|
956
|
-
`+(
|
|
956
|
+
`+(O.length>0?O.join(`
|
|
957
957
|
`):"(no task branches to merge)")+`
|
|
958
|
-
`}catch(
|
|
958
|
+
`}catch(O){let N=O instanceof Error?O.message:String(O);console.warn(`[job] ${h.jobId} conflict merge failed: ${N}`),L||await A.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${N}`},startedAt:Ne,finishedAt:new Date().toISOString()}),R.dispose();return}}let pa=null,Zu="";if(h.contextPack&&re)try{let{assembleContextPack:O}=await Promise.resolve().then(()=>(Zw(),Jw)),N=O({contextDir:re,taskKey:String(h.metadata?.trackerIssueKey??h.taskId.split(":")[1]??""),title:String(h.metadata?.taskTitle??""),repoDirs:new Map(H.map(Y=>[Y.name,Y.workspacePath])),idfPenalty:h.contextPackIdf!==!1});N?($b(_t(R.dir,"meta"),{recursive:!0}),xb(_t(R.dir,"meta","context-pack.md"),N.markdown),pa=N.markdown,Zu=N.top??"",console.log(`[job] ${h.jobId} context pack: ${N.markdown.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${h.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(O){let N=O instanceof Error?O.message:String(O);console.warn(`[job] ${h.jobId} context pack failed (non-fatal): ${N}`)}let Qu="",di=null,fa=null;try{let{loadSkills:O,materializeSkills:N,renderSkillsBlock:Y}=await Promise.resolve().then(()=>(nb(),rb)),z=h.skills??{bundled:!0,context:!0,repo:!0},oe=O({contextDir:re,repoDirs:H.map(nt=>nt.workspacePath),sources:z});for(let nt of oe.errors)console.warn(`[job] ${h.jobId} skill ${nt.source}: ${nt.error}`);let $e=N(R.dir,oe.skills),ue=["implement","rework","testing"].includes(h.role)?dc(uc(_(re,h.taskId))):[];Qu=Y(oe.skills,ue),$e.length>0&&console.log(`[job] ${h.jobId} skills: ${oe.skills.map(nt=>nt.name).join(", ")}`);let{parseMarketplaces:Fe,enabledPluginsSetting:Vr}=await Promise.resolve().then(()=>(D(),Rp)),{sources:zr,errors:oo}=Fe(z.marketplaces??[]);for(let nt of oo)console.warn(`[job] ${h.jobId} marketplace ${nt}`);if(zr.length>0&&(z.plugins??[]).length>0){let{seedMarketplaces:nt}=await Promise.resolve().then(()=>(cb(),ab)),Xr=await nt(zr);for(let J of Xr.errors)console.warn(`[job] ${h.jobId} marketplace ${J.repo}: ${J.error}`);let{enabled:Jr,unknown:Zr}=Vr(z.plugins??[],Xr.ready);for(let J of Zr)console.warn(`[job] ${h.jobId} plugin ${J}: no such marketplace in this project`);Xr.dir&&Object.keys(Jr).length>0&&(di=Xr.dir,fa={enabledPlugins:Jr},console.log(`[job] ${h.jobId} plugins: ${Object.keys(Jr).join(", ")}`))}}catch(O){let N=O instanceof Error?O.message:String(O);console.warn(`[job] ${h.jobId} skills unavailable (non-fatal): ${N}`)}let ed="",bv=h.role==="code-review"&&h.metadata?.reviewPanel===!1;if(["code-review","council","analyze","testing"].includes(h.role)&&!bv)try{let{loadRoles:O}=await Promise.resolve().then(()=>(fb(),pb)),{materializeRoleAgents:N,renderRolesBlock:Y}=await Promise.resolve().then(()=>(hb(),mb)),z=O(re);for(let Fe of z.errors)console.warn(`[job] ${h.jobId} role ${Fe.file}: ${Fe.error}`);let oe=h.role==="council"?"council":h.role==="analyze"?"plan_review":"code_review",$e=h.role==="council"?"council":h.role==="analyze"?"plan-review":h.role==="testing"?"testing":"code-review",ue=N(R.dir,z.roles,oe,re);ed=Y(ue,$e),console.log(`[job] ${h.jobId} review panel: ${ue.roles.length>0?ue.roles.map(Fe=>Fe.name).join(", "):"(no roles)"}`)}catch(O){let N=O instanceof Error?O.message:String(O);console.warn(`[job] ${h.jobId} review panel unavailable (non-fatal): ${N}`)}let kv=ua.length>0?`
|
|
959
959
|
|
|
960
960
|
## Base branch moved \u2014 conflicts to resolve
|
|
961
961
|
|
|
962
962
|
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:
|
|
963
963
|
|
|
964
|
-
`+
|
|
964
|
+
`+ua.join(`
|
|
965
965
|
`)+`
|
|
966
|
-
`:"",
|
|
967
|
-
`));
|
|
968
|
-
`).map(
|
|
969
|
-
`)}function
|
|
970
|
-
[${
|
|
971
|
-
${e}`);let r=await
|
|
966
|
+
`:"",td=j($(h.prompt,H,re).replace(/\{\{contextPackTop\}\}/g,()=>Zu),re,h.taskId).replace(/\{\{rolesBlock\}\}/g,ed).replace(/\{\{skillsBlock\}\}/g,Qu)+Ju+kv,no=[...H.map(O=>O.workspacePath),...re?[re]:[]];if(no.length>0&&console.log(`[job] ${h.jobId} --add-dir: ${no.join(", ")}`),By("agent-request")){let O=Os(Dn(h.metadata??{})),N=Fy(h.projectId,h.jobId,"agent-request",[`# Agent request \u2014 job ${h.jobId}`,"",`- project: ${h.projectId}`,`- task: ${h.taskId}`,`- role: ${h.role}`,`- model: ${ro??"(backend default)"}`,`- effort: ${ui??"(backend default)"}`,`- add-dirs:${no.length>0?"":" (none)"}`,...no.map(Y=>` - ${Y}`),"","## Append-system-prompt (language directive)","","```",O,"```","","## Prompt","",td,"",...pa?["## Context pack (meta/context-pack.md)","",pa]:["## Context pack","","(not generated for this job)"],""].join(`
|
|
967
|
+
`));N&&console.log(`[debug] ${h.jobId} agent request \u2192 ${N}`)}G&&(T=setInterval(()=>{let N=f;if(!N||N.readyState!==N.OPEN)return;let Y;try{Y=vP(_t(R.dir,"drafts")).filter(z=>z.endsWith(".json")).sort()}catch{return}for(let z of Y){if(M.has(z))continue;if(M.size>=xc)break;let oe;try{let ue=JSON.parse(qs(_t(R.dir,"drafts",z),"utf-8")),Fe=typeof ue.localRef=="string"?ue.localRef:"",Vr=typeof ue.title=="string"?ue.title:"",zr=typeof ue.body=="string"?ue.body:"";if(!Fe||!Vr)continue;oe={localRef:Fe,title:Vr,body:zr,...ue.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ue.links)?{links:ue.links}:{}}}catch{continue}M.add(z);let $e={type:"child_draft",jobId:h.jobId,projectId:h.projectId,draftId:G,child:oe};try{N.send(JSON.stringify($e))}catch{}}},1500));try{let O={workspaceDir:R.dir,role:h.role,prompt:td,addDirs:no,metadata:h.metadata??{},...ro?{model:ro}:{},...ui?{effort:ui}:{},...X||di?{env:{...X??{},...di?{CLAUDE_CODE_PLUGIN_SEED_DIR:di}:{}}}:{},...fa?{settings:fa}:{},signal:F.abort.signal,onActivity:U},N=F.chatInbox?await c.run({...O,interactive:{inbox:F.chatInbox.iterable}}):await Ly(c,O,{jobId:h.jobId,policy:l,onBeforeRetry:async()=>{R.clean();for(let J of H)try{await tw(J);let be=da[J.name];h.role==="resolve-conflict"&&be&&await lu(J,be,I)}catch(be){let zt=be instanceof Error?be.message:String(be);console.warn(`[job] ${h.jobId} worktree reset failed (${J.name}): ${zt}`)}try{await Xu()}catch(J){let be=J instanceof Error?J.message:String(J);console.warn(`[job] ${h.jobId} delivery re-checkout failed: ${be}`)}},aborted:()=>L||F.paused}),Y=[];if(SP.has(h.role)&&H.length>0){let J=h.metadata??{},be=typeof J.commitMessage=="string"?J.commitMessage:`${h.taskId}: changes`,zt=h.contextRepo?.cloneUrl,io=ee?.env;if(!zt||!io)throw new Error("delivery requested but "+(zt?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let ma=h.taskId.includes(":")?h.taskId.slice(h.taskId.indexOf(":")+1):h.taskId;for(let xt of H){let Qr=await rw(xt,be);if(!Qr){console.log(`[job] ${h.jobId} ${xt.name}: no changes \u2014 no delivery`);continue}let ha=`codepipe/deliveries/${ma}/${h.jobId}/${xt.name}`;await nw(xt,Qr,ha,zt,io);let vv=await iw(xt,Qr);Y.push({name:xt.name,deliveryRef:ha,deliverySha:Qr,baseSha:xt.baseSha,changedFiles:vv}),console.log(`[job] ${h.jobId} ${xt.name}: delivered ${Qr.slice(0,10)} \u2192 ${ha}`);let rd=await ow(xt,Qr);if(rd.trim().length>0){let $v=_t("display",`${xt.name}.diff`),nd=_t(R.dir,$v);$b(xP(nd),{recursive:!0}),xb(nd,rd)}}}if(h.role==="resolve-conflict"&&Y.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's SOLUTION.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let z;h.role==="build"&&(z=bw(R.dir),console.log(`[job] ${h.jobId} build verdict: ok=${z.ok}`+(z.failedStep?` failedStep=${z.failedStep}`:"")));let oe;if(h.role==="code-review"){oe=fu(R.dir),console.log(`[job] ${h.jobId} review verdict: approved=${oe.approved}`);try{let{parseChangedRanges:J,markFindingScope:be}=await Promise.resolve().then(()=>(mu(),vw)),zt=new Map;for(let io of H)try{let ma=await lw(io,I);zt.set(io.name,J(ma))}catch{}be(oe,zt,H.length===1?H[0].name:void 0)}catch(J){console.warn(`[job] ${h.jobId} finding scope marking failed (non-fatal): ${String(J)}`)}}let $e;if(h.role==="council"){let{readCouncilVerdict:J}=await Promise.resolve().then(()=>(wb(),yb));$e=J(R.dir)??void 0,console.log(`[job] ${h.jobId} council: ${$e?"answered":"no verdict \u2014 task stops for a human"}`)}let ue;if(h.role==="testing"){try{let J=qs(_t(R.dir,"meta","test-result.json"),"utf-8");ue=JSON.parse(J)}catch{ue=void 0}console.log(`[job] ${h.jobId} test verdict: ${ue?"written":"none \u2014 proceeding to the PR"}`)}let Fe;if(h.role==="observer"){let{readQueuePlan:J}=await Promise.resolve().then(()=>(vb(),kb));Fe=J(R.dir)??void 0,console.log(`[job] ${h.jobId} queue plan: ${Fe?"produced":"none \u2014 batch keeps the staged order"}`)}let Vr=N.artifactPaths.length>0?N.artifactPaths:R.listFiles(),zr=Array.from(new Set(Vr)),oo;if(la)try{let J=h.role==="index"?["adr/SOURCES.md"]:h.role==="backfill"?["adr"]:[],be=await hw(la,J);be.length>0&&(oo=be,console.log(`[job] ${h.jobId} captured ${be.length} knowledge file(s) for Context Repo`))}catch(J){let be=J instanceof Error?J.message:String(J);console.warn(`[job] ${h.jobId} knowledge capture failed (non-fatal): ${be}`)}let{artifacts:nt,omitted:Xr,dropped:Jr}=xw(R.dir,zr);for(let J of Xr)console.warn(`[job] ${h.jobId} artifact ${J.path} (${J.bytes} bytes) exceeded upload budget \u2014 content omitted`);Jr.length>0&&console.warn(`[job] ${h.jobId} artifact listing truncated: ${Jr.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Zr={jobId:h.jobId,status:"succeeded",artifacts:nt,...oo?{contextWrites:oo}:{},...Y.length>0?{deliveries:Y}:{},log:EP(N.log),startedAt:Ne,finishedAt:new Date().toISOString(),usage:N.usage,...N.rateLimit?{rateLimit:N.rateLimit}:{},...z?{build:z}:{},...oe?{review:oe}:{},...Fe!==void 0?{queuePlan:Fe}:{},...$e!==void 0?{council:$e}:{},...ue!==void 0?{test:ue}:{}};if(L||F.paused)console.warn(`[job] ${h.jobId} skipping result upload \u2014 ${F.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await A.submitResult(Zr),console.log(`[job] ${h.jobId} done \u2014 uploaded ${Zr.artifacts.length} artifact(s):`);for(let J of Zr.artifacts){let be=Buffer.from(J.contentBase64,"base64").length;console.log(` \xB7 ${J.path} (${be} bytes)`)}Zr.artifacts.length===0&&console.warn(`[job] ${h.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(O){let N=O instanceof Error?O.message:String(O);if(F.paused)console.log(`[job] ${h.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(L)console.warn(`[job] ${h.jobId} failed after claim lost (${N}) \u2014 skipping result upload`);else{let Y=Oy(O),z=O instanceof mr,oe=O instanceof Pt,$e=O instanceof dt?O.details.rateLimited:void 0,ue=O instanceof dt?O.details.usage:void 0;console.warn($e?`[job] ${h.jobId} rate-limited (${$e.kind??"unknown window"}`+($e.resetAtMs?`, resets ${new Date($e.resetAtMs).toISOString()}`:"")+") \u2014 HUB will hold and auto-resume":Y?`[job] ${h.jobId} failed: ${N} (Claude auth \u2014 token invalid/expired)`:z?`[job] ${h.jobId} failed: ${N} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:oe?`[job] ${h.jobId} failed: ${N} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${h.jobId} failed: ${N}`),await A.submitResult({jobId:h.jobId,status:"failed",artifacts:[],error:{message:N},startedAt:Ne,finishedAt:new Date().toISOString(),...Y?{authError:!0}:{},...z?{buildInconclusive:!0}:{},...oe?{reviewInconclusive:!0}:{},...$e?{rateLimited:$e}:{},...ue?{usage:ue}:{}})}}finally{R.dispose()}}finally{clearInterval(Be),T&&clearInterval(T),Lt(),F.chatInbox?.close(),m.delete(h.jobId),q?.cleanup(),ee?.cleanup()}}function C(A,h){if(!A.credBundle)return{gitCreds:null,contextGitCreds:null};if(!h)return console.warn(`[job] ${A.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let F;try{F=JSON.parse(Pn(h,A.credBundle).toString("utf-8"))}catch(se){return console.warn(`[job] ${A.jobId} failed to open credBundle: ${se instanceof Error?se.message:String(se)}`),{gitCreds:null,contextGitCreds:null}}let L=au(F);L&&console.log(`[job] ${A.jobId} cred bundle opened \u2014 git creds configured`);let q=Vy(F,A.contextRepo.cloneUrl),ee={gitCreds:L,contextGitCreds:q};return F.claudeOauthToken&&(ee.claudeOauthToken=F.claudeOauthToken),ee}function E(A,h){return A.split(`
|
|
968
|
+
`).map(F=>h+F).join(`
|
|
969
|
+
`)}function $(A,h,F){let L=h[0]?.workspacePath??"";return A.replace(/\{\{codeDir\}\}/g,L).replace(/\{\{codeRoot\}\}/g,L?L.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,F??"")}function _(A,h){let F=h.includes("::")?"":h.split(":",2)[1]??"";if(!A||!F)return"";for(let L of["PLAN.md","SOLUTION.md"])try{return qs(_t(A,"tasks",F,L),"utf-8")}catch{}return""}function j(A,h,F){let L=A,q=F.includes("::")?"":F.split(":",2)[1]??"",ee=se=>{if(!h||!q)return"";try{return qs(_t(h,"tasks",q,se),"utf-8").trim()}catch{return""}};if(L.includes("{{planMd}}")||L.includes("{{solutionMd}}")){let se=ee("PLAN.md")||ee("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";L=L.replace(/\{\{planMd\}\}/g,()=>se),L=L.replace(/\{\{solutionMd\}\}/g,()=>se)}if(L.includes("{{taskDescription}}")){let se=ee("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";L=L.replace(/\{\{taskDescription\}\}/g,()=>se)}return L=Pw(L,h),L}let B=A=>{if(p)return;p=!0,console.log(`
|
|
970
|
+
[${A}] shutting down`),d.abort();let h=[...m.keys()];for(let q of m.values())q.abort.abort();let F=new AbortController,L=setTimeout(()=>F.abort(),3e3);(async()=>(await Promise.all(h.map(async q=>{try{await u.releaseJob(q,`sandbox ${A}`,F.signal),console.log(`[${A}] released job ${q}`)}catch(ee){let se=ee instanceof Error?ee.message:String(ee);console.warn(`[${A}] release failed: ${se} (sweeper will reclaim)`)}})),clearTimeout(L),v.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM"));let K=[y("implementation")];e.planningLane!==!1?K.push(y("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(K)}var Ys,SP,Sb=S(()=>{"use strict";D();ut();Ic();_y();Ls();My();Fr();Gy();Ke();Ns();zy();Ql();gw();ww();kw();mu();Sw();Cw();Aw();Ys=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),SP=new Set(["implement","resolve-conflict"])});var Hn=S(()=>{"use strict";gy();Sb();Ns()});import{cancel as TP,isCancel as Rb,log as et,password as IP,text as CP}from"@clack/prompts";function PP(t){return Rb(t)&&(TP("aborted"),process.exit(1)),typeof t=="string"?t:""}function Tb(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function _P(t){let e=Bc({redirectUri:Uc,challenge:t.challenge,state:t.state});et.message(`Open this URL, approve the access, and paste the code shown:
|
|
971
|
+
${e}`);let r=await CP({message:"Authorization code \u2014 blank to skip"});if(Rb(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=Nf(r,t.state);return await Fc({code:n,verifier:t.verifier,state:t.state,redirectUri:Uc})}catch(n){return et.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function AP(t){if(Rc()?.claude?.oauthToken&&!t.farm)return et.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!=="1"||!process.stdout.isTTY)return null;et.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=Ni(),n;try{n=await Of({...r,openUrl:jr,log:i=>et.message(i)})}catch(i){et.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await _P(r);if(s===null)return null;n=s}let o=await Ht(n.oauthToken);return o==="invalid"?(et.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(et.success(`Claude: logged in \u2014 ${Tb(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function Ib(t){et.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
|
|
972
972
|
In another terminal:
|
|
973
973
|
1. install Claude Code \u2014 https://claude.com/claude-code
|
|
974
974
|
2. run \`claude setup-token\`
|
|
975
975
|
3. paste the token it prints (starts with sk-ant-) below`+(t.farm?`
|
|
976
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=RP(await EP({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return tt.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`."),"";e.startsWith("sk-ant-")||tt.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`.");let r=await Kt(e);return r==="invalid"?(tt.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),Rb(t)):(tt.success(`Claude: ${Tb(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var Ib,Cb=S(()=>{"use strict";Oi();wn();pe();Gc();Ib={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:CP,promptManual:Rb,validate:Kt}});function Pb(t){return Ib}async function _b(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Ab=S(()=>{"use strict";Cb()});async function Kn(t,e,r){return e.host==="github"?_P(t,e,r):e.host==="gitlab"?MP(t,e,r):UP(t,e,r)}async function jb(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 rt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Nb(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 Ve(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ob(e.gitlabToken,t):o}}return e.bitbucket?(await Ot(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Lb(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 Nb(t,e){let r=!1;try{r=(await rt(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 Ob(t,e){let r=!1;try{r=(await Ve(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 Lb(t,e){let r=!1;try{r=(await Ot(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 rt(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(PP+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 _P(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 AP(n,e,r),i=await jP(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Sn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await NP(n,o.owner,o.name,a.path,i)||await OP(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 AP(t,e,r){let n=await rt(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 Nb(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await $u(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 rt(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 $u(t,e){let{status:r,data:n}=await rt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function jP(t,e,r){let{data:n}=await rt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function NP(t,e,r,n,o){let{status:i,data:s}=await rt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function OP(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 rt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Ve(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(LP+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 MP(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 Ve(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 Ob(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Ve(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 f=await Ve(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await Ve(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Sn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await Ve(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.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 Ve(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 Ot(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(DP+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 UP(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 Ot(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 Lb(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 Ot(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=Sn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await Ot(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 m of l)p.set(m.path,m.content);if((await Ot(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 PP,LP,DP,Zo=S(()=>{"use strict";jr();PP="https://api.github.com";LP="https://gitlab.com/api/v4";DP="https://api.bitbucket.org/2.0"});function ze(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=BP[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 BP,Ys=S(()=>{"use strict";BP={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as FP}from"node:crypto";import{existsSync as Mb,mkdirSync as GP,readFileSync as Db,readdirSync as KP,rmSync as Vs,writeFileSync as HP}from"node:fs";import{homedir as WP}from"node:os";import{dirname as qP,join as xu}from"node:path";function Ub(){return xu(WP(),".codepipe","init-drafts")}function Su(t){let e=FP("sha256").update(t).digest("hex").slice(0,16);return xu(Ub(),`${e}.json`)}function Bb(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=YP)}function Fb(t){let e=Su(t);if(!Mb(e))return null;try{let r=JSON.parse(Db(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Bb(r.savedAt)?(Vs(e,{force:!0}),null):r}catch{return null}}function Eu(t){Vs(Su(t),{force:!0})}function Gb(){let t=Ub();if(Mb(t))for(let e of KP(t)){let r=xu(t,e);try{let n=JSON.parse(Db(r,"utf-8"));Bb(n.savedAt)&&Vs(r,{force:!0})}catch{Vs(r,{force:!0})}}}var YP,Hn,Kb=S(()=>{"use strict";YP=24*60*60*1e3;Hn=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(){Eu(this.cwd)}persist(){let e=Su(this.cwd);GP(qP(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};HP(e,JSON.stringify(r,null,2)+`
|
|
977
|
-
`,{mode:384})}}});function
|
|
978
|
-
`).map(n=>n.trim()).filter(Boolean);return Yb(r)}catch{return!1}}async function r_(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)?Yb(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Vb(t,e){for(let r of t)try{let n=e.localRoot!=null?zP(e.localRoot,r.mountAs??r.name):null;if(n&&VP(n)?await t_(n):await r_(r,e.tokens))return!0}catch{}return!1}var JP,ZP,QP,zb=S(()=>{"use strict";JP=3,ZP=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,QP=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Xb}from"node:fs";import{join as Jb}from"node:path";import{simpleGit as Zb}from"simple-git";async function ei(t,e,r={}){let n=r.log??n_,o=[];for(let i of e){let s=Jb(t,i.mountAs),a=Rp(i);if(!Xb(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 Zb().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=Qo(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(!Xb(Jb(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=Zb(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!o_(l,a)){n.warn(`${i.mountAs}/ origin (${Qo(l)||"none"}) != expected (${Qo(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:Qo(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=Qo(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 o_(t,e){return Qb(t)===Qb(e)}function Qb(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Qo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function ek(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 ei(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 n_,zs=S(()=>{"use strict";bt();n_={info:t=>console.log(t),warn:t=>console.warn(t)}});import{existsSync as Tu,readFileSync as Ru,writeFileSync as tk}from"node:fs";import{join as Iu}from"node:path";import{parseDocument as Cu}from"yaml";function rk(t){let e={};return t.branches.integration&&(e.integration=t.branches.integration),t.branches.stable!==void 0&&(e.stable=t.branches.stable),t.branches.release_pattern!==void 0&&(e.release_pattern=t.branches.release_pattern),{flow:t.flow,branches:e}}function nk(t){let{errors:e}=an(t);if(e.length>0)throw new Error(`invalid git config: ${e.join("; ")}`)}async function ok(t,e){let r=rk(e);nk(r);let n=Iu(t,"project.yaml");if(!Tu(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=Cu(Ru(n,"utf-8"));o.set("git",r),tk(n,o.toString())}async function ik(t,e,r){let n=rk(r);nk(n);let o=Iu(t,"project.yaml");if(!Tu(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Cu(Ru(o,"utf-8"));Xi(i,e).set("git",n),tk(o,i.toString())}function sk(t){let e=Iu(t,"project.yaml");if(!Tu(e))return null;try{let r=Cu(Ru(e,"utf-8")).toJS();return i_(r?.git)}catch{return null}}function i_(t){if(!t||typeof t!="object")return null;let e=t,r=e.flow;if(r!=="simple"&&r!=="gitflow"&&r!=="release")return null;let n=e.branches;if(!n||typeof n!="object")return null;let o=n,i=o.integration;if(typeof i!="string"||!i)return null;let s={flow:r,branches:{integration:i}};return typeof o.stable=="string"&&(s.branches.stable=o.stable),typeof o.release_pattern=="string"&&(s.branches.release_pattern=o.release_pattern),s}var ak=S(()=>{"use strict";D();Ji()});import{confirm as s_,isCancel as a_}from"@clack/prompts";async function Xs(t){let e=ho(t.facts),r=t.confirm??c_,n=t.log??(()=>{}),o=t.readProject??sk,i=t.writeProject??ok,s=t.writeOverride??ik;if(!t.contextDir)return e.flow!=="simple"&&n(`git-flow: detected ${Wn(e)} (no context repo to persist)`),{outcome:"no-context",detected:e};let a=t.contextDir,c=o(a);return c===null?e.flow==="simple"?(n("git-flow: simple (single branch)"),{outcome:"silent-simple",detected:e}):await r(`Detected git-flow: ${Wn(e)}. Use it?`)?(await i(a,e),n(`git-flow: ${Wn(e)} (project default)`),{outcome:"wrote-project",detected:e}):(n("git-flow: keeping simple (detection declined)"),{outcome:"declined",detected:e}):wc(e,c)?await r(`This repo's git-flow (${Wn(e)}) differs from the project (${Wn(c)}). Record a per-repo override?`)?(await s(a,t.repoName,e),n(`git-flow: ${Wn(e)} (per-repo override for "${t.repoName}")`),{outcome:"wrote-override",detected:e}):(n(`git-flow: using the project flow for "${t.repoName}" (override declined)`),{outcome:"declined",detected:e}):{outcome:"match",detected:e}}function Wn(t){if(t.flow==="simple")return"simple (single branch)";let e=[`integration=${t.branches.integration}`];return t.branches.stable&&e.push(`stable=${t.branches.stable}`),t.branches.release_pattern&&e.push(`release=${t.branches.release_pattern}`),`${t.flow} (${e.join(", ")})`}async function c_(t){let e=await s_({message:t,initialValue:!0});return a_(e)?!1:e===!0}var Pu=S(()=>{"use strict";D();ak()});import{simpleGit as ck}from"simple-git";async function ti(t,e){let r=ck(t),n=null;try{n=(await r.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"")||null}catch{}!n&&e&&(n=await l_(e));let o=[];try{o=(await r.raw(["for-each-ref","--format=%(refname:short)","refs/remotes/origin"])).split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).map(s=>s.replace(/^origin\//,"")).filter(s=>s!=="HEAD"&&s!=="origin")}catch{o=[]}return{defaultBranch:n,branches:o}}async function l_(t){try{let e=await ck().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}var _u=S(()=>{"use strict"});import{simpleGit as u_}from"simple-git";async function lk(t,e,r){return t.host==="github"?d_(t,e,r):t.host==="gitlab"?p_(t,e,r):f_(t,e,r)}function Au(t){return new Error(`${t.owner}/${t.repoName} exists but is PUBLIC \u2014 a mirror holds the repository's full history and must be private. Make it private (or pick another name) and re-run`)}async function d_(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await rt(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw Au(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:o.data.ssh_url,created:!1}}let i=(await rt(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await $u(n,t.owner);if(!s&&!a)throw new Error(`"${t.owner}" is neither the token's account ("${i}") nor an organization it can see \u2014 nothing was created. Use a GitHub username or organization (not an email)`);r.info(`creating mirror ${t.owner}/${t.repoName} (github, ${a?"org":"user"})`);let c=await rt(n,"POST",a?`/orgs/${t.owner}/repos`:"/user/repos",{name:t.repoName,private:!0,auto_init:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"});if(!c.data)throw new Error(`GitHub: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url,created:!0}}async function uk(t,e,r){try{return t==="github"?(await rt(e,"GET","/user")).data?.login??null:t==="gitlab"?(await Ve(e,"GET","/user")).data?.username??null:r?(await Ot({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function p_(t,e,r){let n=e.gitlabToken;if(!n)throw new Error("GitLab PAT required to create a gitlab-hosted mirror");let o=encodeURIComponent(`${t.owner}/${t.repoName}`),i=await Ve(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw Au(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i.data.ssh_url_to_repo,created:!1}}let s={name:t.repoName,path:t.repoName,visibility:"private",initialize_with_readme:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"};if((await Ve(n,"GET","/user")).data?.username!==t.owner){let l=await Ve(n,"GET",`/namespaces/${encodeURIComponent(t.owner)}`);if(l.status===404||!l.data)throw new Error(`GitLab namespace "${t.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);s.namespace_id=l.data.id}r.info(`creating mirror ${t.owner}/${t.repoName} (gitlab)`);let c=await Ve(n,"POST","/projects",s);if(!c.data)throw new Error(`GitLab: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url_to_repo,created:!0}}async function f_(t,e,r){let n=e.bitbucket;if(!n)throw new Error("Bitbucket email + API token required to create a bitbucket-hosted mirror");let o=`/repositories/${t.owner}/${encodeURIComponent(t.repoName)}`,i=`git@bitbucket.org:${t.owner}/${t.repoName}.git`,s=await Ot(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw Au(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i,created:!1}}r.info(`creating mirror ${t.owner}/${t.repoName} (bitbucket)`);let a=await Ot(n,"POST",o,{json:{scm:"git",is_private:!0,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"}});if(a.status===404||!a.data?.slug)throw new Error(`Bitbucket cannot create ${t.owner}/${t.repoName} \u2014 check the workspace and that the credential may create repositories in it`);return{spec:t,sshUrl:i,created:!0}}async function dk(t,e,r){let n=u_(t);if((await n.raw(["rev-parse","--is-shallow-repository"])).trim()==="true")throw new Error("this clone is shallow \u2014 the mirror would be seeded with partial history. Run `git fetch --unshallow` first");if((await n.listRemote(["--heads",e])).trim().length>0)return r.info("mirror already has branches \u2014 leaving its content alone"),{seeded:!1};r.info("seeding mirror with the repository's branches and tags\u2026");let i=(await n.raw(["for-each-ref","refs/remotes/origin","--format=%(refname)"])).split(`
|
|
979
|
-
`).map(a=>a.trim()).filter(a=>a.length>0&&a!=="refs/remotes/origin/HEAD");if(i.length===0)throw new Error("the local clone has no origin branches to seed from");let s=i.map(a=>`${a}:refs/heads/${a.slice(20)}`);return await n.push([e,...s]),await n.push([e,"--tags"]),{seeded:!0}}function
|
|
980
|
-
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`),
|
|
981
|
-
`))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function
|
|
982
|
-
`))
|
|
983
|
-
`)};m.stdout?.on("data",
|
|
976
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=PP(await IP({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return et.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`."),"";e.startsWith("sk-ant-")||et.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`.");let r=await Ht(e);return r==="invalid"?(et.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),Ib(t)):(et.success(`Claude: ${Tb(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var Cb,Pb=S(()=>{"use strict";Oi();kn();de();Kc();Cb={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:AP,promptManual:Ib,validate:Ht}});function _b(t){return Cb}async function Ab(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var jb=S(()=>{"use strict";Pb()});async function Wn(t,e,r){return e.host==="github"?NP(t,e,r):e.host==="gitlab"?BP(t,e,r):GP(t,e,r)}async function Nb(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 tt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ob(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 Ye(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Lb(e.gitlabToken,t):o}}return e.bitbucket?(await At(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Mb(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 Ob(t,e){let r=!1;try{r=(await tt(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 Lb(t,e){let r=!1;try{r=(await Ye(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 Mb(t,e){let r=!1;try{r=(await At(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 tt(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(jP+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 NP(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 OP(n,e,r),i=await LP(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Rn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await MP(n,o.owner,o.name,a.path,i)||await DP(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 OP(t,e,r){let n=await tt(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 Ob(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await xu(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 tt(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 xu(t,e){let{status:r,data:n}=await tt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function LP(t,e,r){let{data:n}=await tt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function MP(t,e,r,n,o){let{status:i,data:s}=await tt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function DP(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 tt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Ye(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(UP+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 BP(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 Ye(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 Lb(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Ye(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 f=await Ye(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(f.status===404||!f.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=f.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let m=await Ye(n,"POST","/projects",d);if(!m.data)throw new Error("GitLab create project: empty response");i=m.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Rn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await Ye(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let f of m)l.add(f.path);if(m.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 Ye(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 At(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(FP+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 GP(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 At(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 Mb(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 At(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=Rn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await At(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 m of l)p.set(m.path,m.content);if((await At(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 jP,UP,FP,Qo=S(()=>{"use strict";Nr();jP="https://api.github.com";UP="https://gitlab.com/api/v4";FP="https://api.bitbucket.org/2.0"});function Ve(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=KP[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 KP,Vs=S(()=>{"use strict";KP={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as HP}from"node:crypto";import{existsSync as Db,mkdirSync as WP,readFileSync as Ub,readdirSync as qP,rmSync as zs,writeFileSync as YP}from"node:fs";import{homedir as VP}from"node:os";import{dirname as zP,join as Su}from"node:path";function Bb(){return Su(VP(),".codepipe","init-drafts")}function Eu(t){let e=HP("sha256").update(t).digest("hex").slice(0,16);return Su(Bb(),`${e}.json`)}function Fb(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=XP)}function Gb(t){let e=Eu(t);if(!Db(e))return null;try{let r=JSON.parse(Ub(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Fb(r.savedAt)?(zs(e,{force:!0}),null):r}catch{return null}}function Ru(t){zs(Eu(t),{force:!0})}function Kb(){let t=Bb();if(Db(t))for(let e of qP(t)){let r=Su(t,e);try{let n=JSON.parse(Ub(r,"utf-8"));Fb(n.savedAt)&&zs(r,{force:!0})}catch{zs(r,{force:!0})}}}var XP,qn,Hb=S(()=>{"use strict";XP=24*60*60*1e3;qn=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(){Ru(this.cwd)}persist(){let e=Eu(this.cwd);WP(zP(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};YP(e,JSON.stringify(r,null,2)+`
|
|
977
|
+
`,{mode:384})}}});function Wb(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 qb(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 Yb=S(()=>{"use strict"});import{existsSync as JP}from"node:fs";import{join as ZP}from"node:path";import{simpleGit as QP}from"simple-git";function n_(t){let e=t.split("/");return e[e.length-1]??t}function Vb(t){if(t.filter(r=>!t_.test(n_(r))).length>e_)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(r_.has(n))return!0}return!1}async function o_(t){try{let r=(await QP(t).raw(["ls-files"])).split(`
|
|
978
|
+
`).map(n=>n.trim()).filter(Boolean);return Vb(r)}catch{return!1}}async function i_(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)?Vb(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function zb(t,e){for(let r of t)try{let n=e.localRoot!=null?ZP(e.localRoot,r.mountAs??r.name):null;if(n&&JP(n)?await o_(n):await i_(r,e.tokens))return!0}catch{}return!1}var e_,t_,r_,Xb=S(()=>{"use strict";e_=3,t_=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,r_=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Jb}from"node:fs";import{join as Zb}from"node:path";import{simpleGit as Qb}from"simple-git";async function ti(t,e,r={}){let n=r.log??s_,o=[];for(let i of e){let s=Zb(t,i.mountAs),a=Ip(i);if(!Jb(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 Qb().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=ei(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(!Jb(Zb(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=Qb(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!a_(l,a)){n.warn(`${i.mountAs}/ origin (${ei(l)||"none"}) != expected (${ei(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:ei(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=ei(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 a_(t,e){return ek(t)===ek(e)}function ek(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function ei(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function tk(t={}){let e=Pe();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await ti(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 s_,Xs=S(()=>{"use strict";yt();s_={info:t=>console.log(t),warn:t=>console.warn(t)}});import{existsSync as Tu,readFileSync as Iu,writeFileSync as rk}from"node:fs";import{join as Cu}from"node:path";import{parseDocument as Pu}from"yaml";function nk(t){let e={};return t.branches.integration&&(e.integration=t.branches.integration),t.branches.stable!==void 0&&(e.stable=t.branches.stable),t.branches.release_pattern!==void 0&&(e.release_pattern=t.branches.release_pattern),{flow:t.flow,branches:e}}function ok(t){let{errors:e}=cn(t);if(e.length>0)throw new Error(`invalid git config: ${e.join("; ")}`)}async function ik(t,e){let r=nk(e);ok(r);let n=Cu(t,"project.yaml");if(!Tu(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=Pu(Iu(n,"utf-8"));o.set("git",r),rk(n,o.toString())}async function sk(t,e,r){let n=nk(r);ok(n);let o=Cu(t,"project.yaml");if(!Tu(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Pu(Iu(o,"utf-8"));Xi(i,e).set("git",n),rk(o,i.toString())}function ak(t){let e=Cu(t,"project.yaml");if(!Tu(e))return null;try{let r=Pu(Iu(e,"utf-8")).toJS();return c_(r?.git)}catch{return null}}function c_(t){if(!t||typeof t!="object")return null;let e=t,r=e.flow;if(r!=="simple"&&r!=="gitflow"&&r!=="release")return null;let n=e.branches;if(!n||typeof n!="object")return null;let o=n,i=o.integration;if(typeof i!="string"||!i)return null;let s={flow:r,branches:{integration:i}};return typeof o.stable=="string"&&(s.branches.stable=o.stable),typeof o.release_pattern=="string"&&(s.branches.release_pattern=o.release_pattern),s}var ck=S(()=>{"use strict";D();Ji()});import{confirm as l_,isCancel as u_}from"@clack/prompts";async function Js(t){let e=yo(t.facts),r=t.confirm??d_,n=t.log??(()=>{}),o=t.readProject??ak,i=t.writeProject??ik,s=t.writeOverride??sk;if(!t.contextDir)return e.flow!=="simple"&&n(`git-flow: detected ${Yn(e)} (no context repo to persist)`),{outcome:"no-context",detected:e};let a=t.contextDir,c=o(a);return c===null?e.flow==="simple"?(n("git-flow: simple (single branch)"),{outcome:"silent-simple",detected:e}):await r(`Detected git-flow: ${Yn(e)}. Use it?`)?(await i(a,e),n(`git-flow: ${Yn(e)} (project default)`),{outcome:"wrote-project",detected:e}):(n("git-flow: keeping simple (detection declined)"),{outcome:"declined",detected:e}):bc(e,c)?await r(`This repo's git-flow (${Yn(e)}) differs from the project (${Yn(c)}). Record a per-repo override?`)?(await s(a,t.repoName,e),n(`git-flow: ${Yn(e)} (per-repo override for "${t.repoName}")`),{outcome:"wrote-override",detected:e}):(n(`git-flow: using the project flow for "${t.repoName}" (override declined)`),{outcome:"declined",detected:e}):{outcome:"match",detected:e}}function Yn(t){if(t.flow==="simple")return"simple (single branch)";let e=[`integration=${t.branches.integration}`];return t.branches.stable&&e.push(`stable=${t.branches.stable}`),t.branches.release_pattern&&e.push(`release=${t.branches.release_pattern}`),`${t.flow} (${e.join(", ")})`}async function d_(t){let e=await l_({message:t,initialValue:!0});return u_(e)?!1:e===!0}var _u=S(()=>{"use strict";D();ck()});import{simpleGit as lk}from"simple-git";async function ri(t,e){let r=lk(t),n=null;try{n=(await r.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"")||null}catch{}!n&&e&&(n=await p_(e));let o=[];try{o=(await r.raw(["for-each-ref","--format=%(refname:short)","refs/remotes/origin"])).split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).map(s=>s.replace(/^origin\//,"")).filter(s=>s!=="HEAD"&&s!=="origin")}catch{o=[]}return{defaultBranch:n,branches:o}}async function p_(t){try{let e=await lk().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}var Au=S(()=>{"use strict"});import{simpleGit as f_}from"simple-git";async function uk(t,e,r){return t.host==="github"?m_(t,e,r):t.host==="gitlab"?h_(t,e,r):g_(t,e,r)}function ju(t){return new Error(`${t.owner}/${t.repoName} exists but is PUBLIC \u2014 a mirror holds the repository's full history and must be private. Make it private (or pick another name) and re-run`)}async function m_(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await tt(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw ju(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:o.data.ssh_url,created:!1}}let i=(await tt(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await xu(n,t.owner);if(!s&&!a)throw new Error(`"${t.owner}" is neither the token's account ("${i}") nor an organization it can see \u2014 nothing was created. Use a GitHub username or organization (not an email)`);r.info(`creating mirror ${t.owner}/${t.repoName} (github, ${a?"org":"user"})`);let c=await tt(n,"POST",a?`/orgs/${t.owner}/repos`:"/user/repos",{name:t.repoName,private:!0,auto_init:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"});if(!c.data)throw new Error(`GitHub: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url,created:!0}}async function dk(t,e,r){try{return t==="github"?(await tt(e,"GET","/user")).data?.login??null:t==="gitlab"?(await Ye(e,"GET","/user")).data?.username??null:r?(await At({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function h_(t,e,r){let n=e.gitlabToken;if(!n)throw new Error("GitLab PAT required to create a gitlab-hosted mirror");let o=encodeURIComponent(`${t.owner}/${t.repoName}`),i=await Ye(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw ju(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i.data.ssh_url_to_repo,created:!1}}let s={name:t.repoName,path:t.repoName,visibility:"private",initialize_with_readme:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"};if((await Ye(n,"GET","/user")).data?.username!==t.owner){let l=await Ye(n,"GET",`/namespaces/${encodeURIComponent(t.owner)}`);if(l.status===404||!l.data)throw new Error(`GitLab namespace "${t.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);s.namespace_id=l.data.id}r.info(`creating mirror ${t.owner}/${t.repoName} (gitlab)`);let c=await Ye(n,"POST","/projects",s);if(!c.data)throw new Error(`GitLab: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url_to_repo,created:!0}}async function g_(t,e,r){let n=e.bitbucket;if(!n)throw new Error("Bitbucket email + API token required to create a bitbucket-hosted mirror");let o=`/repositories/${t.owner}/${encodeURIComponent(t.repoName)}`,i=`git@bitbucket.org:${t.owner}/${t.repoName}.git`,s=await At(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw ju(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i,created:!1}}r.info(`creating mirror ${t.owner}/${t.repoName} (bitbucket)`);let a=await At(n,"POST",o,{json:{scm:"git",is_private:!0,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"}});if(a.status===404||!a.data?.slug)throw new Error(`Bitbucket cannot create ${t.owner}/${t.repoName} \u2014 check the workspace and that the credential may create repositories in it`);return{spec:t,sshUrl:i,created:!0}}async function pk(t,e,r){let n=f_(t);if((await n.raw(["rev-parse","--is-shallow-repository"])).trim()==="true")throw new Error("this clone is shallow \u2014 the mirror would be seeded with partial history. Run `git fetch --unshallow` first");if((await n.listRemote(["--heads",e])).trim().length>0)return r.info("mirror already has branches \u2014 leaving its content alone"),{seeded:!1};r.info("seeding mirror with the repository's branches and tags\u2026");let i=(await n.raw(["for-each-ref","refs/remotes/origin","--format=%(refname)"])).split(`
|
|
979
|
+
`).map(a=>a.trim()).filter(a=>a.length>0&&a!=="refs/remotes/origin/HEAD");if(i.length===0)throw new Error("the local clone has no origin branches to seed from");let s=i.map(a=>`${a}:refs/heads/${a.slice(20)}`);return await n.push([e,...s]),await n.push([e,"--tags"]),{seeded:!0}}function y_(t,e){let r=e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-");return`${t}-${r}-mirror`.replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function w_(t,e,r){return e.mirror?{host:e.mirror.host,owner:e.mirror.owner,repoName:e.mirror.repoName}:{host:r.host,owner:r.owner,repoName:y_(t,e.repoName)}}function fk(t,e,r){let n=new Map,o=[];for(let i of e){let s=w_(t,i,r),a=`${s.host}:${s.owner.toLowerCase()}/${s.repoName.toLowerCase()}`,c=n.get(a);if(c)throw new Error(`repositories "${c}" and "${i.name}" both map to the mirror ${s.owner}/${s.repoName} \u2014 mirroring them into one repository would merge their histories. Give one an explicit mirror name (mirror.repo in project.yaml) and re-run`);n.set(a,i.name),o.push({repo:i,spec:s})}return o}var mk=S(()=>{"use strict";Qo()});var bk={};Ge(bk,{ensureEmbeddedWorker:()=>Qs,spawnWorkerProcess:()=>ea,upCommand:()=>ta,workerChildEnv:()=>wk,workerStartArgs:()=>yk});import{spawn as gk}from"node:child_process";import{existsSync as hk}from"node:fs";import{homedir as b_,hostname as k_}from"node:os";import{join as Zs}from"node:path";async function v_(t,e,r){let n=Me(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${vt(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 cg(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 ${vt(e)} still holds its token.
|
|
980
|
+
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`),Kp(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function $_(t,e,r){let n=Me(e)!==null;if(!await v_(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 bs(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof W&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof W&&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 W?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 Ur({hub:t.hubUrl,token:o,name:r.name??`${k_()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function x_(t,e){let r=Me(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=We(r.sealPublicKey);if(!V(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Ri(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 Qs(t,e,r){await $_(t,e,r),x_(t.projectId,e)}function yk(t){return[...t?["--profile",t]:[],"worker","start"]}function wk(t){let e={...t};for(let r of Tc)delete e[r];return e}function ea(t){let e=gk(process.execPath,[t.entry,...yk(t.profile)],{stdio:["ignore","pipe","pipe"],env:wk(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
|
|
981
|
+
`))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function S_(t,e){let r=process.cwd(),n=Zs(r,Qe);if(fn(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(hk(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 ie(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 Nu(r);if(!Tp(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=V(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await js({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=Zs(b_(),".codepipe",e?Zs("profiles",e,"context-config"):"context-config");if(Di(c.contextDir,l,a),!hk(Zs(c.contextDir,"project.yaml"))){xn(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Eo(c.contextDir,It(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 ta(t){let{cfg:e,profile:r}=hn(t.profile);if(t.debug){let m=typeof t.debug=="string"&&t.debug.trim()?t.debug.trim():"agent-request";process.env.CODEPIPE_DEBUG=m,console.log(`[up] debug logging on (${m}) \u2192 ~/.codepipe/debug/${e.projectId}/`)}await S_(e,r),await Qs(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let g=w=>b=>{for(let v of b.toString("utf-8").split(`
|
|
982
|
+
`))v.length>0&&w.write(`${f} ${v}
|
|
983
|
+
`)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},i=(m,f)=>{let g=gk(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,m),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=ea({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
|
|
984
984
|
`)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=m=>{if(!l){l=!0,console.log(`
|
|
985
|
-
[up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(y=>{f.on("exit",(w,h)=>y({name:m,code:w??(h?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 ta=S(()=>{"use strict";ut();Gn();We();Ht();zl();jr();Ne();pe();bt();ri()});import{existsSync as Hr,mkdirSync as kk,readFileSync as ra,readdirSync as $_,writeFileSync as vk}from"node:fs";import{join as Oe,resolve as $k}from"node:path";import{setTimeout as Nu}from"node:timers/promises";import{cancel as xk,confirm as ni,intro as Sk,isCancel as Mu,log as P,multiselect as x_,outro as Ou,password as oi,select as pt,spinner as Du,text as we}from"@clack/prompts";import{simpleGit as qn}from"simple-git";function fe(t){xk(t),process.exit(1)}function ye(t){return Mu(t)&&fe("aborted"),t}function ce(t){return Mu(t)&&fe("aborted"),typeof t=="string"?t:""}async function Ek(t={}){Sk("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Gb();let r=Fb(e),n,o=!1;r&&Object.keys(r.answers).length>0?ye(await ni({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 Hn(e,r),o=!0):(Eu(e),n=new Hn(e)):n=new Hn(e);let i=t.force===!0?null:await ju(e),s=await n.ask("target",async()=>ye(await pt({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??(t.force===!0?null:await E_(e,n)),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||Rk(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ce(await we({message:"HUB URL",placeholder:ht,initialValue:Q("HUB_URL")??ht,validate:$=>$.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Yn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Vn(c,l)),d=null;s==="farm"&&(d=await S_(c,u));let m=a?I_(a.parsed.repoName):"",f=await n.ask("projectId",async()=>ce(await we({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:$=>Xt.test($.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>ce(await we({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()),w=await n.ask("language",()=>U_()),h=await n.ask("automationLevel",async()=>ye(await pt({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"}))),x=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>ye(await pt({message:"how much access should CodePipe have to your repositories?",options:[{value:"no",label:"read and write \u2014 branches and pull requests go into your repositories"},{value:"yes",label:"read only \u2014 CodePipe mirrors them and works in the mirrors",hint:"a mirror is a full copy of the history, in the account you choose next"}],initialValue:"no"}))))==="yes";x&&P.message("read-only token tip: if you want CodePipe to review pull requests people open in your repositories, the token also needs PR-comment permission (GitHub: Pull requests write; Bitbucket: pullrequest:write). Code stays read-only either way.");let b=await n.ask("trackerProvider",async()=>ye(await pt({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"}))),R=b==="internal",E=null,v,C=!0;if(R){let $,I=Du();I.start("checking task-key prefixes on your account\u2026");try{$=await cg(c,u,{excludeProjectId:f}),I.stop("prefixes checked")}catch{I.stop("could not reach the HUB",1),fe("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 V=vc(kc(y),$);v=await n.ask("trackerPrefix",async()=>ce(await we({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:V,initialValue:V,validate:me=>{let mt=me.trim();if(!Rr.test(mt))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if($.has(mt.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else E=await n.ask("youtrack",()=>Lk()),v=await n.ask("youtrackProjectKey",async()=>ce(await we({message:"YouTrack project key",placeholder:"DEV",validate:$=>$.trim().length>0?void 0:"required"})).trim()),C=await n.ask("youtrackWrites",async()=>ye(await ni({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let A=n.get("tokens")??{},G=()=>n.set("tokens",A),Y=await n.ask("repos",()=>j_(A,l,a,{onCred:G,initial:n.get("reposPartial")??[],onProgress:$=>n.set("reposPartial",$)}));n.delete("reposPartial");let _=null,g="",U="";if(x){let $=ye(await n.ask("mirrorHost",async()=>ye(await pt({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(ie=>({value:ie,label:ie===Y[0]?.host?`${ie} (same as your repositories)`:ie})),initialValue:Y[0]?.host??"github"}))));g=ce(await n.ask("mirrorToken",async()=>ye(await oi({message:`token that may CREATE and PUSH repositories on ${$}`})))).trim(),$==="bitbucket"&&(U=ce(await n.ask("mirrorEmail",async()=>ye(await we({message:"Atlassian account email for that token",...A.bitbucket?.email?{placeholder:A.bitbucket.email,defaultValue:A.bitbucket.email}:{}})))).trim());let I=await uk($,g,U||void 0),V=$==="bitbucket"?"workspace slug":"username or organization (not an email)",mt=ce(await n.ask("mirrorOwnerLogin",async()=>ye(await we({message:`account for the mirrors \u2014 ${$} ${V}`,...I?{placeholder:I,defaultValue:I}:{},validate:ie=>{let re=(ie??"").trim();if(!re&&!I)return"required";if(re.includes("@"))return`that looks like an email \u2014 a ${$} ${V} is expected`;if(/\s/.test(re))return"no spaces"}})))).trim()||I||"";if(!mt||mt.includes("@")){xk("mirrors need a host account to live in (a username/organization, not an email)");return}_={host:$,owner:mt}}let O=await N_(await n.ask("contextRepo",()=>jk(f,Y,A,l,_??void 0)),f,Y,A,l,G,$=>n.set("contextRepo",$),_??void 0),{spec:H,mode:X}=O,ue;R||(P.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),ue=await n.ask("assigneeLogin",async()=>ce(await we({message:"your YouTrack login (the assignee value)",...E?.login?{initialValue:E.login}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()));let Et=await n.ask("llmProvider",async()=>{for(;;){if(ye(await pt({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.")}}),ft=Et==="claude"?await n.ask("claudeToken",()=>_b(Pb("claude"),{farm:s==="farm"})):"",Re;if(ft){let $=await _f(ft);if($){let I=Ba($);I&&(Re=I,P.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${I} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let Ae={projectId:f,name:y,automationLevel:h,repos:Y,trackerProvider:b,youtrackProjectKey:v,language:w};P.step(`${X==="attach"?"attaching to":"provisioning"} Context Repo ${H.owner}/${H.name} (${H.host})\u2026`);let Le;try{Le=await Kn(Ae,H,{...Nk(A),youtrackWrites:C,...E?{trackerUrl:E.url}:{},mode:X,log:{info:$=>P.message($),warn:$=>P.warn($)}})}catch($){fe(`Context Repo provisioning failed: ${$ instanceof Error?$.message:String($)}`)}Ae.contextRepo=Le,P.success(`Context Repo ready: ${Le.owner}/${Le.name}@${Le.branch}`),P.step(`registering project on ${c}\u2026`);let Fe;try{Fe=await cr(c,u,Ae)}catch($){if($ instanceof K&&$.status===409){P.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{Fe=await se(c,u,f)}catch(I){throw I instanceof K&&fe(`HUB \u2192 ${I.status} ${I.message}`),I}}else if($ instanceof K&&$.status===401)n.delete("cliToken"),fe("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if($ instanceof K)fe(`HUB \u2192 ${$.status} ${$.message}`);else throw $}let M=Fe.contextRepo??Le;P.success(`project ${Fe.projectId} ready (${Fe.provisioningStatus})`);let B=E?{url:E.url,token:E.token}:void 0;if(s==="farm"){let $=d,I={...A,...ft?{claude:{oauthToken:ft}}:{},...B?{youtrack:B}:{}},V=A.github?.token;if(M.host==="github"&&V)try{let re=ey(`devpipe-${f}`);await ty(M,V,re.publicKey,`devpipe-${f}`),I.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 me={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:I,contextRepo:M,projectConfig:_t(Ae,C,E?.url,ue||void 0,Et,Re)},mt=Wt($.farm.publicKey,JSON.stringify(me));P.step(`handing project ${f} to farm ${$.farm.name}\u2026`);let ie;try{ie=await ws(c,u,$.farm.farmId,{projectId:f,sealedBundle:mt})}catch(re){throw re instanceof K&&fe(re.status===409?`farm ${$.farm.name} is offline \u2014 start it and re-run.`:re.status===504?`farm ${$.farm.name} did not respond in time.`:`HUB \u2192 ${re.status} ${re.message}`),re}ie.ok||fe(`farm rejected provisioning: ${ie.error??"unknown error"}`),await Lu(c,u,f,M,V,Fe.repos,null,A),n.clear(),Ou(`done. project ${f} is now hosted on farm ${$.farm.name} (daemon ${ie.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Ok(A),await Pk(e,M.cloneUrl,M.branch),Ak(e);try{$n(Oe(e,et),e,{info:$=>P.message($),warn:$=>P.warn($)})}catch($){P.warn(`skills materialize failed \u2014 ${$ instanceof Error?$.message:String($)}`)}a&&await P_(e);{let $=Oe(e,et);vn($);let I=_t(Ae,C,E?.url,ue||void 0,Et,Re),V=So($,I);V.length>0&&P.success(`local project config \u2192 .codepipe/{${V.join(", ")}}`),or(f,I,{info:me=>P.message(me),warn:me=>P.warn(me)})}await _k(e,Fe.repos),await A_(e,Fe.repos);let L=!1;if(x&&_&&(L=await __(e,Oe(e,et),f,Fe.repos,{host:_.host,owner:_.owner,token:g,...U?{email:U}:{}}),L)){let $=Oe(e,et);or(f,{projectYaml:ra(Oe($,"project.yaml"),"utf-8"),regimenYaml:ra(Oe($,"regimen.yaml"),"utf-8")},{info:I=>P.message(I),warn:I=>P.warn(I)})}let ee={hubUrl:c,cliToken:u,projectId:f,...A,...ft?{claude:{oauthToken:ft}}:{},...B?{youtrack:B}:{},...L?{mirrorWrite:{token:g,host:_.host,...U?{email:U}:{}}}:{}};ae(ee),Gt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),P.success(`secrets \u2192 ${Ct(f)}`),await Lu(c,u,f,M,A.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,Fe.repos,e,A),n.clear();let F=`${c}/?project=${encodeURIComponent(f)}`;Ar(F),Ou(`done. your project on the dashboard (sign in there to work with it):
|
|
986
|
-
${
|
|
987
|
-
starting codepipe up \u2014 the CLI daemon and an agent worker, with their logs on screen. Ctrl+C to stop (restart anytime with \`codepipe up\` from this folder).`);let{upCommand:
|
|
985
|
+
[up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} 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:m,child:f})=>new Promise(g=>{f.on("exit",(w,b)=>g({name:m,code:w??(b?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 ra=S(()=>{"use strict";ut();Hn();He();Wt();Xl();Nr();Ae();de();yt();ni()});import{existsSync as Wr,mkdirSync as vk,readFileSync as na,readdirSync as E_,writeFileSync as $k}from"node:fs";import{join as je,resolve as xk}from"node:path";import{setTimeout as Ou}from"node:timers/promises";import{cancel as Sk,confirm as oi,intro as Ek,isCancel as Du,log as P,multiselect as R_,outro as Lu,password as ii,select as pt,spinner as Uu,text as ge}from"@clack/prompts";import{simpleGit as Vn}from"simple-git";function pe(t){Sk(t),process.exit(1)}function he(t){return Du(t)&&pe("aborted"),t}function ce(t){return Du(t)&&pe("aborted"),typeof t=="string"?t:""}async function Rk(t={}){Ek("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Kb();let r=Gb(e),n,o=!1;r&&Object.keys(r.answers).length>0?he(await oi({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 qn(e,r),o=!0):(Ru(e),n=new qn(e)):n=new qn(e);let i=t.force===!0?null:await Nu(e),s=await n.ask("target",async()=>he(await pt({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??(t.force===!0?null:await I_(e,n)),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||Ik(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ce(await ge({message:"HUB URL",placeholder:ft,initialValue:Q("HUB_URL")??ft,validate:T=>T.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>zn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Xn(c,l)),d=null;s==="farm"&&(d=await T_(c,u));let m=a?__(a.parsed.repoName):"",f=await n.ask("projectId",async()=>ce(await ge({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:T=>Jt.test(T.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>ce(await ge({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),w=await n.ask("language",()=>G_()),b=await n.ask("automationLevel",async()=>he(await pt({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"}))),y=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>he(await pt({message:"how much access should CodePipe have to your repositories?",options:[{value:"no",label:"read and write \u2014 branches and pull requests go into your repositories"},{value:"yes",label:"read only \u2014 CodePipe mirrors them and works in the mirrors",hint:"a mirror is a full copy of the history, in the account you choose next"}],initialValue:"no"}))))==="yes";y&&P.message("read-only token tip: if you want CodePipe to review pull requests people open in your repositories, the token also needs PR-comment permission (GitHub: Pull requests write; Bitbucket: pullrequest:write). Code stays read-only either way.");let k=await n.ask("trackerProvider",async()=>he(await pt({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"}))),C=k==="internal",E=null,$,_=!0;if(C){let T,R=Uu();R.start("checking task-key prefixes on your account\u2026");try{T=await lg(c,u,{excludeProjectId:f}),R.stop("prefixes checked")}catch{R.stop("could not reach the HUB",1),pe("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 x=$c(vc(g),T);$=await n.ask("trackerPrefix",async()=>ce(await ge({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:x,initialValue:x,validate:I=>{let X=I.trim();if(!Ir.test(X))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(T.has(X.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else E=await n.ask("youtrack",()=>Mk()),$=await n.ask("youtrackProjectKey",async()=>ce(await ge({message:"YouTrack project key",placeholder:"DEV",validate:T=>T.trim().length>0?void 0:"required"})).trim()),_=await n.ask("youtrackWrites",async()=>he(await oi({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let j=n.get("tokens")??{},B=()=>n.set("tokens",j),K=await n.ask("repos",()=>L_(j,l,a,{onCred:B,initial:n.get("reposPartial")??[],onProgress:T=>n.set("reposPartial",T)}));n.delete("reposPartial");let A=null,h="",F="";if(y){let T=he(await n.ask("mirrorHost",async()=>he(await pt({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(H=>({value:H,label:H===K[0]?.host?`${H} (same as your repositories)`:H})),initialValue:K[0]?.host??"github"}))));h=ce(await n.ask("mirrorToken",async()=>he(await ii({message:`token that may CREATE and PUSH repositories on ${T}`})))).trim(),T==="bitbucket"&&(F=ce(await n.ask("mirrorEmail",async()=>he(await ge({message:"Atlassian account email for that token",...j.bitbucket?.email?{placeholder:j.bitbucket.email,defaultValue:j.bitbucket.email}:{}})))).trim());let R=await dk(T,h,F||void 0),x=T==="bitbucket"?"workspace slug":"username or organization (not an email)",X=ce(await n.ask("mirrorOwnerLogin",async()=>he(await ge({message:`account for the mirrors \u2014 ${T} ${x}`,...R?{placeholder:R,defaultValue:R}:{},validate:H=>{let re=(H??"").trim();if(!re&&!R)return"required";if(re.includes("@"))return`that looks like an email \u2014 a ${T} ${x} is expected`;if(/\s/.test(re))return"no spaces"}})))).trim()||R||"";if(!X||X.includes("@")){Sk("mirrors need a host account to live in (a username/organization, not an email)");return}A={host:T,owner:X}}let L=await M_(await n.ask("contextRepo",()=>Nk(f,K,j,l,A??void 0)),f,K,j,l,B,T=>n.set("contextRepo",T),A??void 0),{spec:q,mode:ee}=L,se;C||(P.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),se=await n.ask("assigneeLogin",async()=>ce(await ge({message:"your YouTrack login (the assignee value)",...E?.login?{initialValue:E.login}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()));let Nt=await n.ask("llmProvider",async()=>{for(;;){if(he(await pt({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.")}}),Be=Nt==="claude"?await n.ask("claudeToken",()=>Ab(_b("claude"),{farm:s==="farm"})):"",Ne;if(Be){let T=await Af(Be);if(T){let R=Fa(T);R&&(Ne=R,P.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${R} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let Ce={projectId:f,name:g,automationLevel:b,repos:K,trackerProvider:k,youtrackProjectKey:$,language:w};P.step(`${ee==="attach"?"attaching to":"provisioning"} Context Repo ${q.owner}/${q.name} (${q.host})\u2026`);let Oe;try{Oe=await Wn(Ce,q,{...Ok(j),youtrackWrites:_,...E?{trackerUrl:E.url}:{},mode:ee,log:{info:T=>P.message(T),warn:T=>P.warn(T)}})}catch(T){pe(`Context Repo provisioning failed: ${T instanceof Error?T.message:String(T)}`)}Ce.contextRepo=Oe,P.success(`Context Repo ready: ${Oe.owner}/${Oe.name}@${Oe.branch}`),P.step(`registering project on ${c}\u2026`);let Ee;try{Ee=await lr(c,u,Ce)}catch(T){if(T instanceof W&&T.status===409){P.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{Ee=await ie(c,u,f)}catch(R){throw R instanceof W&&pe(`HUB \u2192 ${R.status} ${R.message}`),R}}else if(T instanceof W&&T.status===401)n.delete("cliToken"),pe("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(T instanceof W)pe(`HUB \u2192 ${T.status} ${T.message}`);else throw T}let rt=Ee.contextRepo??Oe;P.success(`project ${Ee.projectId} ready (${Ee.provisioningStatus})`);let Ot=E?{url:E.url,token:E.token}:void 0;if(s==="farm"){let T=d,R={...j,...Be?{claude:{oauthToken:Be}}:{},...Ot?{youtrack:Ot}:{}},x=j.github?.token;if(rt.host==="github"&&x)try{let re=ty(`devpipe-${f}`);await ry(rt,x,re.publicKey,`devpipe-${f}`),R.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 I={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:R,contextRepo:rt,projectConfig:It(Ce,_,E?.url,se||void 0,Nt,Ne)},X=qt(T.farm.publicKey,JSON.stringify(I));P.step(`handing project ${f} to farm ${T.farm.name}\u2026`);let H;try{H=await ws(c,u,T.farm.farmId,{projectId:f,sealedBundle:X})}catch(re){throw re instanceof W&&pe(re.status===409?`farm ${T.farm.name} is offline \u2014 start it and re-run.`:re.status===504?`farm ${T.farm.name} did not respond in time.`:`HUB \u2192 ${re.status} ${re.message}`),re}H.ok||pe(`farm rejected provisioning: ${H.error??"unknown error"}`),await Mu(c,u,f,rt,x,Ee.repos,null,j),n.clear(),Lu(`done. project ${f} is now hosted on farm ${T.farm.name} (daemon ${H.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Lk(j),await _k(e,rt.cloneUrl,rt.branch),jk(e);try{Sn(je(e,Qe),e,{info:T=>P.message(T),warn:T=>P.warn(T)})}catch(T){P.warn(`skills materialize failed \u2014 ${T instanceof Error?T.message:String(T)}`)}a&&await j_(e);{let T=je(e,Qe);xn(T);let R=It(Ce,_,E?.url,se||void 0,Nt,Ne),x=Eo(T,R);x.length>0&&P.success(`local project config \u2192 .codepipe/{${x.join(", ")}}`),ir(f,R,{info:I=>P.message(I),warn:I=>P.warn(I)})}await Ak(e,Ee.repos),await O_(e,Ee.repos);let Lt=!1;if(y&&A&&(Lt=await N_(e,je(e,Qe),f,Ee.repos,{host:A.host,owner:A.owner,token:h,...F?{email:F}:{}}),Lt)){let T=je(e,Qe);ir(f,{projectYaml:na(je(T,"project.yaml"),"utf-8"),regimenYaml:na(je(T,"regimen.yaml"),"utf-8")},{info:R=>P.message(R),warn:R=>P.warn(R)})}let U={hubUrl:c,cliToken:u,projectId:f,...j,...Be?{claude:{oauthToken:Be}}:{},...Ot?{youtrack:Ot}:{},...Lt?{mirrorWrite:{token:h,host:A.host,...F?{email:F}:{}}}:{}};ae(U),Gt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),P.success(`secrets \u2192 ${Rt(f)}`),await Mu(c,u,f,rt,j.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,Ee.repos,e,j),n.clear();let G=`${c}/?project=${encodeURIComponent(f)}`;jr(G),Lu(`done. your project on the dashboard (sign in there to work with it):
|
|
986
|
+
${G}
|
|
987
|
+
starting codepipe up \u2014 the CLI daemon and an agent worker, with their logs on screen. Ctrl+C to stop (restart anytime with \`codepipe up\` from this folder).`);let{upCommand:M}=await Promise.resolve().then(()=>(ra(),bk));await M({profile:void 0})}async function Mu(t,e,r,n,o,i=[],s=null,a={}){let c=await qb(n,o),l=!1;if(!c)try{l=await zb(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Wb({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await R_({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Du(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let m=Pe(s);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(Ho(),Ps)),g=await f(m,void 0,{onLog:w=>P.message(w)});P.success(`project map ready: ${g.events} task events mined from history`)}catch(m){P.warn(`could not build the project map: ${m instanceof Error?m.message:String(m)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:m}=await Ko(t,e,r,{reindex:!1,backfill:!0});P.success(`retrospective architecture analysis queued (job ${m}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(m){P.warn(`could not start the retrospective analysis: ${m instanceof Error?m.message:String(m)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:m}=await Ko(t,e,r,{reindex:u.reindex});P.success(`indexing queued (job ${m}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(m){P.warn(`could not start indexing: ${m instanceof Error?m.message:String(m)}. You can retry later \u2014 registration is not affected.`)}}async function T_(t,e){let r;try{r=await ig(t,e)}catch(c){throw c instanceof W&&pe(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&pe("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=he(await pt({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=gs(i.farmId,i.publicKey)}catch(c){pe(c instanceof Error?c.message:String(c))}return he(await oi({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
988
988
|
${s}
|
|
989
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||
|
|
989
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||pe("farm fingerprint not confirmed \u2014 aborting."),hs(i.farmId,s),{farm:i,fingerprint:s}}async function Tk(t){Ek(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Ik(e,t.force===!0);let r=ce(await ge({message:"HUB URL",initialValue:Q("HUB_URL")??ft,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await zn(),{cliToken:o,accountEmail:i}=await Xn(r,n);P.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await ie(r,o,t.projectId)}catch(d){throw d instanceof W&&pe(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||pe(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Mk(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let m=s.repos.find(f=>f.host===d);await oa(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}Lk(l),await _k(e,s.contextRepo.cloneUrl,s.contextRepo.branch),jk(e);{let d=je(e,Qe);xn(d);let m={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},f=It(m,!0,c?.url,void 0,s.llmProvider??Je),g=Eo(d,f);g.length>0&&P.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),ir(t.projectId,f,{info:w=>P.message(w),warn:w=>P.warn(w)})}await Ak(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ae(p),Gt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),P.success(`secrets \u2192 ${Rt(t.projectId)}`),await Mu(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),Lu("done.")}function Ik(t,e){if(!Wr(t)){vk(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=E_(t).filter(o=>!r.has(o));n.length!==0&&(e||pe(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Nu(t){if(!Wr(je(t,".git")))return null;try{let e=Ve(await Ck(t));return e?{parsed:e,defaultBranch:await Pk(t)}:null}catch{return null}}async function Ck(t){try{return(await Vn(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function I_(t,e){if(!Wr(je(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await Ck(t);return P.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),ce(await ge({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:i=>!i||!i.trim()||Ve(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?Ve(r):null;return n?{parsed:n,defaultBranch:await Pk(t)}:null}async function C_(t){try{let e=await Vn().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}async function P_(t,e){try{return(await Vn().listRemote([t,`refs/heads/${e}`])).trim().length>0}catch{return!0}}async function Pk(t){let e=Vn(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 __(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Jt.test(e)?e:""}function A_(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function j_(t){let e=je(t,".gitignore"),r=Wr(e)?na(e,"utf-8"):"";if(A_(r))return;if(!he(await oi({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(`
|
|
990
990
|
`)?"":`
|
|
991
|
-
|
|
991
|
+
`;$k(e,r+o+`
|
|
992
992
|
# codepipe workspace (added by \`codepipe init\`)
|
|
993
993
|
.codepipe/
|
|
994
|
-
`),P.success(`.codepipe/ added to ${
|
|
994
|
+
`),P.success(`.codepipe/ added to ${xk(e)}`)}async function zn(){let t="";try{t=(await Vn().raw(["config","--global","user.email"])||"").trim()}catch{}return ce(await ge({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Xn(t,e){P.step(`connecting account ${e}`);let r;try{r=await ug(t,e)}catch(s){throw s instanceof Go&&pe(`${e} is not authorized on this HUB yet.
|
|
995
995
|
Sign up at ${t} (registration form on the login screen),
|
|
996
996
|
wait for the operator to approve it by email, then re-run
|
|
997
|
-
\`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&&(
|
|
997
|
+
\`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&&(jr(r.authorizeUrl),P.message(`a browser tab was opened to confirm this CLI:
|
|
998
998
|
${r.authorizeUrl}
|
|
999
999
|
`+(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
|
|
1000
|
-
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
|
|
1001
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
1000
|
+
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 dg(t,r.requestId)}catch(a){P.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Ou(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"&&pe("the HUB rejected this account"),s.status==="expired"&&pe("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
|
|
1001
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Ou(5e3);continue}await Ou(2e3)}pe("bootstrap timed out")}async function _k(t,e,r){let n=je(t,Qe);if(Wr(je(n,".git"))){P.message(`${n} already cloned \u2014 skipping`);return}Wr(n)&&pe(`${n} exists but is not a git repo \u2014 remove it and re-run`),vk(n,{recursive:!0}),P.step(`cloning Context Repo \u2192 ${n}`);try{await Vn().clone(e,n,["--branch",r]),P.success(`cloned ${e}`)}catch(o){pe(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function N_(t,e,r,n,o){if(n.length===0)return!1;P.step(`setting up ${n.length} mirror(s) \u2014 your repositories stay read-only`);let i={info:l=>P.message(` ${l}`),warn:l=>P.warn(` ${l}`)},s={...o.host==="github"?{githubToken:o.token}:{},...o.host==="gitlab"?{gitlabToken:o.token}:{},...o.host==="bitbucket"&&o.email?{bitbucket:{email:o.email,apiToken:o.token}}:{}},a;try{a=fk(r,n,o)}catch(l){return P.warn(` ${l instanceof Error?l.message:String(l)}`),P.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}let c=[];for(let{repo:l,spec:u}of a)try{let p=await uk(u,s,i);await pk(je(t,l.mountAs??l.name),p.sshUrl,i),c.push({repoName:l.name,spec:u})}catch(p){return P.warn(` ${l.name}: mirror not set up \u2014 ${p instanceof Error?p.message:String(p)}`),P.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}for(let l of c)Zm(e,l.repoName,l.spec);for(let l of c)P.success(` ${l.repoName} \u2192 ${l.spec.owner}/${l.spec.repoName}`);return!0}async function Ak(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 ti(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}`:""}`)}async function O_(t,e){let r=je(t,Qe);for(let n of e){let o=je(t,n.mountAs??n.name),i;try{i=await ri(o)}catch(s){P.warn(`git-flow detection skipped for "${n.name}": ${s instanceof Error?s.message:String(s)}`);continue}try{await Js({contextDir:r,repoName:n.name,facts:i,log:s=>P.message(s)})}catch(s){throw P.error(`git-flow for "${n.name}" was NOT saved: ${s instanceof Error?s.message:String(s)}`),s}}}function jk(t){let e=je(t,Qe,".gitignore"),r="";if(Wr(e)&&(r=na(e,"utf-8")),kk.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
|
|
1002
1002
|
`)||r.length===0?"":`
|
|
1003
|
-
`,i=
|
|
1003
|
+
`,i=kk.join(`
|
|
1004
1004
|
`)+`
|
|
1005
|
-
|
|
1006
|
-
`:"")+i),P.message(`appended runtime entries to ${
|
|
1005
|
+
`;$k(e,r+o+(r?`
|
|
1006
|
+
`:"")+i),P.message(`appended runtime entries to ${xk(e)}`)}async function L_(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await oa(s.host,t,s.owner,e,s.repoName),i?.(),o.push({name:s.repoName,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:a,mountAs:"."}),n.onProgress?.(o),P.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;he(await oi({message:o.length===0?"Add a project repository?":`Project repositories: ${o.map(f=>f.name).join(", ")}. Add another one?`,initialValue:o.length===0}));){let a=ce(await ge({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||Ve(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=Ve(a);P.message(`${c.host}: ${c.owner}/${c.repoName}`),await oa(c.host,t,c.owner,e,c.repoName),i?.();let l=ce(await ge({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=await C_(a),p="";for(;p=ce(await ge({message:"default branch",placeholder:u??"main",...u?{initialValue:u}:{}})).trim(),!(!p||!u||p===u||await P_(a,p));)P.warn(`branch "${p}" does not exist in ${c.owner}/${c.repoName} (the repository's default is "${u}")`);let d=ce(await ge({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),m={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(m.defaultBranch=p),d&&d!==l&&(m.mountAs=d),o.push(m),n.onProgress?.(o)}return o}async function Nk(t,e,r,n,o){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 i=he(await pt({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"}));i==="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 s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=ce(await ge({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:Et(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!Ve(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=Ve(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await D_(),u=ce(await ge({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=ce(await ge({message:"Context Repo name",placeholder:Et(t),initialValue:Et(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function Ok(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??yn()}}async function M_(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await oa(l.host,n,l.owner,o),i?.();let p=Uu();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await Nb(l,Ok(n),{explain:u==="attach"});if(d.found===!0)return p.stop(`${l.owner}/${l.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),c;if(d.found==="unknown")return p.stop(`could not check ${l.owner}/${l.name} (${d.detail}) \u2014 continuing`,1),c;if(u==="create")return p.stop(`${l.owner}/${l.name} not found \u2014 will be created`),c;p.stop(d.detail,1);let m=he(await pt({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(m==="abort"&&pe("aborted"),m==="create")return c={spec:l,mode:"create"},s(c),c;c=await Nk(e,r,n,o,a),s(c)}}async function D_(){return he(await pt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function ia(t,e){let r=Uu();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 Lk(t){_o(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Ao(t.gitlab?.token??process.env.GITLAB_TOKEN),jo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function oa(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await U_(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 B_(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 F_();i?e.gitlab=i:P.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function U_(t){for(;;){let e=ce(await ii({message:`GitHub PAT \u2014 blank to skip
|
|
1007
1007
|
classic PAT: 'repo' + 'workflow'
|
|
1008
1008
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
1009
1009
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
1010
|
-
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await
|
|
1010
|
+
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await ia("GitHub",()=>Zt(e,t?{owner:t}:void 0)))return{token:e};P.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function B_(t,e,r){for(P.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
1011
1011
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
1012
1012
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
|
|
1013
1013
|
read:repository:bitbucket + write:repository:bitbucket +
|
|
1014
1014
|
read:pullrequest:bitbucket + write:pullrequest:bitbucket
|
|
1015
1015
|
\u2014 write scopes do NOT include read: pick BOTH scopes of each pair
|
|
1016
1016
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
1017
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let n=ce(await
|
|
1018
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
1019
|
-
`),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
|
|
1020
|
-
`),a=s.findIndex(
|
|
1021
|
-
`).replace(/^\n+/,""),w=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",
|
|
1017
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let n=ce(await ge({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=ce(await ii({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 ia("Bitbucket",async()=>{let i=await Qt(n,o,t);if(t&&r){let s=await ji(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 F_(){for(;;){let t=ce(await ii({message:`GitLab PAT \u2014 blank to skip
|
|
1018
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await ia("GitLab",()=>er(t))){let e=await Qp(t);return e&&P.warn(e),{token:t}}P.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function G_(){let t="__other__",e=async()=>ce(await ge({message:"language name (in English, e.g. Ukrainian)",validate:s=>{let a=s.trim();if(a.length===0)return"required";if(a.length>40)return`\u2264 ${40} chars`}})).trim(),r=he(await pt({message:"project language",options:[...an.map(s=>({value:s,label:s==="English"?"English (default)":s})),{value:t,label:"other\u2026"}],initialValue:"English"})),n=r===t?await e():r;if(n==="English")return{primary:n,context:n,tasks:n,docs:n,code_comments:n,chat:me};let o=[{key:"context",label:"context documents (knowledge, ADRs, task artifacts)",initial:n},{key:"tasks",label:"tracker issues the agent drafts",initial:n},{key:"docs",label:"documentation in the project repos",initial:n},{key:"code_comments",label:"code comments",initial:n},{key:"chat",label:"chat with the agent",initial:me}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",me].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===me?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=he(await pt({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function Mk(){for(;;){let t=ce(await ge({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=ce(await ii({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await ia("YouTrack",()=>nr({baseUrl:t,token:e}))){let r=await mf({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}P.warn("re-enter the YouTrack URL / token.")}}var kk,ni=S(()=>{"use strict";Ke();D();ut();jb();Oi();He();Wt();Nr();kn();Qo();zl();Vs();Kt();Ar();Hb();Ae();Yb();Xb();_l();zi();de();Xs();Ji();_u();Au();mk();Gi();yt();kk=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});D();Ke();He();import{Command as VA}from"commander";He();de();async function Wp(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=wt(e);r&&!t.force&&(console.error(`already configured at ${mn(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Gt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...V(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ae(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${mn(e)}`)}Ic();He();import{homedir as Jl}from"node:os";import{join as Wo}from"node:path";Ke();D();import{existsSync as Zg,rmSync as fT}from"node:fs";import{join as Dr}from"node:path";import{simpleGit as mT}from"simple-git";import"ws";Ke();de();import{createHash as cx}from"node:crypto";import{existsSync as lx,readFileSync as ux}from"node:fs";import{homedir as dx,hostname as Cc}from"node:os";import{join as px}from"node:path";function zp(t){return cx("sha256").update(t).digest("hex").slice(0,12)}function fx(){let t=Q("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=px(dx(),".claude","credentials.json");if(!lx(e))return;let r=JSON.parse(ux(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 Xp(t){let e=fx(),r=Q("ACCOUNT_ID")?.trim(),n=Q("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=gn(t);return o?{accountId:`acct-${zp(o)}`,label:n||Cc(),...e?{email:e}:{}}:{accountId:`acct-${zp(`host:${Cc()}`)}`,label:n||Cc(),...e?{email:e}:{}}}Ke();kn();de();Kc();async function Lf(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")!=="1"){s("autologin_disabled");return}let a;try{a=await Gc(Ni())}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 Ht(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=V(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},ae(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()}}Ke();function Mf(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?Q("ORIGIN")==="farm"||Q("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Df(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}Oi();import{existsSync as Ux}from"node:fs";import{join as Bx}from"node:path";import{simpleGit as Fx}from"simple-git";async function Uf(t,e){if(!Ux(Bx(t,".git")))return{status:"skipped"};let r=Fx(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Gx(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 Gx(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Wc,readFileSync as Hf,readdirSync as Wx,watch as qx}from"node:fs";import{join as So}from"node:path";D();import{existsSync as Bf,readFileSync as Ff,readdirSync as Kx,statSync as Hx}from"node:fs";import{join as Hc}from"node:path";import{parse as Gf}from"yaml";function Li(t){let e=Hc(t,"actions"),r=[],n=[];if(!Bf(e))return{defs:r,errors:n};let o;try{o=Kx(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=Hc(e,s);try{if(!Hx(a).isFile())continue;let c=qa(s,Gf(Ff(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 Kf(t){let e={},r=Hc(t,"project.yaml");if(!Bf(r))return e;let n;try{n=Gf(Ff(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))!Ze.test(i)||Bt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var Mi=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,So(this.contextDir,"prompts"),So(this.contextDir,"actions")];for(let n of r)if(Wc(n))try{let o=qx(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=Li(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=So(this.contextDir,e);if(!Wc(r))return null;try{return Hf(r,"utf-8")}catch{return null}}readPrompts(){let e=So(this.contextDir,"prompts"),r={};if(!Wc(e))return r;let n;try{n=Wx(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Hf(So(e,o),"utf-8")}catch{}}return r}};ct();import{existsSync as Qc,readFileSync as Jf,readdirSync as iS}from"node:fs";import{join as Zf}from"node:path";import{simpleGit as sS}from"simple-git";var aS=/^(\d{4})-(.+)\.md$/,cS="0000-template.md";function lS(t){let e=t.split(`
|
|
1019
|
+
`),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 uS(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
1020
|
+
`),a=s.findIndex(b=>b.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,m=a>=0?a+1:0;for(let b=m;b<s.length;b++){let v=(s[b]??"").trim();if(v===""){m=b+1;continue}let y=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(v);if(!y)break;let k=(y[1]??"").trim().toLowerCase(),C=(y[2]??"").trim(),E=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(v);E&&(d=parseInt(E[1]??"",10)),k==="tasks"&&(p=C),l.has(k)||u.push(v),m=b+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(m).join(`
|
|
1021
|
+
`).replace(/^\n+/,""),w=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",g].join(`
|
|
1022
1022
|
`);return{content:w.endsWith(`
|
|
1023
1023
|
`)?w:w+`
|
|
1024
|
-
`,supersedes:d}}function
|
|
1024
|
+
`,supersedes:d}}function dS(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
|
|
1025
1025
|
|
|
1026
|
-
- **Status:** superseded by ADR-${r}`):n}function
|
|
1026
|
+
- **Status:** superseded by ADR-${r}`):n}function pS(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(`
|
|
1027
1027
|
`)+`
|
|
1028
|
-
`}async function
|
|
1029
|
-
`)}async function
|
|
1030
|
-
`,o.length>
|
|
1031
|
-
`))!==-1;)o(m,f.slice(0,w).replace(/\r$/,"")),f=f.slice(w+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),i(a?
|
|
1032
|
-
`)){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
|
|
1028
|
+
`}async function Qf(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await sS(t).pull(void 0,void 0,["--rebase"])}catch{}let i=w=>o==="staging"?`adr/DRAFT-${w}.md`:`tasks/${e}/adr/DRAFT-${w}.md`,s=[],a=[];for(let w of r){let b=Se(t,i(w));if(!Qc(b)){a.push(w);continue}s.push({slug:w,content:Jf(b,"utf-8")})}let c=Zf(t,"adr"),l=new Map;if(Qc(c))for(let w of iS(c)){let b=aS.exec(w);!b||w===cS||l.set(w,{num:parseInt(b[1]??"",10),slug:b[2]??"",content:Jf(Zf(c,w),"utf-8")})}let u=Math.max(0,...[...l.values()].map(w=>w.num))+1,p=new Map,d=[],m=[];for(let w of s){if([...l.entries()].find(([,E])=>E.slug===w.slug&&E.content.includes(e))){m.push(w.slug);continue}let v=u++,y=`${String(v).padStart(4,"0")}-${w.slug}.md`,{content:k,supersedes:C}=uS(w.content,v,w.slug,e,n);if(p.set(y,k),l.set(y,{num:v,slug:w.slug,content:k}),d.push(`adr/${y}`),C!==null){let E=[...l.keys()].find($=>$.startsWith(`${String(C).padStart(4,"0")}-`));if(E&&E!==y){let $=dS(p.get(E)??l.get(E).content,v);p.set(E,$),l.set(E,{...l.get(E),content:$})}}}let f=[];if(o==="staging")for(let w of s)Qc(Se(t,`adr/DRAFT-${w.slug}.md`))&&f.push({path:`adr/DRAFT-${w.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let w=[...l.entries()].map(([b,v])=>({num:v.num,file:b,header:lS(v.content)}));p.set("INDEX.md",pS(w))}for(let[w,b]of p.entries())f.push({path:`adr/${w}`,content:b});let g=d.length>0?`adr(${e}): promote ${s.map(w=>w.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Te(t,f,g),{promoted:d,skipped:m,missing:a}}ct();Gi();Wt();D();import{existsSync as rm,readFileSync as vS}from"node:fs";import{join as nm}from"node:path";function $S(t){for(let e of[ht,en]){let r=nm(t,e);if(rm(r))try{return wa(vS(r,"utf-8"))}catch{return 0}}return 0}function xS(t,e,r,n=6){let o=e<n,i=o?ba(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Ki(t,e){return xS(e,$S(t),r=>rm(nm(t,r)))}D();Kt();import{existsSync as hm,mkdirSync as JS,mkdtempSync as ZS,rmSync as gm,writeFileSync as ym}from"node:fs";import{tmpdir as QS}from"node:os";import{dirname as eE,join as Wi}from"node:path";import{simpleGit as nl}from"simple-git";Nr();function tE(t){return`codepipe/context-migration-v${t}`}function rE(t){let e=ka(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 \`${ht}\` 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(`
|
|
1029
|
+
`)}async function wm(t,e,r,n){let o=nl(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Ki(t,e);if(!i.outdated)return i;let s=tE(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 nE(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=_r(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:rE(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 nE(t,e,r,n,o,i,s){let a=nl(t),c=ZS(Wi(QS(),"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(Rn(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===ht)continue;let w=p.get(g);if(w==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let b=Wi(c,g);hm(b)||(JS(eE(b),{recursive:!0}),ym(b,w),d++)}ym(Wi(c,ht),ao(n.currentVersion)),d++;let m=Wi(c,en);hm(m)&&(gm(m,{force:!0}),d++);let f=nl(c);await f.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await f.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await f.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),gm(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as oE,readFileSync as iE,writeFileSync as sE}from"node:fs";import{homedir as aE}from"node:os";import{join as bm}from"node:path";import{parseDocument as cE}from"yaml";function lE(t,e,r){let n={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(n.default_branch=t.defaultBranch),e!==void 0&&(n.mirror=e),r!==void 0&&(n.git=r),n}function uE(t,e){let r=cE(t),n=new Map,o=new Map,i=r.toJS();for(let s of i?.repos??[]){if(!s||typeof s!="object")continue;let a=typeof s.name=="string"?s.name:String(s.repo??"");a&&(s.mirror!==void 0&&s.mirror!==null&&n.set(a,s.mirror),s.git!==void 0&&s.git!==null&&o.set(a,s.git))}return r.set("repos",e.map(s=>lE(s,n.get(s.name),o.get(s.name)))),r.toString()}function dE(t,e){let r=[bm(aE(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(bm(e,"project.yaml")),r}function Po(t,e,r){let n=[],o=[];for(let i of dE(t,r))if(oE(i))try{let s=iE(i,"utf-8"),a=uE(s,e);a!==s&&(sE(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}Cn();ut();de();function $E(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}),t.mirrorWrite?.token&&(r.mirrorWrite={token:t.mirrorWrite.token,...t.mirrorWrite.host?{host:t.mirrorWrite.host}:{}}),r}function Am(t,e,r,n){let o=$E(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=Ri(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=qt(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}ut();de();Kt();Ar();kn();zi();function Lm(t){let e=V(t);if(!e)return null;if(!e.sealKey){let r=Vi();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ae(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:We(e.sealKey.publicKey)}}async function Mm(t,e,r,n){let o;try{o=JSON.parse(Pn(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=V(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 Zt(o.token);return i.github={token:o.token},_n(i,()=>{process.env.GH_TOKEN=o.token,jm(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await er(o.token);return i.gitlab={token:o.token},_n(i,()=>{process.env.GITLAB_TOKEN=o.token,Nm(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 Qt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},_n(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Om(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 nr({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},_n(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 Ht(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},_n(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},_n(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 _n(t,e){ae(t),e()}D();D();import{spawn as xE}from"node:child_process";var SE=124,Dm=16*1024,Um=4e3;function EE(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Bt(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 Bm(t){let{def:e,onEvent:r}=t,n=EE(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
|
|
1030
|
+
`,o.length>Dm&&(o=o.slice(o.length-Dm))},s=(a,c)=>{let l=c.length>Um?c.slice(0,Um)+"\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 RE(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 RE(t,e,r,n,o){return new Promise(i=>{let s=xE("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Wa)*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=m=>{let f="";return{data:g=>{f+=g.toString("utf-8");let w;for(;(w=f.indexOf(`
|
|
1031
|
+
`))!==-1;)o(m,f.slice(0,w).replace(/\r$/,"")),f=f.slice(w+1)},flush:()=>{f.length>0&&o(m,f.replace(/\r$/,"")),f=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",m=>{clearTimeout(l),o("stderr",`spawn failed: ${m.message}`),i(127)}),s.on("close",(m,f)=>{clearTimeout(l),p.flush(),d.flush(),i(a?SE:m??(f?1:0))})})}ct();ct();import{existsSync as TE,readFileSync as IE,statSync as Fm}from"node:fs";var Gm=2*1024*1024;function CE(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Km(t,e){let r=Se(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!TE(r)||!Fm(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Fm(r);if(n>Gm)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Gm})`);let o=IE(r);return CE(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}de();D();import{existsSync as PE,readFileSync as _E,writeFileSync as AE}from"node:fs";import{join as jE}from"node:path";import{parseDocument as NE}from"yaml";async function Hm(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=ec(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=jE(t,o);if(!PE(s))throw new Error(`${o} not found in context repo (${t})`);let a=NE(_E(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);AE(s,a.toString()),n.push(o)}return{files:n}}Ji();import{existsSync as ul,readFileSync as dl,writeFileSync as OE}from"node:fs";import{join as Zi}from"node:path";import{parseDocument as pl}from"yaml";async function Qm(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=Zi(t,"project.yaml");if(!ul(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=pl(dl(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=Zi(t,"regimen.yaml");if(!ul(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=pl(dl(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)OE(Zi(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Qi(t){if(!t)return"Stage";try{let e=Zi(t,"project.yaml");if(!ul(e))return"Stage";let n=pl(dl(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Kt();qi();Cn();D();ct();import{existsSync as oR,readFileSync as iR}from"node:fs";import{join as Hh}from"node:path";import{simpleGit as Rl}from"simple-git";D();import{existsSync as eh,readFileSync as th,readdirSync as LE}from"node:fs";import{join as fl}from"node:path";import{simpleGit as ME}from"simple-git";function DE(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(`
|
|
1032
|
+
`)){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 UE(t,e){let r=fl(t,`tasks/${e}/annotations`);if(!eh(r))return[];let n=[];for(let o of LE(r).sort())if(o.endsWith(".md")){try{let i=DE(o,th(fl(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=Ca)break}return n}var BE=12;async function rh(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=ME(o),p=[];for(let d of UE(e,r)){if(d.repo!==n)continue;let m=fe("code",n,d.path);if(!a.has(m))continue;let f=l.get(m);if(!f)continue;let g=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,BE),w=xa(f),b=fl(e,w),v=p.find(_=>_.path===w),y=v?.content??(eh(b)?th(b,"utf-8"):null),k=`<!-- ${r}${g?`:${g}`:""} -->`;if(y?.includes(k))continue;let C=y??`---
|
|
1033
1033
|
entityId: ${f}
|
|
1034
1034
|
---
|
|
1035
1035
|
|
|
1036
1036
|
# Intent log
|
|
1037
1037
|
|
|
1038
1038
|
Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
|
|
1039
|
-
`,E=["",`## ${s} \u2014 ${r}`,
|
|
1040
|
-
`)
|
|
1041
|
-
`)){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
|
|
1042
|
-
`)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await
|
|
1043
|
-
`)}function
|
|
1044
|
-
`)){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=Tr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function
|
|
1039
|
+
`,E=["",`## ${s} \u2014 ${r}`,k,"",d.body,""].join(`
|
|
1040
|
+
`),$=C+E;v?v.content=$:p.push({path:w,content:$})}return p}bl();$l();rs();Sl();Oo();async function sR(t,e){let n=await Rl(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
|
|
1041
|
+
`)){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 aR(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>oR(Hh(t,i)));if(!n)return{};let o=Hh(t,n);try{let i=iR(o,"utf-8"),s=[...new Set(i.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:n,...s.length>0?{adr:s}:{}}}catch{return{solution:n}}}async function Wh(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Lr(e),a=Or([...s.ignore,...An]),c=await sR(r,i),l=(await Rl(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=kl(e,n),u&&(p=new Map(u.entities.filter(C=>C.status==="active").map(C=>[C.currentKey,C.entityId])))}catch{}let d=[];for(let C of c){if(a(C.path))continue;let E=fe("code",n,C.path),$=p.get(E);d.push({key:E,...$?{entityId:$}:{},churn:C.churn})}if(d.length===0)return{recorded:!1};let m=aR(e,o),f=es(e,o),g=f?.origin==="pipeline"?f.files.filter(C=>te(C.key)?.repo!==n):[],w=f?.origin==="pipeline"?f.commits:[],b={modelFormatVersion:2,taskKey:o,origin:"pipeline",...f?.title?{title:f.title}:{},...l?{date:l}:{},commits:[...new Set([...w,i])],files:[...g,...d],links:{...f?.origin==="pipeline"?f.links:{},...m}};b.links&&Object.keys(b.links).length===0&&delete b.links;let v=[...os(e).filter(C=>C.taskKey!==o),b],y=Dh(Uh(e),v,o,s.cochange.halfLifeDays),k=await rh({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(C=>C.key)),identity:u}).catch(()=>[]);await Te(e,[{path:$r(o),content:rn(b)},{path:vr,content:is(y)},...k],`model: task event ${o}`);{let{rebuildSearchIndex:C}=await Promise.resolve().then(()=>(Mo(),Lo));await C(e).catch(()=>{})}return{recorded:!0}}async function qh(t){let e=new Set([t.fallbackTaskKey]);try{let r=Rl(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(`
|
|
1042
|
+
`)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await cR(t.contextDir,r,t.prUrl)}async function cR(t,e,r){let n=es(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Te(t,[{path:$r(e),content:rn(o)}],`model: pr link for ${e}`)}Ar();import{existsSync as zh,readFileSync as Xh}from"node:fs";import{join as Jh}from"node:path";import{parseDocument as Zh}from"yaml";Ar();var Do=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Ef(this.cfg,e)}getIssue(e,r){return Rf(this.cfg,e,r??Qi(this.contextDir))}listComments(e,r){return Tf(this.cfg,e,r)}downloadAttachment(e){return Sf(this.cfg,e)}updateStatus(e,r){return hf(this.cfg,e,r,Qi(this.contextDir))}addComment(e,r,n){return gf(this.cfg,e,r)}createIssue(e){return bf(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Qi(this.contextDir))}editIssue(e,r){return yf(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return kf(this.cfg,e,r,n)}fetchStateFields(e){return Cf(this.cfg,e)}};D();ct();import{existsSync as hR,readFileSync as gR}from"node:fs";import{randomBytes as yR}from"node:crypto";import{existsSync as Tl,readFileSync as lR,readdirSync as uR}from"node:fs";D();ct();function us(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=mR(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:dR(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:fR(pR(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 Yh(t,e,r,n=10){let o=new Set(e.map(c=>c.issue.key)),i=[],s=c=>(c.links??[]).filter(l=>l.type==="subtask").map(l=>l.targetKey);for(let c of e)i.push(...s(c.issue));let a=[];for(;i.length>0&&a.length<n;){let c=i.shift();if(o.has(c)||(o.add(c),Tl(Se(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),i.push(...s(l)))}return a}async function ds(t,e,r){if(r.length===0)return;let n=us(t,e,r),o=r.map(i=>i.issue.key);await Te(t,n,`sync(${o.join(", ")}): task data`)}function dR(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(`
|
|
1043
|
+
`)}function pR(t,e,r){let n=new Map,o=Se(t,`tasks/${e}/comments.jsonl`);if(Tl(o))for(let i of lR(o,"utf-8").split(`
|
|
1044
|
+
`)){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=Tr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function fR(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
1045
1045
|
`)+(t.length>0?`
|
|
1046
|
-
`:"")}function
|
|
1046
|
+
`:"")}function mR(t,e,r){let n=[],o=Se(t,`tasks/${e}/attachments`);if(Tl(o))for(let i of uR(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}Hi();var Uo=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await To(this.contextDir);let r=e.columns??[];return um(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Co(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Io(this.contextDir,e);return r?Co(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Vh(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 To(this.contextDir),!Io(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${yR(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Tr(r);s&&(i.parsedCommand=s);let c=[...Vh(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
|
|
1047
1047
|
`)+`
|
|
1048
|
-
`;return await
|
|
1049
|
-
`)){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}Hi();function
|
|
1048
|
+
`;return await Te(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 dm(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:xi.statusColumns}]}async mutateRecord(e,r,n){let o=Io(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Co(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:dn(e),content:rl(i)},...us(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Te(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:wo,status:r.targetStatus,links:[],created:n,updated:n},i=Co(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:dn(e),content:rl(o)},...us(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function Vh(t,e){let r=Se(t,`tasks/${e}/comments.jsonl`);if(!hR(r))return[];let n=[];for(let o of gR(r,"utf-8").split(`
|
|
1049
|
+
`)){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}Hi();function Il(t){if(!t)return"youtrack";try{let e=Jh(t,"project.yaml");return zh(e)&&Zh(Xh(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Ct(t){let e=Il(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=cm(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=wR(n);return i?{ok:!0,kind:e,provider:new Uo(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=ff();return r?{ok:!0,kind:e,provider:new Do(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function wR(t){try{let e=Jh(t,"project.yaml");if(!zh(e))return null;let r=Zh(Xh(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var ms=new Map;async function Bo(t,e){let n=(ms.get(t)??Promise.resolve()).catch(()=>{}).then(e);ms.set(t,n);try{return await n}finally{ms.get(t)===n&&ms.delete(t)}}function Fo(t,e){return tr(t.split(":",2)[0]??"",e)}function rg(t){let{mirror:e,...r}=t;return{spec:r,host:_r(r)}}async function ng(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;lt(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Bo(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);if(r.mirror){let{syncUpstream:p}=await Promise.resolve().then(()=>(fs(),ps)),d=await p(r,a,{info:m=>lt(`[mirror] ${m}`),warn:m=>lt(`[mirror] WARN ${m}`)});d.error&<(`[mirror] ${r.name}: pre-apply sync failed \u2014 ${d.error}`)}let{commit:c,pushed:l,baseMoved:u}=await xm(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 p=e.taskId.split(":")[1]??"";p&&await Wh({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{lt(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return le({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...typeof u=="number"&&u>0?{baseMoved:u}:{},...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Bo(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir);return await Sm(s,a,{branchName:e.branchName,force:e.force}),le({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=Fo(e.taskId,r),a=await s.createPullRequest(i,e);if(t.contextDir){let c=e.taskId.split(":")[1]??"",l=e.taskId.split(":",2)[0]??"?";c&&await qh({contextDir:t.contextDir,repoDir:_e(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{lt(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return le({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=Fo(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return le({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return Z("no repo spec");let{spec:i,host:s}=Fo(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),le({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Bo(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{commit:c,dropped:l}=await Em(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:ln(r)});return le({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return Z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Bo(`${i}/${r.name}`,async()=>{let s=await cr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=_e(i,r.name,t.baseDir),{mergedSha:c}=await Rm(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return le({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Z("no repo spec");let i=t.cloneUrlOverride??In(r),a=(await Yi(i)).filter(u=>Tm(u,e.issueKey)),c=_r(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 le({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Z("no repo spec");let{spec:i,host:s}=e.upstream?rg(r):Fo(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),le({prNumber:e.prNumber,host:s.name})}case"add_pr_inline_comment":{if(!r)return Z("no repo spec");let{spec:i,host:s}=e.upstream?rg(r):Fo(e.taskId,r);if(s.addPRInlineComment)try{return await s.addPRInlineComment(i,e.prNumber,e.path,e.line,e.body),le({prNumber:e.prNumber,inline:!0,host:s.name})}catch(a){lt(`[exec] inline comment ${e.path}:${e.line} failed (${a instanceof Error?a.message.split(`
|
|
1050
1050
|
`)[0]:String(a)}) \u2014 posting as a plain comment`)}return await s.addPRComment(i,e.prNumber,`\u{1F4CD} \`${e.path}:${e.line}\`
|
|
1051
1051
|
|
|
1052
|
-
${e.body}`),le({prNumber:e.prNumber,inline:!1,host:s.name})}case"tracker_status":{let i=
|
|
1053
|
-
`,{mode:384})}function
|
|
1054
|
-
`)[0]:String(u)))}}}async function
|
|
1055
|
-
`).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await Pg(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function WT(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}var vs=class{constructor(e,r,n,o){this.intervalMs=e;this.fetchDeliverables=r;this.workspace=n;this.log=o}timer=null;running=!1;caughtUp=!1;warned=new Set;start(){if(this.timer)return;this.log.info(`[pull] local delivery started (interval=${this.intervalMs}ms)`);let e=()=>void this.runOnce();e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[pull] local delivery stopped"))}poke(){this.runOnce()}async runOnce(){if(!this.running){this.running=!0;try{let e=await this.fetchDeliverables(),r=this.caughtUp?e.filter(n=>n.phase==="TRACKING"||n.phase==="AWAITING_CLUSTER"):e;for(let n of r)await Ol(this.workspace.root,this.workspace.repos,n,this.warned,this.log);this.caughtUp=!0}catch(e){this.log.warn(`[pull] pass failed: ${e instanceof Error?e.message:String(e)}`)}finally{this.running=!1}}}};D();ut();pe();var _g=16*1024;function qT(t){return Qe.test(t)?Bt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Qe}`}function Ag(t,e,r,n){let o=qT(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(In(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>_g)return{ok:!1,detail:`secret value too large (max ${_g} chars)`};try{return Up(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function jg(t,e){try{return Bp(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)}}}wn();pe();er();var $s=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=[],o=e.split(":",2)[0]??"";for(let a of r.prs){let{spec:c,host:l}=vo(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,repoName:a.repoSpec.name,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof Cr){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.repoName??""}#${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=vo(o,r.prs[a].repoSpec);if(u.getCiFailureLog)try{let p=await u.getCiFailureLog(l,c.number);p&&(c.ciFailureLog=p)}catch(p){this.log.warn(`[track] task=${e} pr=${c.url} ci-log fetch failed: ${p instanceof Error?p.message:String(p)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,i);let s=YT(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function YT(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}D();Rn();var xs=class{constructor(e,r,n,o=i=>Yi(Tn(i))){this.intervalMs=e;this.send=r;this.log=n;this.listBranches=o}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r,this.lastSig.clear()}start(){if(this.timer)return;this.log.info(`[branches] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branches] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[branches] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let e of this.repos)await this.processRepo(e)}finally{this.running=!1}}}async processRepo(e){let r=e.gitFlow;if(!r||r.flow==="simple")return;let n;try{n=await this.listBranches(e)}catch(s){this.log.warn(`[branches] repo=${e.name} ls-remote failed: ${s instanceof Error?s.message:String(s)}`);return}let o=n.filter(s=>yc(s,r)).sort(),i=o.join("|");this.lastSig.get(e.name)!==i&&(this.send({type:"branches_observation",projectId:this.projectId,repoName:e.name,branches:o}),this.lastSig.set(e.name,i),this.log.info(`[branches] repo=${e.name} reported ${o.length} base candidate(s)`))}};D();var Ss=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??(()=>At({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 x=e.stageField?{stageField:e.stageField}:{},b=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},E=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(E){let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[C,A]=await Promise.all([v.length>0?r.listIssues({projectKey:e.projectKey,columns:v,...x,...b}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...x})]),G=new Map;for(let Y of[...C,...A])G.set(Y.id,Y);o=[...G.values()]}else{let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:v,...x,...b})}}catch(x){let b=x instanceof Error?x.message:String(x);b.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${b}`):this.log.warn(`[yt-sync] listIssues failed: ${b}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let x of o){if(s.add(x.id),a.has(x.status))continue;let b=await Lg(r,x.id,e.sinceMs,this.log);b&&i.set(x.id,b)}let c=[];for(let x of e.offBoardIssueIds){if(s.has(x))continue;let b=await Lg(r,x,e.sinceMs,this.log);b&&b.length>0&&i.set(x,b);let R=await Og(r,x,e.stageField,this.log);if(R)c.push(R);else if(b&&b.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}let l=o.filter(x=>!a.has(x.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(x=>({issue:x,comments:i.get(x.id)??[],attachments:u.get(x.id)??[]}));d.push(...await qh(this.options.contextDir,d,x=>Og(r,x,e.stageField,this.log)));try{await ds(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let x of p)this.shippedAttachments.add(x)}catch(x){let b=x instanceof Error?x.message:String(x);this.abandonTick(`context task sync failed: ${b}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],y=[];for(let[x,b]of i){let R=b.filter(v=>!m(v.id));if(R.length===0)continue;f.push({issueId:x,comments:R.map(VT)});let E=R.flatMap(v=>{let C=Tr(v.body);return C?[{commentId:v.id,author:v.author,name:C.name,args:C.args,createdAt:v.createdAt}]:[]});E.length>0&&y.push({issueId:x,commands:E})}let w={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Ng),commentsBatch:f,...y.length>0?{commandsBatch:y}:{},...c.length>0?{offBoardIssues:c.map(Ng)}:{},observedAtMs:n};this.send(w);let h=f.reduce((x,b)=>x+b.comments.length,0),k=y.reduce((x,b)=>x+b.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${h} commands=${k} (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(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=zT(u.name);l.has(m)&&(m=`${u.id}-${m}`),l.add(m),c.push({name:m,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Ng(t){let{description:e,...r}=t;return r}function VT(t){let{body:e,...r}=t;return r}function zT(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 Og(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 Lg(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}}async function pR(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(fs(),ps)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Mr(t.root,i.mountAs);try{o.push({repo:i.name,behind:await n(i,s)})}catch(a){e.warn(`[mirror] lag for ${i.name} unknown: ${a instanceof Error?a.message:String(a)}`),o.push({repo:i.name,behind:null})}}return o}var Wl="npm i -g @code-partner/codepipe@latest";function Ps(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${Je} (protocol ${gt})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&Wf(o.contextDir,r);let i=()=>{if(o?.contextDir)try{$n(o.contextDir,o.root,r)}catch(h){r.warn(`[skills] materialize failed (non-fatal): ${h instanceof Error?h.message:String(h)}`)}};i();let s=Yl("CLI_TRACKING_POLL_INTERVAL_SEC"),a=Yl("CLI_YOUTRACK_POLL_INTERVAL_SEC"),c=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),l=!1,u=!1,p=!1,d=new Set,m=!1,f=new Set,y=w();function w(){let h=ys(t.hubUrl,t.cliToken),k=null,x=new $s(s,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r),b=new xs(s,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r),R=o&&o.repos.length>0?new vs(Yl("CLI_LOCAL_PULL_INTERVAL_SEC"),()=>ks(t.hubUrl,t.cliToken,t.projectId),{root:o.root,repos:o.repos},r):null,E=new Ss(a,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r,{contextDir:o?.contextDir??null,isSelfComment:M=>f.has(M)}),v=null,C=async()=>{try{let M={trackerProvider:Rl(o?.contextDir??null)};try{let T=await se(t.hubUrl,t.cliToken,t.projectId);M={...M,repos:T.repos,contextRepo:T.contextRepo},b.setRepos(t.projectId,T.repos)}catch(T){r.warn(`[readiness] could not fetch project summary for push checks: ${T instanceof Error?T.message:String(T)}`)}let B=await Pf(t.projectId,M),L=o?await pR(o,r):[];if(i(),h.readyState!==h.OPEN)return;let ee={type:"cli_readiness",projectId:t.projectId,ready:B.ready,checks:B.checks,creds:B.creds,secretNames:Fp(t.projectId),...o?{mirrors:L}:{},checkedAt:B.checkedAt};if(h.send(JSON.stringify(ee)),B.ready)r.info("[readiness] ready");else{let T=B.checks.filter($=>!$.ok).map($=>`${$.name}(${$.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${T.join(", ")}`)}let F=Lf(B.creds,p);if(F==="open"){p=!0;let T=Mf(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${T}`),Ar(T)}else F==="rearm"&&(p=!1)}catch(M){r.warn(`[readiness] check failed: ${M instanceof Error?M.message:String(M)}`)}},A=()=>{C(),v=setInterval(()=>void C(),c),typeof v.unref=="function"&&v.unref()},G=()=>{v&&(clearInterval(v),v=null)},Y=150,_=new Map,g=M=>{let B=_.get(M);if(!B||(B.timer&&clearTimeout(B.timer),_.delete(M),B.events.length===0||h.readyState!==h.OPEN))return;let L={type:"run_activity",projectId:t.projectId,runId:M,events:B.events};h.send(JSON.stringify(L))},U=(M,B)=>{let L=_.get(M);if(L||(L={events:[],timer:null},_.set(M,L)),L.events.push(B),B.kind==="result"){g(M);return}L.timer||(L.timer=setTimeout(()=>g(M),Y),L.timer.unref?.())},O=o?.contextDir?new Mi(o.contextDir,t.projectId,M=>{h.readyState===h.OPEN&&h.send(JSON.stringify(M))},r):null,H=async()=>{let M=o?.contextDir;if(!M)throw new Error("no context repo clone on this CLI");let B;try{B=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let L=await ym(M,t.projectId,B,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(L)),L},X=null,ue=async()=>{let M=o?.contextDir;if(M)try{let{readContextIndexHub:B,collectSearchRows:L}=await Promise.resolve().then(()=>(Lo(),Oo));if(B(M)!=="metadata")return;let ee=L(M);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:ee})),r.info(`[model] tier-2 index snapshot pushed (${ee.length} rows)`))}catch(B){r.warn(`[model] tier-2 index push failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},Et=()=>{X&&clearTimeout(X),X=setTimeout(()=>void ue(),5e3)},ft=async()=>{if(!o?.contextDir)throw new Error("no Context Repo clone on this CLI");if(m)throw new Error("model bootstrap is already running");m=!0;try{let M=await se(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:B}=await Promise.resolve().then(()=>(Ko(),Cs)),L=await B(t.projectId,{root:o.root,contextDir:o.contextDir},M.repos,ee=>r.info(`[model] ${ee}`));return r.info(`[model] bootstrap done: ${L.repos} repos, ${L.events} task events`),Et(),L}finally{m=!1}},Re=null,Ae=async M=>{if(o?.contextDir)try{let B=await Promise.resolve().then(()=>(Ko(),Cs)),L={root:o.root,contextDir:o.contextDir,repos:o.repos};if(B.shouldAutoBootstrapModel(o.contextDir)){await B.syncWorkspaceMirrors(L,F=>r.info(F));try{await ft()}catch(F){r.warn(`[model] auto-bootstrap failed (non-fatal): ${F instanceof Error?F.message:String(F)}`)}return}(await B.rebuildWorkspaceModelIfStale(L,{fetch:M,onLog:F=>r.info(F)})).rebuilt.length>0&&Et()}catch(B){r.warn(`[model] release-path rebuild failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}},Le=M=>{Re&&clearTimeout(Re),Re=setTimeout(()=>void Ae(M),6e4)},Fe=setInterval(()=>void Ae(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let M=zp(t.projectId),B=Q("ORIGIN")==="farm"?"farm":"local",L=Q("FARM_ID"),ee=t.accountEmail??M.email,F;try{let $=Om(t.projectId);$&&(F=$.publicKey,r.info(`[cred-channel] key fingerprint: ${$.fingerprint}`))}catch($){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${$ instanceof Error?$.message:String($)}`)}let T={type:"register",projectId:t.projectId,platformVersion:Je,protocolVersion:gt,accountId:M.accountId,accountLabel:M.label,origin:B,inFlightActionIds:[...d],...ee?{accountEmail:ee}:{},...B==="farm"&&L?{farmId:L}:{},...F?{sealPublicKey:F}:{}};h.send(JSON.stringify(T))}),h.on("message",async M=>{let B=M.toString("utf-8");if(B==="pong"||B==="ping")return;let L;try{L=JSON.parse(B)}catch{return}if(!L||typeof L!="object")return;let ee=L.type;if(ee==="registered"){let T=L;if(T.ok){if(r.info(`[ws] registered for project ${T.projectId}`),n({kind:"registered",projectId:T.projectId??t.projectId}),x.start(),b.start(),R?.start(),O?.start(),A(),ql(t,o,r),o?.contextDir){try{let $=Ki(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify($)),$.outdated&&(r.warn(`[ctx] context format outdated: v${$.templateVersion} \u2192 v${$.currentVersion}`+($.missingPaths.length>0?` (missing: ${$.missingPaths.join(", ")})`:"")),u||(u=!0,H().catch(()=>{})))}catch($){r.warn(`[ctx] context-format detect failed (non-fatal): ${$ instanceof Error?$.message:String($)}`)}ue(),Le(!0)}}else r.warn(`[ws] register rejected: ${T.reason??"unknown"}`),n({kind:"register_rejected",reason:T.reason??"unknown"}),l=!0,h.close();return}if(ee==="hello"){let T=L;k=oo(T.protocolVersion);let $=k?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${T.platformVersion} (protocol ${T.protocolVersion}) \u2014 ${$}`),k||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Je}, protocol ${gt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Wl}`),n({kind:"incompatible",hubVersion:typeof T.platformVersion=="string"?T.platformVersion:null,hubProtocol:typeof T.protocolVersion=="number"?T.protocolVersion:null,updateCommand:Wl}));return}if(ee==="tracking_targets"){x.setTargets(L.targets),R?.poke();return}if(ee==="youtrack_sync_request"){E.setRequest(L);return}if(ee==="youtrack_force_sync"){E.forceSync();return}if(ee==="sync_local"){await hR(L,o,h,r);return}if(ee==="provision_repo"){let T=L;r.info(`[repo] provision_repo: ${T.repo.name} (${T.repo.host}:${T.repo.owner}/${T.repo.repoName})`),await fR(t,o,T.repo,r),await ql(t,o,r);return}if(ee==="remove_repo"){let T=L;r.info(`[repo] remove_repo: ${T.repoName}${T.purge?" (purge)":""}`),await ql(t,o,r),T.purge&&mR(t,o,T.repoName,r);return}if(ee==="context_write"){await gR(L,o,h,r),i();return}if(ee==="adr_promote"){await yR(L,o,h,r),i();return}if(ee==="cred_update"){let T=L,$=q(t.projectId),I=$?.sealKey?await Lm(t.projectId,T.kind,T.sealed,$.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},V={type:"cred_update_result",updateId:T.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(V)),I.ok?(r.info(`[cred] ${T.kind} replaced${I.detail?` \u2014 ${I.detail}`:""}`),C()):r.warn(`[cred] ${T.kind} replacement rejected: ${I.detail??"unknown"}`);return}if(ee==="readiness_check"){r.info("[readiness] on-demand check requested"),C();return}if(ee==="agent_login_start"){Of(t,h,L,r,C);return}if(ee==="move_to_farm"){let T=L;r.info(`[farm-move] request to move ${t.projectId} onto farm ${T.farmName} (${T.farmId})`);let $=await bg(t,T,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify($)),$.ok?r.info(`[farm-move] done \u2014 farm daemon ${$.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${$.error??"unknown error"}`);return}if(ee==="gh_runner_setup"){let T=L;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${T.runnerName} (${T.runnerId})`);let $=await Tg(t,T,r);h.readyState===h.OPEN&&h.send(JSON.stringify($)),$.ok?r.info(`[ghr] runners connected on ${T.runnerName}`):r.warn(`[ghr] setup failed: ${$.error??"see per-repo statuses"}`);return}if(ee==="gh_runner_teardown"){let T=L;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${T.runnerName} (${T.runnerId})`);let $=await Rg(t,T,r);h.readyState===h.OPEN&&h.send(JSON.stringify($)),$.ok?r.info(`[ghr] runners disconnected from ${T.runnerName}`):r.warn(`[ghr] teardown failed: ${$.error??"unknown error"}`);return}if(ee==="tracker_fields_request"){let T=L,$={type:"tracker_fields_result",requestId:T.requestId,projectId:t.projectId,ok:!1},I=At({contextDir:o?.contextDir??null});if(!I.ok)$.error=I.error;else try{$.fields=await I.provider.fetchStateFields(T.projectKey),$.ok=!0}catch(V){$.error=V instanceof Error?V.message:String(V)}h.readyState===h.OPEN&&h.send(JSON.stringify($)),$.ok||r.warn(`[yt-fields] listing failed: ${$.error??"unknown"}`);return}if(ee==="project_secret_update"||ee==="project_secret_delete"){let T=L,$;if(T.type==="project_secret_update"){let V=q(t.projectId);$=V?.sealKey?Ag(t.projectId,T.name,T.sealed,V.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else $=jg(t.projectId,T.name);let I={type:"project_secret_update_result",updateId:T.updateId,projectId:t.projectId,ok:$.ok,...$.detail?{detail:$.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(I)),$.ok?(r.info(`[secret] ${T.name} ${T.type==="project_secret_update"?"saved":"deleted"}`+($.detail?` \u2014 ${$.detail}`:"")),C()):r.warn(`[secret] ${T.name} rejected: ${$.detail??"unknown"}`);return}if(ee==="sandbox_keys"){let T=q(t.projectId);if(!T){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let $=mn(t.projectId),I=_m(L,T,$,r);for(let V of I)h.readyState===h.OPEN&&h.send(JSON.stringify(V));return}if(ee!=="dispatch_action")return;let F=L;if(k===!1){let T=`refused: HUB protocol incompatible with CLI v${Je} (protocol ${gt})`;h.send(JSON.stringify({type:"action_result",actionId:F.actionId,status:"failed",error:T})),r.warn(`[exec] ${F.actionId} (${F.action.type}) \u2192 REFUSED: ${T}`),r.warn(`[exec] update the CLI to clear this: ${Wl}`),n({kind:"action",actionId:F.actionId,actionType:F.action.type,ok:!1,error:T});return}if(F.action.type==="model_drift"){d.add(F.actionId);try{let T,$=o?.repos.find(I=>I.name===F.action.repoName);if(!o?.contextDir||!$)T={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:I}=await Promise.resolve().then(()=>(Xg(),zg)),V=$.mountAs==="."?o.root:Mr(o.root,$.mountAs);T={status:"done",result:{report:await I(V,o.contextDir,$.name)}}}catch(I){T={status:"failed",error:I instanceof Error?I.message:String(I)}}h.send(JSON.stringify({type:"action_result",actionId:F.actionId,...T}))}finally{d.delete(F.actionId)}return}if(F.action.type==="model_bootstrap"){d.add(F.actionId);try{let T;try{let $=await ft();T={status:"done",result:{repos:$.repos,events:$.events}}}catch($){T={status:"failed",error:$ instanceof Error?$.message:String($)},r.warn(`[model] bootstrap failed: ${T.error}`)}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:F.actionId,...T}))}finally{d.delete(F.actionId)}return}d.add(F.actionId);try{let T=await rg({action:F.action,repo:F.repo,trackerIssueId:F.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:O?()=>O.reportNow():void 0,refreshContextStatus:o?.contextDir?H:void 0,onRunActivity:U}).catch(V=>({status:"failed",error:V instanceof Error?V.message:String(V)}));F.action.type==="tracker_comment"&&T.status==="done"&&"result"in T&&typeof T.result?.commentId=="string"&&f.add(T.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:F.actionId,...T}));let $=T.status!=="failed",I=!$&&"error"in T?T.error:void 0;$?r.info(`[exec] ${F.actionId} (${F.action.type}) \u2192 done`):r.warn(`[exec] ${F.actionId} (${F.action.type}) \u2192 FAILED: ${I??"?"}`),n({kind:"action",actionId:F.actionId,actionType:F.action.type,ok:$,...I?{error:I}:{}}),$&&["apply_delivery","context_write","create_pr"].includes(F.action.type)&&Et(),$&&["merge_pr","merge_branch"].includes(F.action.type)&&Le(!0)}finally{d.delete(F.actionId)}}),h.on("close",(M,B)=>{let L=B?.toString("utf-8")??"";if(r.info(`[ws] closed code=${M}${L?` reason=${L}`:""}`),x.stop(),b.stop(),R?.stop(),E.stop(),O?.stop(),G(),clearInterval(Fe),Re&&clearTimeout(Re),X&&clearTimeout(X),L==="replaced"){l=!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:M}),!l&&setTimeout(()=>{y=w()},2e3)}),h.on("error",M=>r.warn(`[ws] error: ${M.message}`)),h}return{stop(){l=!0,y.close()}}}async function ql(t,e,r){try{let n=await se(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Co(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 fR(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?Mr(e.root,o):je(t.projectId,r.name);if(Jg(Mr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await dR().clone(e?Tn(r):sl(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 mR(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Mr(e.root,o):je(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Jg(Mr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{uR(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 hR(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=Mr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Df(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 gR(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 Ce(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 yR(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 Zf(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 Yl(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}Ne();pe();Ht();zl();bt();zi();async function ly(t={profile:void 0}){let{cfg:e,profile:r}=fn(t.profile),n=q(e.projectId);n&&ko(n),Po(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),_o(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Ao(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Ho(Xl(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Ii("CLI_LOG",i,o);if(s.enabled){let d=new gn(s);Ci(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=dn(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=Ho(Xl(),".codepipe",r?Ho("profiles",r,"context"):"context");if(await Al(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await ay(()=>As({cfg:e,secrets:n,contextDir:d,log:{info:m=>console.log(m),warn:m=>console.warn(m)}}),{log:{warn:m=>console.warn(m)}}),a||await Al(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let m=Ho(Xl(),".codepipe",r?Ho("profiles",r,"context-config"):"context-config");Di(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=Ps(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(`
|
|
1056
|
-
[${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Gn();We();Ne();async function Sb(t={profile:void 0}){let e=it(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=ys(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 se(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=De(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`)")}ri();import{readFileSync as B_}from"node:fs";D();We();Ht();Zo();jr();er();_r();Ne();pe();function xe(t){throw new Error(t)}function Pe(t,e){return(typeof t!="string"||t.trim().length===0)&&xe(`config: '${e}' must be a non-empty string`),t.trim()}function ii(t,e){if(t==null)return;typeof t!="string"&&xe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function F_(t){(!t||typeof t!="object")&&xe("config: expected a JSON object");let e=t,r=Pe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||xe("config: 'hubUrl' must start with http(s)://");let n=Pe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&xe("config: 'project' is required");let i=o,s=Pe(i.id,"project.id");Xt.test(s)||xe("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Pe(i.name,"project.name"),c=Pe(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&xe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||xe("config: 'project.repos' must be an array");let u=l.map((k,x)=>{(!k||typeof k!="object")&&xe(`config: project.repos[${x}] must be an object`);let b=k,R=Pe(b.host,`project.repos[${x}].host`);R!=="github"&&R!=="bitbucket"&&R!=="gitlab"&&xe(`config: project.repos[${x}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:Pe(b.name,`project.repos[${x}].name`),host:R,owner:Pe(b.owner,`project.repos[${x}].owner`),repoName:Pe(b.repoName,`project.repos[${x}].repoName`)},v=ii(b.defaultBranch,`project.repos[${x}].defaultBranch`);v&&(E.defaultBranch=v);let C=ii(b.mountAs,`project.repos[${x}].mountAs`);return C&&(E.mountAs=C),E}),p=i.contextRepo;(!p||typeof p!="object")&&xe("config: 'project.contextRepo' is required");let d=p,m=ii(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&xe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:Pe(d.owner,"project.contextRepo.owner"),name:ii(d.name,"project.contextRepo.name")??It(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},w=ii(i.youtrackProjectKey,"project.youtrackProjectKey");if(w&&(y.project.youtrackProjectKey=w),i.index!==void 0&&(typeof i.index!="boolean"&&xe("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&xe("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let k=Pe(i.llmProvider,"project.llmProvider");k==="codex"&&xe(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),k!=="claude"&&xe("config: 'project.llmProvider' must be 'claude'"),y.project.llmProvider=k}let h=e.secrets;if(h!==void 0){(typeof h!="object"||h===null)&&xe("config: 'secrets' must be an object");let k=h,x={};if(k.github){let b=k.github;x.github={token:Pe(b.token,"secrets.github.token")}}if(k.bitbucket){let b=k.bitbucket;x.bitbucket={email:Pe(b.email,"secrets.bitbucket.email"),apiToken:Pe(b.apiToken,"secrets.bitbucket.apiToken")}}if(k.gitlab){let b=k.gitlab;x.gitlab={token:Pe(b.token,"secrets.gitlab.token")}}if(k.youtrack){let b=k.youtrack;x.youtrack={url:Pe(b.url,"secrets.youtrack.url").replace(/\/$/,""),token:Pe(b.token,"secrets.youtrack.token")}}if(k.contextWrite){let b=k.contextWrite;x.contextWrite={token:Pe(b.token,"secrets.contextWrite.token")}}y.secrets=x}return y}async function G_(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function K_(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Jt(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 Zt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await ji(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 Qt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await rr({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Mk(t){let e=!t.configPath||t.configPath==="-"?await G_():B_(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){xe(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=F_(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 K_(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 Kn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??hn(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){xe(`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 cr(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 se(o,i,s.id);else if(d instanceof K)xe(`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(ae(p),Gt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ct(s.id)}`),or(s.id,_t(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??Ze),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Go(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`)}We();pe();import{cancel as Dk,intro as Uk,isCancel as Bk,log as Uu,outro as H_,password as Fk}from"@clack/prompts";async function W_(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Gk(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await W_(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Uk("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Uu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Fk({message:"Claude OAuth token"});Bk(i)&&(Dk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Kp({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Ri()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=it(t.profile);if(!e){Uk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Uu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Fk({message:"Claude OAuth token"});Bk(i)&&(Dk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=q(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ae(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Uu.success("Claude OAuth token saved."),H_("It will be sealed into job bundles when a SANDBOX (re)connects."))}Ko();D();We();Ht();Zo();jr();Ys();Ne();pe();import{cancel as q_,confirm as Y_,intro as V_,isCancel as Kk,log as Ue,outro as z_,select as Hk,text as yr}from"@clack/prompts";function Wk(t){q_(t),process.exit(1)}function zn(t){return Kk(t)&&Wk("aborted"),t}function si(t){return Kk(t)&&Wk("aborted"),typeof t=="string"?t:""}async function X_(t,e){let r=zn(await Hk({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=si(await yr({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=si(await yr({message:"Context Repo name",placeholder:It(t),initialValue:It(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function qk(t={profile:void 0}){let e=it(t.profile);V_(`codepipe project add \u2192 ${e.hubUrl}`);let r=zn(await yr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Xt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=zn(await yr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=zn(await Hk({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=zn(await yr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=zn(await Y_({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=si(await yr({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:h=>!h||!h.trim()||ze(h)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=ze(d);Ue.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=si(await yr({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:h=>h.trim().length>0?void 0:"required"})).trim(),y=si(await yr({message:"default branch (optional)",placeholder:"main"})).trim(),w={name:f,host:m.host,owner:m.owner,repoName:m.repoName};y&&(w.defaultBranch=y),a.push(w)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await X_(r,a),u=q(e.projectId);Ue.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Kn(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??hn(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Ue.message(d),warn:d=>Ue.warn(d)}})}catch(d){Ue.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Ue.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await cr(e.hubUrl,e.cliToken,c);Ue.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),or(r,_t(c,s,u?.youtrack?.url),{info:m=>Ue.message(m),warn:m=>Ue.warn(m)}),d.contextRepo&&(Ue.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Ue.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Ue.error(` error: ${d.provisioningError}`),z_("done")}catch(d){d instanceof K?(Ue.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Ue.message(JSON.stringify(d.payload,null,2))):Ue.error(d instanceof Error?d.message:String(d)),process.exit(1)}}Gn();We();Ne();pe();bt();ri();import{existsSync as J_,rmSync as Z_}from"node:fs";import{confirm as Q_,intro as eA,isCancel as tA,log as wr,outro as rA,spinner as nA}from"@clack/prompts";function Lt(t){wr.error(t),process.exit(1)}var Yk=t=>t.trim().replace(/\/+$/,"");async function Vk(t){eA("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??_e()?.spec.projectId??void 0;e||Lt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=kt(e);r||Lt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Yk(r.hubUrl),o=r.projectId,i=Yk(t.hub);i.startsWith("http")||Lt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Lt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let h=nA();h.start(`reading project ${o} from ${n}\u2026`);try{l=await se(n,r.cliToken,o),h.stop(`read project ${o} (${l.name})`)}catch(k){throw h.stop("could not read the source project",1),k instanceof K&&Lt(`source HUB ${n} \u2192 ${k.status} ${k.message}. The source HUB must be reachable with a valid token to move a project.`),k}}l.contextRepo||Lt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=q(o),p=(t.account??r.accountEmail??await Yn()).trim().toLowerCase();if(wr.message(`move project '${o}'
|
|
1052
|
+
${e.body}`),le({prNumber:e.prNumber,inline:!1,host:s.name})}case"tracker_status":{let i=Ct({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),le({issueId:t.trackerIssueId,newStatus:e.newStatus})):Z("no tracker_issue_id provided"):Z(i.error)}case"tracker_comment":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!t.trackerIssueId)return Z("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return le({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!e.projectKey)return Z("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 le({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(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 Z(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return le({applied:s})}case"set_project_setting":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await Hm(t.contextDir,e.edits);return le({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return Z("no context repo clone on this CLI");if(!ic(e.role))return Z(`unknown prompt operation: ${e.role}`);let i=sc(e.role);return await Te(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),le({path:i,reset:e.content===null})}case"tracker_edit":{let i=Ct({contextDir:t.contextDir});if(!i.ok)return Z(i.error);if(!t.contextDir)return Z("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 ds(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),le({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await Qm(t.contextDir,e);return le({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=await Jm(t.contextDir,e);return le({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),le({reported:!0})):Z("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return Z("no context repo clone on this CLI");let i=await t.refreshContextStatus();return le({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return Z("no project workspace on this CLI");if(!r)return Z("no repo spec");if(!t.onRunActivity)return Z("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Li(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return Z(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Ya(c,e.input);if(!l.ok)return Z(l.error);let u=Kf(t.contextDir),p=V(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),Bo(`${e.projectId}/${r.name}`,async()=>{await cr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=_e(e.projectId,r.name,t.baseDir),f=await Bm({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return le({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Z("no context repo clone on this CLI");let i=Km(t.contextDir,e.path);return le({path:e.path,...i})}case"search_model":{if(!t.contextDir)return Z("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(Mo(),Lo)),s=await i(t.contextDir,e.q,e.limit);return le({hits:s})}case"model_drift":return Z("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return Z("model_bootstrap requires a local workspace (handled by the daemon)");default:return Z(`unsupported action type: ${e.type}`)}}catch(i){return Z(i instanceof Error?i.message:String(i))}}function le(t){return{status:"done",result:t}}function Z(t){return{status:"failed",error:t}}ut();_l();Ae();de();import{existsSync as yg,readFileSync as wg}from"node:fs";import{join as bg}from"node:path";async function kg(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=We(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");gs(e.farmId,e.farmPublicKey);let s=V(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await ie(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=bg(r,"project.yaml"),m=bg(r,"regimen.yaml");yg(d)&&yg(m)?c={projectYaml:wg(d,"utf-8"),regimenYaml:wg(m,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=qt(e.farmPublicKey,JSON.stringify(l));hs(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await ws(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))}}D();ut();Ke();ut();import{homedir as jR}from"node:os";import{existsSync as NR,mkdirSync as OR,readFileSync as LR,writeFileSync as MR}from"node:fs";import{dirname as DR,join as UR}from"node:path";function Nl(){return Q("RUNNER_PINS")??UR(jR(),".codepipe","runner-pins.json")}function vg(){let t=Nl();if(!NR(t))return{};try{return JSON.parse(LR(t,"utf-8"))}catch{return{}}}function BR(t){let e=Nl();OR(DR(e),{recursive:!0}),MR(e,JSON.stringify(t,null,2)+`
|
|
1053
|
+
`,{mode:384})}function FR(t){return vg()[t]}function Ol(t,e){let r=vg();r[t]=e,BR(r)}function $g(t,e){let r=We(e),n=FR(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 ${Nl()}.`);return r}Ae();de();var Sg=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function xg(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Sg(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var GR={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Sg(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)=>xg(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>xg(t,e,r,"remove-token")},Eg={api:GR,fetchProject:ie,provisionOnRunner:sg,teardownOnRunner:ag};async function Rg(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(We(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");$g(e.runnerId,e.runnerPublicKey);let i=V(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 Tg(t,e,r,n=Eg){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 Rg(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:[pc(e.runnerId)]},c=qt(e.runnerPublicKey,JSON.stringify(a));Ol(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 Ig(t,e,r,n=Eg){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 Rg(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=qt(e.runnerPublicKey,JSON.stringify(c));Ol(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))}}Ae();D();import{existsSync as KR}from"node:fs";import{join as Cg}from"node:path";import{simpleGit as _g}from"simple-git";async function Ll(t,e,r,n,o){for(let i of r.repos){let s=e.find(u=>u.name===i.repoName);if(!s)continue;let a=`${r.taskKey}:${s.name}:${i.branchName}`;if(!Xt(i.branchName)){n.has(a)||(n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: refusing suspicious branch name`));continue}let c=Cg(t,s.mountAs);if(!KR(Cg(c,".git")))continue;let l=_g(c);try{let u=await qR(l,i.branchName);await l.fetch(await HR(l,s),`refs/heads/${i.branchName}`);let p=(await l.revparse(["FETCH_HEAD"])).trim();if(u===p)continue;if(await WR(l,c,i.branchName)){n.has(a)||(n.add(a),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} is checked out here \u2014 fetched ${p.slice(0,10)}; merge or pull it in that checkout yourself`));continue}await l.raw(["branch","-f",i.branchName,p]),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} ${p.slice(0,10)} (checkout untouched)`)}catch(u){if(n.has(a))continue;n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: ${i.branchName} unavailable \u2014 `+(u instanceof Error?u.message.split(`
|
|
1054
|
+
`)[0]:String(u)))}}}async function HR(t,e){if(e.mirror)return Pg(e.mirror);try{if((await t.getRemotes(!0)).find(n=>n.name==="origin")?.refs?.fetch)return"origin"}catch{}return e.host&&e.owner&&e.repoName?Pg({host:e.host,owner:e.owner,repoName:e.repoName}):"origin"}function Pg(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 WR(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
|
|
1055
|
+
`).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await _g(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function qR(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}var vs=class{constructor(e,r,n,o){this.intervalMs=e;this.fetchDeliverables=r;this.workspace=n;this.log=o}timer=null;running=!1;caughtUp=!1;warned=new Set;start(){if(this.timer)return;this.log.info(`[pull] local delivery started (interval=${this.intervalMs}ms)`);let e=()=>void this.runOnce();e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[pull] local delivery stopped"))}poke(){this.runOnce()}async runOnce(){if(!this.running){this.running=!0;try{let e=await this.fetchDeliverables(),r=this.caughtUp?e.filter(n=>n.phase==="TRACKING"||n.phase==="AWAITING_CLUSTER"):e;for(let n of r)await Ll(this.workspace.root,this.workspace.repos,n,this.warned,this.log);this.caughtUp=!0}catch(e){this.log.warn(`[pull] pass failed: ${e instanceof Error?e.message:String(e)}`)}finally{this.running=!1}}}};D();ut();de();var Ag=16*1024;function YR(t){return Ze.test(t)?Bt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Ze}`}function jg(t,e,r,n){let o=YR(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Pn(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>Ag)return{ok:!1,detail:`secret value too large (max ${Ag} chars)`};try{return Bp(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Ng(t,e){try{return Fp(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)}}}kn();de();Kt();var $s=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=[],o=e.split(":",2)[0]??"";for(let a of r.prs){let{spec:c,host:l}=tr(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,repoName:a.repoSpec.name,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof Pr){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.repoName??""}#${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=tr(o,r.prs[a].repoSpec);if(u.getCiFailureLog)try{let p=await u.getCiFailureLog(l,c.number);p&&(c.ciFailureLog=p)}catch(p){this.log.warn(`[track] task=${e} pr=${c.url} ci-log fetch failed: ${p instanceof Error?p.message:String(p)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,i);let s=VR(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function VR(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}D();Cn();var xs=class{constructor(e,r,n,o=i=>Yi(In(i))){this.intervalMs=e;this.send=r;this.log=n;this.listBranches=o}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r,this.lastSig.clear()}start(){if(this.timer)return;this.log.info(`[branches] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branches] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[branches] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let e of this.repos)await this.processRepo(e)}finally{this.running=!1}}}async processRepo(e){let r=e.gitFlow;if(!r||r.flow==="simple")return;let n;try{n=await this.listBranches(e)}catch(s){this.log.warn(`[branches] repo=${e.name} ls-remote failed: ${s instanceof Error?s.message:String(s)}`);return}let o=n.filter(s=>wc(s,r)).sort(),i=o.join("|");this.lastSig.get(e.name)!==i&&(this.send({type:"branches_observation",projectId:this.projectId,repoName:e.name,branches:o}),this.lastSig.set(e.name,i),this.log.info(`[branches] repo=${e.name} reported ${o.length} base candidate(s)`))}};D();Kt();var Ss=class{constructor(e,r,n,o=zR,i=XR){this.intervalMs=e;this.send=r;this.log=n;this.read=o;this.readFailureLog=i}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r;let n=new Set(r.map(o=>o.name));for(let o of[...this.lastSig.keys()])n.has(o)||this.lastSig.delete(o)}start(){if(this.timer)return;this.log.info(`[branch-ci] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branch-ci] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async tick(){if(!(this.running||!this.projectId)){this.running=!0;try{for(let e of this.repos){let r=ln(e);try{let n=await this.read(this.projectId,e,r);if(!n||n.ci==="none")continue;let o=`${r}:${n.ci}:${n.headSha}`;if(this.lastSig.get(e.name)===o)continue;let i;n.ci==="failed"&&(i=await this.readFailureLog(this.projectId,e,n.headSha).catch(()=>{})),this.send({type:"branch_ci_observed",projectId:this.projectId,repoName:e.name,branch:r,ci:n.ci,headSha:n.headSha,...i?{ciFailureLog:i}:{}}),this.lastSig.set(e.name,o),this.log.info(`[branch-ci] ${e.name}#${r}: ${n.ci} @ ${n.headSha.slice(0,10)}`)}catch(n){this.log.warn(`[branch-ci] ${e.name}#${r}: read failed \u2014 ${n instanceof Error?n.message:String(n)}`)}}}finally{this.running=!1}}}};async function zR(t,e,r){let{spec:n,host:o}=tr(t,e);if(!o.getBranchCi)return null;let i=await o.getBranchCi(n,r);return i?{ci:i.ci,headSha:i.headSha}:null}async function XR(t,e,r){let{spec:n,host:o}=tr(t,e);if(o.getCiFailureLogForSha)return await o.getCiFailureLogForSha(n,r)}D();var Es=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??(()=>Ct({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 y=e.stageField?{stageField:e.stageField}:{},k=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},E=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(E){let $=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[_,j]=await Promise.all([$.length>0?r.listIssues({projectKey:e.projectKey,columns:$,...y,...k}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...y})]),B=new Map;for(let K of[..._,...j])B.set(K.id,K);o=[...B.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:$,...y,...k})}}catch(y){let k=y instanceof Error?y.message:String(y);k.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${k}`):this.log.warn(`[yt-sync] listIssues failed: ${k}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let y of o){if(s.add(y.id),a.has(y.status))continue;let k=await Mg(r,y.id,e.sinceMs,this.log);k&&i.set(y.id,k)}let c=[];for(let y of e.offBoardIssueIds){if(s.has(y))continue;let k=await Mg(r,y,e.sinceMs,this.log);k&&k.length>0&&i.set(y,k);let C=await Lg(r,y,e.stageField,this.log);if(C)c.push(C);else if(k&&k.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}let l=o.filter(y=>!a.has(y.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(y=>({issue:y,comments:i.get(y.id)??[],attachments:u.get(y.id)??[]}));d.push(...await Yh(this.options.contextDir,d,y=>Lg(r,y,e.stageField,this.log)));try{await ds(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let y of p)this.shippedAttachments.add(y)}catch(y){let k=y instanceof Error?y.message:String(y);this.abandonTick(`context task sync failed: ${k}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[y,k]of i){let C=k.filter($=>!m($.id));if(C.length===0)continue;f.push({issueId:y,comments:C.map(JR)});let E=C.flatMap($=>{let _=Tr($.body);return _?[{commentId:$.id,author:$.author,name:_.name,args:_.args,createdAt:$.createdAt}]:[]});E.length>0&&g.push({issueId:y,commands:E})}let w={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Og),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...c.length>0?{offBoardIssues:c.map(Og)}:{},observedAtMs:n};this.send(w);let b=f.reduce((y,k)=>y+k.comments.length,0),v=g.reduce((y,k)=>y+k.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${b} commands=${v} (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(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=ZR(u.name);l.has(m)&&(m=`${u.id}-${m}`),l.add(m),c.push({name:m,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Og(t){let{description:e,...r}=t;return r}function JR(t){let{body:e,...r}=t;return r}function ZR(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 Lg(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 Mg(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}}async function hT(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(fs(),ps)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Dr(t.root,i.mountAs);try{o.push({repo:i.name,behind:await n(i,s)})}catch(a){e.warn(`[mirror] lag for ${i.name} unknown: ${a instanceof Error?a.message:String(a)}`),o.push({repo:i.name,behind:null})}}return o}var ql="npm i -g @code-partner/codepipe@latest";function _s(t,e={}){let r=e.log??{info:y=>console.log(y),warn:y=>console.warn(y)};r.info(`codepipe-cli v${Xe} (protocol ${mt})`);let n=y=>e.onEvent?.(y),o=e.workspace;o?.contextDir&&qf(o.contextDir,r);let i=()=>{if(o?.contextDir)try{Sn(o.contextDir,o.root,r)}catch(y){r.warn(`[skills] materialize failed (non-fatal): ${y instanceof Error?y.message:String(y)}`)}};i();let s=Vl("CLI_TRACKING_POLL_INTERVAL_SEC"),a=parseInt(process.env.CLI_BRANCH_CI_POLL_INTERVAL_SEC??"300",10),c=Number.isFinite(a)&&a>0?a*1e3:3e5,l=Vl("CLI_YOUTRACK_POLL_INTERVAL_SEC"),u=(()=>{let y=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(y)&&y>0?y*1e3:6e5})(),p=!1,d=!1,m=!1,f=new Set,g=!1,w=new Set,b=v();function v(){let y=ys(t.hubUrl,t.cliToken),k=null,C=new $s(s,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r),E=new xs(s,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r),$=new Ss(c,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r),_=o&&o.repos.length>0?new vs(Vl("CLI_LOCAL_PULL_INTERVAL_SEC"),()=>ks(t.hubUrl,t.cliToken,t.projectId),{root:o.root,repos:o.repos},r):null,j=new Es(l,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r,{contextDir:o?.contextDir??null,isSelfComment:U=>w.has(U)}),B=null,K=async()=>{try{let U={trackerProvider:Il(o?.contextDir??null)};try{let x=await ie(t.hubUrl,t.cliToken,t.projectId);U={...U,repos:x.repos,contextRepo:x.contextRepo},E.setRepos(t.projectId,x.repos),$.setRepos(t.projectId,x.repos)}catch(x){r.warn(`[readiness] could not fetch project summary for push checks: ${x instanceof Error?x.message:String(x)}`)}let G=await _f(t.projectId,U),M=o?await hT(o,r):[];if(i(),y.readyState!==y.OPEN)return;let T={type:"cli_readiness",projectId:t.projectId,ready:G.ready,checks:G.checks,creds:G.creds,secretNames:Gp(t.projectId),...o?{mirrors:M}:{},checkedAt:G.checkedAt};if(y.send(JSON.stringify(T)),G.ready)r.info("[readiness] ready");else{let x=G.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${x.join(", ")}`)}let R=Mf(G.creds,m);if(R==="open"){m=!0;let x=Df(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${x}`),jr(x)}else R==="rearm"&&(m=!1)}catch(U){r.warn(`[readiness] check failed: ${U instanceof Error?U.message:String(U)}`)}},A=()=>{K(),B=setInterval(()=>void K(),u),typeof B.unref=="function"&&B.unref()},h=()=>{B&&(clearInterval(B),B=null)},F=150,L=new Map,q=U=>{let G=L.get(U);if(!G||(G.timer&&clearTimeout(G.timer),L.delete(U),G.events.length===0||y.readyState!==y.OPEN))return;let M={type:"run_activity",projectId:t.projectId,runId:U,events:G.events};y.send(JSON.stringify(M))},ee=(U,G)=>{let M=L.get(U);if(M||(M={events:[],timer:null},L.set(U,M)),M.events.push(G),G.kind==="result"){q(U);return}M.timer||(M.timer=setTimeout(()=>q(U),F),M.timer.unref?.())},se=o?.contextDir?new Mi(o.contextDir,t.projectId,U=>{y.readyState===y.OPEN&&y.send(JSON.stringify(U))},r):null,Nt=async()=>{let U=o?.contextDir;if(!U)throw new Error("no context repo clone on this CLI");let G;try{G=(await ie(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let M=await wm(U,t.projectId,G,r);return y.readyState===y.OPEN&&y.send(JSON.stringify(M)),M},Be=null,Ne=async()=>{let U=o?.contextDir;if(U)try{let{readContextIndexHub:G,collectSearchRows:M}=await Promise.resolve().then(()=>(Mo(),Lo));if(G(U)!=="metadata")return;let T=M(U);y.readyState===y.OPEN&&(y.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:T})),r.info(`[model] tier-2 index snapshot pushed (${T.length} rows)`))}catch(G){r.warn(`[model] tier-2 index push failed (non-fatal): ${G instanceof Error?G.message:String(G)}`)}},Ce=()=>{Be&&clearTimeout(Be),Be=setTimeout(()=>void Ne(),5e3)},Oe=async()=>{if(!o?.contextDir)throw new Error("no Context Repo clone on this CLI");if(g)throw new Error("model bootstrap is already running");g=!0;try{let U=await ie(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:G}=await Promise.resolve().then(()=>(Ho(),Ps)),M=await G(t.projectId,{root:o.root,contextDir:o.contextDir},U.repos,T=>r.info(`[model] ${T}`));return r.info(`[model] bootstrap done: ${M.repos} repos, ${M.events} task events`),Ce(),M}finally{g=!1}},Ee=null,rt=async U=>{if(o?.contextDir)try{let G=await Promise.resolve().then(()=>(Ho(),Ps)),M={root:o.root,contextDir:o.contextDir,repos:o.repos};if(G.shouldAutoBootstrapModel(o.contextDir)){await G.syncWorkspaceMirrors(M,R=>r.info(R));try{await Oe()}catch(R){r.warn(`[model] auto-bootstrap failed (non-fatal): ${R instanceof Error?R.message:String(R)}`)}return}(await G.rebuildWorkspaceModelIfStale(M,{fetch:U,onLog:R=>r.info(R)})).rebuilt.length>0&&Ce()}catch(G){r.warn(`[model] release-path rebuild failed (non-fatal): ${G instanceof Error?G.message:String(G)}`)}},Ot=U=>{Ee&&clearTimeout(Ee),Ee=setTimeout(()=>void rt(U),6e4)},Lt=setInterval(()=>void rt(!0),6*36e5);return y.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let U=Xp(t.projectId),G=Q("ORIGIN")==="farm"?"farm":"local",M=Q("FARM_ID"),T=t.accountEmail??U.email,R;try{let I=Lm(t.projectId);I&&(R=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let x={type:"register",projectId:t.projectId,platformVersion:Xe,protocolVersion:mt,accountId:U.accountId,accountLabel:U.label,origin:G,inFlightActionIds:[...f],...T?{accountEmail:T}:{},...G==="farm"&&M?{farmId:M}:{},...R?{sealPublicKey:R}:{}};y.send(JSON.stringify(x))}),y.on("message",async U=>{let G=U.toString("utf-8");if(G==="pong"||G==="ping")return;let M;try{M=JSON.parse(G)}catch{return}if(!M||typeof M!="object")return;let T=M.type;if(T==="registered"){let x=M;if(x.ok){if(r.info(`[ws] registered for project ${x.projectId}`),n({kind:"registered",projectId:x.projectId??t.projectId}),C.start(),E.start(),$.start(),_?.start(),se?.start(),A(),Yl(t,o,r),o?.contextDir){try{let I=Ki(o.contextDir,t.projectId);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),d||(d=!0,Nt().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}Ne(),Ot(!0)}}else r.warn(`[ws] register rejected: ${x.reason??"unknown"}`),n({kind:"register_rejected",reason:x.reason??"unknown"}),p=!0,y.close();return}if(T==="hello"){let x=M;k=so(x.protocolVersion);let I=k?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${x.platformVersion} (protocol ${x.protocolVersion}) \u2014 ${I}`),k||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Xe}, protocol ${mt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${ql}`),n({kind:"incompatible",hubVersion:typeof x.platformVersion=="string"?x.platformVersion:null,hubProtocol:typeof x.protocolVersion=="number"?x.protocolVersion:null,updateCommand:ql}));return}if(T==="tracking_targets"){C.setTargets(M.targets),_?.poke();return}if(T==="youtrack_sync_request"){j.setRequest(M);return}if(T==="youtrack_force_sync"){j.forceSync();return}if(T==="sync_local"){await wT(M,o,y,r);return}if(T==="provision_repo"){let x=M;r.info(`[repo] provision_repo: ${x.repo.name} (${x.repo.host}:${x.repo.owner}/${x.repo.repoName})`),await gT(t,o,x.repo,r),await Yl(t,o,r);return}if(T==="remove_repo"){let x=M;r.info(`[repo] remove_repo: ${x.repoName}${x.purge?" (purge)":""}`),await Yl(t,o,r),x.purge&&yT(t,o,x.repoName,r);return}if(T==="context_write"){await bT(M,o,y,r),i();return}if(T==="adr_promote"){await kT(M,o,y,r),i();return}if(T==="cred_update"){let x=M,I=V(t.projectId),X=I?.sealKey?await Mm(t.projectId,x.kind,x.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},H={type:"cred_update_result",updateId:x.updateId,projectId:t.projectId,ok:X.ok,...X.detail?{detail:X.detail}:{}};y.readyState===y.OPEN&&y.send(JSON.stringify(H)),X.ok?(r.info(`[cred] ${x.kind} replaced${X.detail?` \u2014 ${X.detail}`:""}`),K()):r.warn(`[cred] ${x.kind} replacement rejected: ${X.detail??"unknown"}`);return}if(T==="readiness_check"){r.info("[readiness] on-demand check requested"),K();return}if(T==="agent_login_start"){Lf(t,y,M,r,K);return}if(T==="move_to_farm"){let x=M;r.info(`[farm-move] request to move ${t.projectId} onto farm ${x.farmName} (${x.farmId})`);let I=await kg(t,x,o?.contextDir,r);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if(T==="gh_runner_setup"){let x=M;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${x.runnerName} (${x.runnerId})`);let I=await Tg(t,x,r);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${x.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if(T==="gh_runner_teardown"){let x=M;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${x.runnerName} (${x.runnerId})`);let I=await Ig(t,x,r);y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${x.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if(T==="tracker_fields_request"){let x=M,I={type:"tracker_fields_result",requestId:x.requestId,projectId:t.projectId,ok:!1},X=Ct({contextDir:o?.contextDir??null});if(!X.ok)I.error=X.error;else try{I.fields=await X.provider.fetchStateFields(x.projectKey),I.ok=!0}catch(H){I.error=H instanceof Error?H.message:String(H)}y.readyState===y.OPEN&&y.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(T==="project_secret_update"||T==="project_secret_delete"){let x=M,I;if(x.type==="project_secret_update"){let H=V(t.projectId);I=H?.sealKey?jg(t.projectId,x.name,x.sealed,H.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else I=Ng(t.projectId,x.name);let X={type:"project_secret_update_result",updateId:x.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};y.readyState===y.OPEN&&y.send(JSON.stringify(X)),I.ok?(r.info(`[secret] ${x.name} ${x.type==="project_secret_update"?"saved":"deleted"}`+(I.detail?` \u2014 ${I.detail}`:"")),K()):r.warn(`[secret] ${x.name} rejected: ${I.detail??"unknown"}`);return}if(T==="sandbox_keys"){let x=V(t.projectId);if(!x){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=gn(t.projectId),X=Am(M,x,I,r);for(let H of X)y.readyState===y.OPEN&&y.send(JSON.stringify(H));return}if(T!=="dispatch_action")return;let R=M;if(k===!1){let x=`refused: HUB protocol incompatible with CLI v${Xe} (protocol ${mt})`;y.send(JSON.stringify({type:"action_result",actionId:R.actionId,status:"failed",error:x})),r.warn(`[exec] ${R.actionId} (${R.action.type}) \u2192 REFUSED: ${x}`),r.warn(`[exec] update the CLI to clear this: ${ql}`),n({kind:"action",actionId:R.actionId,actionType:R.action.type,ok:!1,error:x});return}if(R.action.type==="model_drift"){f.add(R.actionId);try{let x,I=o?.repos.find(X=>X.name===R.action.repoName);if(!o?.contextDir||!I)x={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:X}=await Promise.resolve().then(()=>(Jg(),Xg)),H=I.mountAs==="."?o.root:Dr(o.root,I.mountAs);x={status:"done",result:{report:await X(H,o.contextDir,I.name)}}}catch(X){x={status:"failed",error:X instanceof Error?X.message:String(X)}}y.send(JSON.stringify({type:"action_result",actionId:R.actionId,...x}))}finally{f.delete(R.actionId)}return}if(R.action.type==="model_bootstrap"){f.add(R.actionId);try{let x;try{let I=await Oe();x={status:"done",result:{repos:I.repos,events:I.events}}}catch(I){x={status:"failed",error:I instanceof Error?I.message:String(I)},r.warn(`[model] bootstrap failed: ${x.error}`)}y.readyState===y.OPEN&&y.send(JSON.stringify({type:"action_result",actionId:R.actionId,...x}))}finally{f.delete(R.actionId)}return}f.add(R.actionId);try{let x=await ng({action:R.action,repo:R.repo,trackerIssueId:R.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:se?()=>se.reportNow():void 0,refreshContextStatus:o?.contextDir?Nt:void 0,onRunActivity:ee}).catch(H=>({status:"failed",error:H instanceof Error?H.message:String(H)}));R.action.type==="tracker_comment"&&x.status==="done"&&"result"in x&&typeof x.result?.commentId=="string"&&w.add(x.result.commentId),y.send(JSON.stringify({type:"action_result",actionId:R.actionId,...x}));let I=x.status!=="failed",X=!I&&"error"in x?x.error:void 0;I?r.info(`[exec] ${R.actionId} (${R.action.type}) \u2192 done`):r.warn(`[exec] ${R.actionId} (${R.action.type}) \u2192 FAILED: ${X??"?"}`),n({kind:"action",actionId:R.actionId,actionType:R.action.type,ok:I,...X?{error:X}:{}}),I&&["apply_delivery","context_write","create_pr"].includes(R.action.type)&&Ce(),I&&["merge_pr","merge_branch"].includes(R.action.type)&&Ot(!0)}finally{f.delete(R.actionId)}}),y.on("close",(U,G)=>{let M=G?.toString("utf-8")??"";if(r.info(`[ws] closed code=${U}${M?` reason=${M}`:""}`),C.stop(),E.stop(),$.stop(),_?.stop(),j.stop(),se?.stop(),h(),clearInterval(Lt),Ee&&clearTimeout(Ee),Be&&clearTimeout(Be),M==="replaced"){p=!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:U}),!p&&setTimeout(()=>{b=v()},2e3)}),y.on("error",U=>r.warn(`[ws] error: ${U.message}`)),y}return{stop(){p=!0,b.close()}}}async function Yl(t,e,r){try{let n=await ie(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Po(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 gT(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?Dr(e.root,o):_e(t.projectId,r.name);if(Zg(Dr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await mT().clone(e?In(r):al(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 yT(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Dr(e.root,o):_e(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Zg(Dr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{fT(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 wT(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=Dr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Uf(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 bT(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 Te(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 kT(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 Qf(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 Vl(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}Ae();de();Wt();Xl();yt();zi();async function uy(t={profile:void 0}){let{cfg:e,profile:r}=hn(t.profile),n=V(e.projectId);n&&$o(n),_o(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Ao(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),jo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Wo(Jl(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Ii("CLI_LOG",i,o);if(s.enabled){let d=new wn(s);Ci(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=fn(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let d=Wo(Jl(),".codepipe",r?Wo("profiles",r,"context"):"context");if(await jl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await cy(()=>js({cfg:e,secrets:n,contextDir:d,log:{info:m=>console.log(m),warn:m=>console.warn(m)}}),{log:{warn:m=>console.warn(m)}}),a||await jl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let m=Wo(Jl(),".codepipe",r?Wo("profiles",r,"context-config"):"context-config");Di(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=_s(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(`
|
|
1056
|
+
[${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Hn();He();Ae();async function Eb(t={profile:void 0}){let e=it(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=ys(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 ie(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=Me(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}ni();import{readFileSync as K_}from"node:fs";D();He();Wt();Qo();Nr();Kt();Ar();Ae();de();function ve(t){throw new Error(t)}function Ie(t,e){return(typeof t!="string"||t.trim().length===0)&&ve(`config: '${e}' must be a non-empty string`),t.trim()}function si(t,e){if(t==null)return;typeof t!="string"&&ve(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function H_(t){(!t||typeof t!="object")&&ve("config: expected a JSON object");let e=t,r=Ie(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ve("config: 'hubUrl' must start with http(s)://");let n=Ie(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ve("config: 'project' is required");let i=o,s=Ie(i.id,"project.id");Jt.test(s)||ve("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Ie(i.name,"project.name"),c=Ie(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ve("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ve("config: 'project.repos' must be an array");let u=l.map((v,y)=>{(!v||typeof v!="object")&&ve(`config: project.repos[${y}] must be an object`);let k=v,C=Ie(k.host,`project.repos[${y}].host`);C!=="github"&&C!=="bitbucket"&&C!=="gitlab"&&ve(`config: project.repos[${y}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:Ie(k.name,`project.repos[${y}].name`),host:C,owner:Ie(k.owner,`project.repos[${y}].owner`),repoName:Ie(k.repoName,`project.repos[${y}].repoName`)},$=si(k.defaultBranch,`project.repos[${y}].defaultBranch`);$&&(E.defaultBranch=$);let _=si(k.mountAs,`project.repos[${y}].mountAs`);return _&&(E.mountAs=_),E}),p=i.contextRepo;(!p||typeof p!="object")&&ve("config: 'project.contextRepo' is required");let d=p,m=si(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&ve("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:Ie(d.owner,"project.contextRepo.owner"),name:si(d.name,"project.contextRepo.name")??Et(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},w=si(i.youtrackProjectKey,"project.youtrackProjectKey");if(w&&(g.project.youtrackProjectKey=w),i.index!==void 0&&(typeof i.index!="boolean"&&ve("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ve("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let v=Ie(i.llmProvider,"project.llmProvider");v==="codex"&&ve(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),v!=="claude"&&ve("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=v}let b=e.secrets;if(b!==void 0){(typeof b!="object"||b===null)&&ve("config: 'secrets' must be an object");let v=b,y={};if(v.github){let k=v.github;y.github={token:Ie(k.token,"secrets.github.token")}}if(v.bitbucket){let k=v.bitbucket;y.bitbucket={email:Ie(k.email,"secrets.bitbucket.email"),apiToken:Ie(k.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let k=v.gitlab;y.gitlab={token:Ie(k.token,"secrets.gitlab.token")}}if(v.youtrack){let k=v.youtrack;y.youtrack={url:Ie(k.url,"secrets.youtrack.url").replace(/\/$/,""),token:Ie(k.token,"secrets.youtrack.token")}}if(v.contextWrite){let k=v.contextWrite;y.contextWrite={token:Ie(k.token,"secrets.contextWrite.token")}}g.secrets=y}return g}async function W_(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function q_(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Zt(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 Qt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await ji(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 er(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await nr({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Dk(t){let e=!t.configPath||t.configPath==="-"?await W_():K_(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){ve(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=H_(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 q_(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 Wn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??yn(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){ve(`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 lr(o,i,a)}catch(d){if(d instanceof W&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await ie(o,i,s.id);else if(d instanceof W)ve(`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(ae(p),Gt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Rt(s.id)}`),ir(s.id,It(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??Je),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Ko(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`)}He();de();import{cancel as Uk,intro as Bk,isCancel as Fk,log as Bu,outro as Y_,password as Gk}from"@clack/prompts";async function V_(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Kk(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await V_(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Bk("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Bu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Gk({message:"Claude OAuth token"});Fk(i)&&(Uk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Hp({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Ti()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=it(t.profile);if(!e){Bk(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Bu.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Gk({message:"Claude OAuth token"});Fk(i)&&(Uk("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=V(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ae(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Bu.success("Claude OAuth token saved."),Y_("It will be sealed into job bundles when a SANDBOX (re)connects."))}Ho();D();He();Wt();Qo();Nr();Vs();Ae();de();import{cancel as z_,confirm as X_,intro as J_,isCancel as Hk,log as De,outro as Z_,select as Wk,text as wr}from"@clack/prompts";function qk(t){z_(t),process.exit(1)}function Jn(t){return Hk(t)&&qk("aborted"),t}function ai(t){return Hk(t)&&qk("aborted"),typeof t=="string"?t:""}async function Q_(t,e){let r=Jn(await Wk({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=ai(await wr({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=ai(await wr({message:"Context Repo name",placeholder:Et(t),initialValue:Et(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Yk(t={profile:void 0}){let e=it(t.profile);J_(`codepipe project add \u2192 ${e.hubUrl}`);let r=Jn(await wr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>Jt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Jn(await wr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Jn(await Wk({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=Jn(await wr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Jn(await X_({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=ai(await wr({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:b=>!b||!b.trim()||Ve(b)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=Ve(d);De.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=ai(await wr({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:b=>b.trim().length>0?void 0:"required"})).trim(),g=ai(await wr({message:"default branch (optional)",placeholder:"main"})).trim(),w={name:f,host:m.host,owner:m.owner,repoName:m.repoName};g&&(w.defaultBranch=g),a.push(w)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Q_(r,a),u=V(e.projectId);De.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Wn(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??yn(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>De.message(d),warn:d=>De.warn(d)}})}catch(d){De.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,De.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await lr(e.hubUrl,e.cliToken,c);De.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),ir(r,It(c,s,u?.youtrack?.url),{info:m=>De.message(m),warn:m=>De.warn(m)}),d.contextRepo&&(De.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),De.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&De.error(` error: ${d.provisioningError}`),Z_("done")}catch(d){d instanceof W?(De.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&De.message(JSON.stringify(d.payload,null,2))):De.error(d instanceof Error?d.message:String(d)),process.exit(1)}}Hn();He();Ae();de();yt();ni();import{existsSync as eA,rmSync as tA}from"node:fs";import{confirm as rA,intro as nA,isCancel as oA,log as br,outro as iA,spinner as sA}from"@clack/prompts";function jt(t){br.error(t),process.exit(1)}var Vk=t=>t.trim().replace(/\/+$/,"");async function zk(t){nA("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Pe()?.spec.projectId??void 0;e||jt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=wt(e);r||jt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Vk(r.hubUrl),o=r.projectId,i=Vk(t.hub);i.startsWith("http")||jt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&jt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let b=sA();b.start(`reading project ${o} from ${n}\u2026`);try{l=await ie(n,r.cliToken,o),b.stop(`read project ${o} (${l.name})`)}catch(v){throw b.stop("could not read the source project",1),v instanceof W&&jt(`source HUB ${n} \u2192 ${v.status} ${v.message}. The source HUB must be reachable with a valid token to move a project.`),v}}l.contextRepo||jt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=V(o),p=(t.account??r.accountEmail??await zn()).trim().toLowerCase();if(br.message(`move project '${o}'
|
|
1057
1057
|
from : ${n} (profile ${e})
|
|
1058
1058
|
to : ${i} (profile ${s}, project ${a}, account ${p})
|
|
1059
1059
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
1060
1060
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
1061
|
-
`+(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
|
|
1062
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let
|
|
1063
|
-
re-run the command or set the git-flow manually in project.yaml`)}}
|
|
1064
|
-
`)[0]:String(e)}`)}}
|
|
1065
|
-
`))}async function
|
|
1066
|
-
`)}`:" (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}
|
|
1067
|
-
`),t.unread+=1,
|
|
1061
|
+
`+(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 b=await rA({message:"Continue?",initialValue:!0});(oA(b)||!b)&&jt("aborted")}!c&&a===o&&br.warn(`source and destination share the same project id, so they share one secrets file (${Rt(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:m}=await Xn(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};br.step(`registering project on ${i}\u2026`);let g;try{g=await lr(i,d,f)}catch(b){if(b instanceof W&&b.status===409){br.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await ie(i,d,a)}catch(v){throw v instanceof W&&jt(`target HUB \u2192 ${v.status} ${v.message}`),v}}else if(b instanceof W&&b.status===403)jt(`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(b instanceof W)jt(`target HUB \u2192 ${b.status} ${b.message}`);else throw b}br.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),Gt({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let w={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete w.sandboxPins,ae(w),br.success(`profile '${s}' \u2192 ${Rt(a)}`),c){let b=vt(s);eA(b)&&(tA(b),br.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}iA(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}D();He();import{existsSync as Fu,rmSync as aA,statSync as cA}from"node:fs";import{join as ci,relative as lA,resolve as uA}from"node:path";import{cancel as dA,intro as Jk,isCancel as pA,log as ye,outro as Zk,text as qr}from"@clack/prompts";import{simpleGit as Qk}from"simple-git";_u();Au();Vs();Ae();Cn();de();yt();function ze(t){dA(t),process.exit(1)}function Yr(t){return pA(t)&&ze("aborted"),typeof t=="string"?t:""}async function Xk(t){try{let e=await Qk(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function fA(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function mA(t,e){let r=V(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(fA(r,e)){ye.message(`reusing existing ${e} credentials`);return}if(ye.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Yr(await qr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Yr(await qr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Yr(await qr({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}}ae(r),ye.success(`saved ${e} credentials`)}async function ev(t){let e=it(t.profile);Jk(`codepipe repo add \u2192 project ${e.projectId}`);let r=Pe()??void 0,n;try{n=(await ie(e.hubUrl,e.cliToken,e.projectId)).repos}catch(k){ze(`could not read project from HUB: ${k instanceof Error?k.message:String(k)}`)}let o=t.target?.trim();if(!o){let k=await Xk(process.cwd());k?(o=process.cwd(),ye.message(`using the current directory (${k})`)):o=Yr(await qr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:C=>C.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Fu(o)&&cA(o).isDirectory()){i=uA(o);let k=await Xk(i);k||ze(`${i} is not a git repository (no origin remote)`);let C=Ve(k);C||ze(`origin ${k} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=C,s=k,ye.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let k=Ve(o);k||ze(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=k,s=o,ye.message(`${a}: ${c}/${l}`)}let u=Yr(await qr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:k=>k.trim()?void 0:"required"})).trim();n.some(k=>k.name===u)&&ze(`a repo named "${u}" is already registered`);let p;i&&(p=await ri(i,s));let d=p?yo(p).branches.integration:"",m=Yr(await qr({message:"default branch (optional)",placeholder:d||"main",...d?{initialValue:d}:{}})).trim(),f=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let k=lA(r.root,i);f=k===""?".":k}let g=Yr(await qr({message:"mount_as (directory relative to the workspace root)",placeholder:f,initialValue:f})).trim()||f;n.some(k=>(k.mountAs??k.name)===g)&&ze(`mount_as "${g}" is already used by another repo`),await mA(e,a);let w={name:u,host:a,owner:c,repoName:l,mountAs:g,...m?{defaultBranch:m}:{}};if(!i){let k=r?ci(r.root,g):_e(e.projectId,u);if(Fu(ci(k,".git")))ye.message(`already cloned at ${k}`);else{ye.info(`cloning ${s} \u2192 ${k} \u2026`);try{await Qk().clone(s,k),ye.success(`cloned into ${k}`)}catch(C){ze(`clone failed: ${C instanceof Error?C.message.trim():String(C)}
|
|
1062
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let b;try{b=await hg(e.hubUrl,e.cliToken,e.projectId,w)}catch(k){k instanceof W&&ze(`HUB \u2192 ${k.status} ${k.message}`),ze(k instanceof Error?k.message:String(k))}let{updated:v,errors:y}=Po(e.projectId,b.repos,r?.contextDir);for(let k of v)ye.message(`updated ${k}`);for(let k of y)ye.warn(`could not update ${k.path}: ${k.error}`);if(r?.contextDir){if(!p)try{let k=i??ci(r.root,g);p=await ri(k,s)}catch(k){ye.warn(`git-flow detection skipped: ${k instanceof Error?k.message:String(k)}`),p={defaultBranch:null,branches:[]}}try{await Js({contextDir:r.contextDir,repoName:u,facts:p,log:k=>ye.message(k)})}catch(k){ze(`"${u}" was added, but its git-flow choice was NOT saved: ${k instanceof Error?k.message.trim():String(k)}
|
|
1063
|
+
re-run the command or set the git-flow manually in project.yaml`)}}ye.success(`added "${u}" \u2014 project now has ${b.repos.length} repo(s)`),Zk("done")}async function tv(t){let e=it(t.profile);Jk(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Pe()??void 0,n;try{let c=(await ie(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 gg(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof W&&(a.status===404&&ze(`no repo named "${t.name}" in this project`),ze(`HUB \u2192 ${a.status} ${a.message}`)),ze(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Po(e.projectId,o.repos,r?.contextDir);for(let a of i)ye.message(`updated ${a}`);for(let a of s)ye.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ye.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?ci(r.root,n):_e(e.projectId,t.name);if(Fu(ci(a,".git")))try{aA(a,{recursive:!0,force:!0}),ye.message(`deleted local clone ${a}`)}catch(c){ye.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ye.message(`no local clone found to purge (${a})`)}ye.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Zk("done")}async function rv(t){let e=it(t.profile),r;try{r=(await ie(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}`)}}Xs();He();Gi();Ae();import{existsSync as hA}from"node:fs";import{join as gA}from"node:path";import{simpleGit as yA}from"simple-git";yt();var wA=60;async function nv(t){let{cfg:e}=hn(t.profile),r=fn(e.projectId);if(!r)throw new Error(`no workspace for ${e.projectId} here \u2014 run this from the project folder (the one with .codepipe/)`);let n=new Set,o={info:a=>console.log(a),warn:a=>console.warn(a)},i=async()=>{let a=await ks(e.hubUrl,e.cliToken,e.projectId);if(a.length===0){console.log("[pull] nothing ready yet");return}for(let c of a)await Ll(r.root,r.spec.repos,c,n,o);if(await bA(r.contextDir),r.contextDir)try{Sn(r.contextDir,r.root,{info:c=>console.log(`[pull] ${c}`),warn:c=>console.warn(`[pull] ${c}`)})}catch(c){console.warn(`[pull] skills materialize failed \u2014 ${c instanceof Error?c.message:String(c)}`)}};if(!t.watch){await i();return}try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}let s=Math.max(10,t.intervalSec??wA)*1e3;for(console.log(`[pull] watching \u2014 every ${Math.round(s/1e3)}s, Ctrl+C to stop`);;){await new Promise(a=>setTimeout(a,s));try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}}}async function bA(t){if(!(!t||!hA(gA(t,".git"))))try{await yA(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
|
|
1064
|
+
`)[0]:String(e)}`)}}ra();import{existsSync as cv,mkdirSync as kA,readFileSync as vA,writeFileSync as $A}from"node:fs";import{homedir as xA}from"node:os";import{dirname as SA,join as lv}from"node:path";import*as Qn from"node:readline";Ae();qi();de();yt();Xs();ra();var sa=lv(xA(),".codepipe","history"),ov=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],uv=500,iv=40;async function dv(t={}){let e=Pe();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=V(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)),$o(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."),console.log("");let n=Qn.createInterface({input:process.stdin,output:process.stdout,completer:EA,history:BA(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};vm(i=>kr(o,i)),o.daemon=_s({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>kr(o,i),warn:i=>kr(o,i)},onEvent:i=>LA(o,i),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos}});try{let i={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await Qs(i,t.profile,{profile:t.profile});let s=process.argv[1];if(!s)throw new Error("cannot resolve the codepipe entry script for the worker process");let a=ea({entry:s,profile:t.profile,onLine:c=>kr(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!Hu&&Zn(o,`[worker] exited (code ${c??(l?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),o.workerChild=a,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(i){console.warn(`[worker] could not start the embedded worker (${i instanceof Error?i.message:String(i)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}Ku(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await RA(o,s)){av(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,Ku(o),n.prompt()}),n.on("close",()=>{av(o)})}function EA(t){let e=ov.filter(r=>r.startsWith(t));return[e.length?e:ov,t]}async function RA(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return TA(),!1;case"/status":return await IA(t),!1;case"/tasks":return await CA(t,n),!1;case"/task":return await PA(t,n),!1;case"/sync":return await _A(t),!1;case"/logs":return MA(t,n),!1;case"/monitor":return DA(t),!1;case"/approve":return await sv(t,n,"approve"),!1;case"/merge":return await sv(t,n,"merge"),!1;case"/login":return AA(t,n),!1;case"/secret":return jA(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function TA(){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)","/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(`
|
|
1065
|
+
`))}async function IA(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=cv(lv(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function CA(t,e){let r=UA(e,"--phase");try{let n=await pg(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){Wu(n)}}async function PA(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await fg(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){Wu(n)}}async function _A(t){let e=await ti(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 sv(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await mg(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Wu(o)}}function AA(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},ae(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 jA(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(`
|
|
1066
|
+
`)}`:" (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}NA(t.secrets,n,i),ae(t.secrets),$o(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}OA(t.secrets,n),ae(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function NA(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 OA(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 LA(t,e){switch(e.kind){case"connected":t.connection="connecting",kr(t,"[hub] connected");break;case"registered":t.connection="registered",kr(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Zn(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",kr(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Zn(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Zn(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?kr(t,`[hub] action ${e.actionType} done`):Zn(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function kr(t,e){t.logBuffer.push(e),t.logBuffer.length>uv&&t.logBuffer.shift(),t.follow&&Zn(t,e)}function MA(t,e){let r=e[0];if(r==="follow"||r==="on"){Gu(t,!0);return}if(r==="off"){Gu(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(uv,Number(r)||iv)):iv,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 DA(t){Gu(t,!t.follow)}function Gu(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Zn(t,e){Qn.cursorTo(process.stdout,0),Qn.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
1067
|
+
`),t.unread+=1,Ku(t),t.rl.prompt(!0)}function Ku(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Hu=!1;function av(t){if(Hu)return;Hu=!0,FA(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
|
|
1068
1068
|
bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
|
|
1069
|
-
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
|
|
1069
|
+
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 UA(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Wu(t){t instanceof W?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function BA(){if(!cv(sa))return[];try{return vA(sa,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function FA(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{kA(SA(sa),{recursive:!0}),$A(sa,r.slice().reverse().join(`
|
|
1070
1070
|
`)+`
|
|
1071
|
-
`)}catch{}}Gn();D();He();Gn();We();Ne();ri();import{hostname as UA}from"node:os";import{cancel as BA,confirm as dv,intro as FA,isCancel as mv,log as Zn,multiselect as GA,outro as pv,password as KA,select as Wu,text as qu}from"@clack/prompts";function ci(t){BA(t),process.exit(1)}function Qn(t){return mv(t)&&ci("aborted"),t}function sa(t){return mv(t)&&ci("aborted"),typeof t=="string"?t:""}function aa(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function fv(t,e){try{let{secret:r}=await bs(t,e);return r}catch(r){throw r instanceof K&&r.status===404&&ci("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 HA(t,e){if(Qn(await Wu({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 _l(t,e);if(o.length>0)return Qn(await GA({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}));Zn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Zn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return sa(await qu({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 Yu(t){FA("codepipe worker \u2014 set up this machine as a runner");let e=De(t.profile);e&&(Zn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Qn(await dv({message:"re-register this worker?",initialValue:!1}))||ci("keeping the existing registration"));let r=kt(t.profile)??kt(),n=sa(await qu({message:"HUB URL",placeholder:ht,initialValue:Q("HUB_URL")??r?.hubUrl??ht,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Qn(await Wu({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 fv(n,a),Zn.success("account-issued registration token minted");else if(i==="login"){let d=await Yn();a=(await Vn(n,d)).cliToken,s=await fv(n,a),Zn.success("account-issued registration token minted")}else s=sa(await KA({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||ci("a registration token is required");let c=await HA(n,a),l=sa(await qu({message:"worker name",initialValue:UA(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Qn(await Wu({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 Dr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Zn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Qn(await dv({message:"start the claim-loop now?",initialValue:!0}))){pv("registered. start later with `codepipe worker`.");return}pv("starting the claim-loop\u2026"),await Jo(t.profile?{profile:t.profile}:{})}function qA(){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 ke=qA();_p(ke);var Be=new WA;Be.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Je).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{aa()?await uv({profile:ke}):await ea({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Be.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 Mk({configPath:t.config,skipVerify:t.skipVerify===!0}):await Ek({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.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 Hp({...t,profile:ke})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.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 Tk({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Be.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await ly({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Be.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 ek({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.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 Gk({profile:ke,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Sb({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Be.command("pull").description("Fetch finished task branches into your local clones (no checkout switch)").option("--profile <name>","Config profile").option("--watch","Keep pulling instead of exiting after one pass").option("--interval <sec>","Watch interval in seconds (default 60, minimum 10)",t=>parseInt(t,10)).action(async t=>{if(t.interval!==void 0&&!Number.isFinite(t.interval))throw new Error("--interval expects a number of seconds");await rv({profile:t.profile,...t.watch?{watch:!0}:{},...Number.isFinite(t.interval)?{intervalSec:t.interval}:{}})});Be.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).option("--debug [categories]","Write local debug logs (comma-separated categories; default: agent-request \u2014 the full prompt and context each agent job receives, under ~/.codepipe/debug/)").action(async t=>{try{await ea({profile:ke,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var hv=Be.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");hv.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")??kt(ke)?.hubUrl??ht,r=t.token??Q("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&aa()){await Yu({profile:ke});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 Dr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ke?{profile:ke}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});hv.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!De(ke)&&aa()){await Yu({profile:ke});return}await Jo(ke?{profile:ke}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var gv=Be.command("project").description("Manage CodePipe projects");gv.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await qk({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});gv.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 Vk({...t,cliProfile:ke})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Vu=Be.command("repo").description("Manage the project's git repositories");Vu.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 Qk({profile:ke,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Vu.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 ev({profile:ke,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Vu.command("list").description("List the project's repos").action(async()=>{try{await tv({profile:ke})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var yv=Be.command("model").description("Project map (model/ in the Context Repo)");yv.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 Ul({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});yv.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 Bl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Be.parseAsync();
|
|
1071
|
+
`)}catch{}}Hn();D();Ke();Hn();He();Ae();ni();import{hostname as GA}from"node:os";import{cancel as KA,confirm as pv,intro as HA,isCancel as hv,log as eo,multiselect as WA,outro as fv,password as qA,select as qu,text as Yu}from"@clack/prompts";function li(t){KA(t),process.exit(1)}function to(t){return hv(t)&&li("aborted"),t}function aa(t){return hv(t)&&li("aborted"),typeof t=="string"?t:""}function ca(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function mv(t,e){try{let{secret:r}=await bs(t,e);return r}catch(r){throw r instanceof W&&r.status===404&&li("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 YA(t,e){if(to(await qu({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 Al(t,e);if(o.length>0)return to(await WA({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}));eo.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){eo.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return aa(await Yu({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 Vu(t){HA("codepipe worker \u2014 set up this machine as a runner");let e=Me(t.profile);e&&(eo.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),to(await pv({message:"re-register this worker?",initialValue:!1}))||li("keeping the existing registration"));let r=wt(t.profile)??wt(),n=aa(await Yu({message:"HUB URL",placeholder:ft,initialValue:Q("HUB_URL")??r?.hubUrl??ft,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=to(await qu({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 mv(n,a),eo.success("account-issued registration token minted");else if(i==="login"){let d=await zn();a=(await Xn(n,d)).cliToken,s=await mv(n,a),eo.success("account-issued registration token minted")}else s=aa(await qA({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||li("a registration token is required");let c=await YA(n,a),l=aa(await Yu({message:"worker name",initialValue:GA(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=to(await qu({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 Ur({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),eo.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!to(await pv({message:"start the claim-loop now?",initialValue:!0}))){fv("registered. start later with `codepipe worker`.");return}fv("starting the claim-loop\u2026"),await Zo(t.profile?{profile:t.profile}:{})}function zA(){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 we=zA();Ap(we);var Ue=new VA;Ue.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Xe).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{ca()?await dv({profile:we}):await ta({profile:we})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ue.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 Dk({configPath:t.config,skipVerify:t.skipVerify===!0}):await Rk({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.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 Wp({...t,profile:we})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.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 Tk({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ue.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await uy({profile:we})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ue.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 tk({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.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 Kk({profile:we,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Eb({profile:we})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ue.command("pull").description("Fetch finished task branches into your local clones (no checkout switch)").option("--profile <name>","Config profile").option("--watch","Keep pulling instead of exiting after one pass").option("--interval <sec>","Watch interval in seconds (default 60, minimum 10)",t=>parseInt(t,10)).action(async t=>{if(t.interval!==void 0&&!Number.isFinite(t.interval))throw new Error("--interval expects a number of seconds");await nv({profile:t.profile,...t.watch?{watch:!0}:{},...Number.isFinite(t.interval)?{intervalSec:t.interval}:{}})});Ue.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).option("--debug [categories]","Write local debug logs (comma-separated categories; default: agent-request \u2014 the full prompt and context each agent job receives, under ~/.codepipe/debug/)").action(async t=>{try{await ta({profile:we,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var gv=Ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");gv.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")??wt(we)?.hubUrl??ft,r=t.token??Q("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ca()){await Vu({profile:we});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 Ur({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...we?{profile:we}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});gv.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Me(we)&&ca()){await Vu({profile:we});return}await Zo(we?{profile:we}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var yv=Ue.command("project").description("Manage CodePipe projects");yv.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Yk({profile:we})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});yv.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 zk({...t,cliProfile:we})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var zu=Ue.command("repo").description("Manage the project's git repositories");zu.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 ev({profile:we,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});zu.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 tv({profile:we,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});zu.command("list").description("List the project's repos").action(async()=>{try{await rv({profile:we})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var wv=Ue.command("model").description("Project map (model/ in the Context Repo)");wv.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 Bl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});wv.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 Fl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.parseAsync();
|