@code-partner/codepipe 0.8.2-dev.199.g6402531 → 0.8.2-dev.204.g1769c26

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.
Files changed (2) hide show
  1. package/dist/index.js +185 -178
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,55 +1,55 @@
1
1
  #!/usr/bin/env node
2
- var vk=Object.defineProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var Rr=(t,e)=>{for(var r in e)vk(t,r,{get:e[r],enumerable:!0})};var Ue,st,ys=x(()=>{"use strict";Ue="0.8.2-dev.199.g6402531",st="https://hub.dev.codepipe.dev"});function To(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=xk&&t<=at}var at,xk,ol=x(()=>{"use strict";ys();at=4,xk=4});var il=x(()=>{"use strict";ys()});function Ro(t=4){return`# CodePipe Context Repo format version.
2
+ var jk=Object.defineProperty;var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var Rr=(t,e)=>{for(var r in e)jk(t,r,{get:e[r],enumerable:!0})};var Ue,ct,$s=v(()=>{"use strict";Ue="0.8.2-dev.204.g1769c26",ct="https://hub.dev.codepipe.dev"});function Ro(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Nk&&t<=lt}var lt,Nk,ul=v(()=>{"use strict";$s();lt=4,Nk=4});var dl=v(()=>{"use strict";$s()});function Io(t=4){return`# CodePipe Context Repo format version.
3
3
  # Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
4
4
  template_version: ${t}
5
- `}function al(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 cl(t,e=sl){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 ll(t,e=sl){return e.filter(r=>r.version>t)}var ct,An,sl,ul=x(()=>{"use strict";ct=".codepipe-context.yaml",An=".devpipe-context.yaml",sl=[{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",ct]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[ct]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]}]});function Io(t){return`model/facts/identity/${t}.yaml`}function Cr(t){return`model/facts/events/${t}.yaml`}function dl(t){return`model/facts/annotations/${t}.md`}function pl(t){return`model/derived/correlates/${t}.yaml`}function fl(t){return`model/derived/touched/${t}.yaml`}function Sk(t){return t===""?"root":t.replace(/\//g,"-")}function ml(t,e){return`model/derived/structure/${t}/${Sk(e)}.yaml`}function $s(t){return typeof t=="string"&&Rk.test(t)}function Q(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!Tk.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Ik.includes(n)||i===""?null:{level:n,repo:o,path:i}}function ke(t){return`task::${t}`}function pe(t,e,r){return`${t}:${e}:${r}`}function Eo(t){let e=[];return lt(t)?(Co(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(!lt(r)){e.push(`edges[${n}]: not an object`);return}hl.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),Q(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),Q(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function Ek(t){return{...t,edges:Ir(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function Ar(t){return _r(Ek(t))}function lt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Co(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function Ve(t){return typeof t=="string"&&t.length>0}function Et(t){let e=[];if(!lt(t))return{ok:!1,errors:["shard: not an object"]};Co(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ve(t.repo)||e.push("repo: missing or empty"),Ve(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(!lt(o)){e.push(`nodes[${i}]: not an object`);return}let s=Q(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!$s(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(!lt(o)){e.push(`edges[${i}]: not an object`);return}hl.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!Ve(o.to)||!Q(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!Ve(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 Ao(t){let e=[];if(!lt(t))return{ok:!1,errors:["identity: not an object"]};if(Co(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ve(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!Ve(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(!lt(n)){e.push(`entities[${o}]: not an object`);return}$s(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),Q(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),Ve(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),Ve(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!lt(i)||!Q(i.key)||!Ve(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 Ct(t){let e=[];return lt(t)?(Co(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ve(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=>!Ve(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!lt(r)||!Q(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!$s(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 Ir(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Ck(t){return{...t,nodes:Ir(t.nodes,e=>e.key),edges:Ir(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Ak(t){return{...t,entities:Ir(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Ir(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Pk(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:Ir(t.files,r=>r.key),...e?{links:e}:{}}}function Pn(t){return _k.test(t)?t:JSON.stringify(t)}function bl(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 $l(t){return t===null||["boolean","number","string"].includes(typeof t)}function ks(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function vl(t,e,r){if(Array.isArray(t)){for(let n of t)if($l(n))r.push(`${e}- ${bl(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=ks(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;ws(i,s,c,`${e} `,r)})}}return}for(let[n,o]of ks(t))ws(n,o,e,e,r)}function ws(t,e,r,n,o){if($l(e))o.push(`${r}${Pn(t)}: ${bl(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${Pn(t)}: []`):(o.push(`${r}${Pn(t)}:`),vl(e,`${n} `,o));else{let i=ks(e);if(i.length===0)o.push(`${r}${Pn(t)}: {}`);else{o.push(`${r}${Pn(t)}:`);for(let[s,a]of i)ws(s,a,`${n} `,`${n} `,o)}}}function _r(t){let e=[];return vl(t,"",e),e.join(`
5
+ `}function fl(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 ml(t,e=pl){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 gl(t,e=pl){return e.filter(r=>r.version>t)}var ut,Pn,pl,hl=v(()=>{"use strict";ut=".codepipe-context.yaml",Pn=".devpipe-context.yaml",pl=[{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",ut]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[ut]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]}]});function Co(t){return`model/facts/identity/${t}.yaml`}function Ar(t){return`model/facts/events/${t}.yaml`}function yl(t){return`model/facts/annotations/${t}.md`}function kl(t){return`model/derived/correlates/${t}.yaml`}function wl(t){return`model/derived/touched/${t}.yaml`}function Ok(t){return t===""?"root":t.replace(/\//g,"-")}function bl(t,e){return`model/derived/structure/${t}/${Ok(e)}.yaml`}function Ts(t){return typeof t=="string"&&Lk.test(t)}function Q(t){if(typeof t!="string")return null;let e=t.indexOf(":");if(e<=0)return null;let r=t.indexOf(":",e+1);if(r<0)return null;let n=t.slice(0,e);if(!Dk.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!Mk.includes(n)||i===""?null:{level:n,repo:o,path:i}}function be(t){return`task::${t}`}function fe(t,e,r){return`${t}:${e}:${r}`}function Ao(t){let e=[];return dt(t)?(Po(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(!dt(r)){e.push(`edges[${n}]: not an object`);return}$l.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),Q(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),Q(r.to)||e.push(`edges[${n}].to: malformed nodeKey`),r.weight!==void 0&&!(typeof r.weight=="number"&&Number.isFinite(r.weight))&&e.push(`edges[${n}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}):{ok:!1,errors:["edge sheet: not an object"]}}function Uk(t){return{...t,edges:Ir(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function Pr(t){return jr(Uk(t))}function dt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Po(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function Ve(t){return typeof t=="string"&&t.length>0}function It(t){let e=[];if(!dt(t))return{ok:!1,errors:["shard: not an object"]};Po(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ve(t.repo)||e.push("repo: missing or empty"),Ve(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(!dt(o)){e.push(`nodes[${i}]: not an object`);return}let s=Q(o.key);if(!s){e.push(`nodes[${i}].key: malformed nodeKey (${JSON.stringify(o.key??null)})`);return}o.level!==s.level&&e.push(`nodes[${i}]: level "${String(o.level)}" does not match key prefix "${s.level}"`),r&&s.repo!==r&&e.push(`nodes[${i}].key: repo "${s.repo}" mixed into shard of repo "${r}"`);let a=o.key;n.has(a)&&e.push(`nodes[${i}].key: duplicate "${a}"`),n.add(a),o.entityId!==void 0&&!Ts(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(!dt(o)){e.push(`edges[${i}]: not an object`);return}$l.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!Ve(o.to)||!Q(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!Ve(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 _o(t){let e=[];if(!dt(t))return{ok:!1,errors:["identity: not an object"]};if(Po(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ve(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!Ve(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(!dt(n)){e.push(`entities[${o}]: not an object`);return}Ts(n.entityId)?r.has(n.entityId)?e.push(`entities[${o}].entityId: duplicate "${n.entityId}"`):r.add(n.entityId):e.push(`entities[${o}].entityId: malformed (${JSON.stringify(n.entityId??null)})`),Q(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),Ve(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),Ve(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!dt(i)||!Q(i.key)||!Ve(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 Ct(t){let e=[];return dt(t)?(Po(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ve(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=>!Ve(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!dt(r)||!Q(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Ts(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 Ir(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Bk(t){return{...t,nodes:Ir(t.nodes,e=>e.key),edges:Ir(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Fk(t){return{...t,entities:Ir(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:Ir(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Gk(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:Ir(t.files,r=>r.key),...e?{links:e}:{}}}function _n(t){return Kk.test(t)?t:JSON.stringify(t)}function El(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 Rl(t){return t===null||["boolean","number","string"].includes(typeof t)}function vs(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Il(t,e,r){if(Array.isArray(t)){for(let n of t)if(Rl(n))r.push(`${e}- ${El(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=vs(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;xs(i,s,c,`${e} `,r)})}}return}for(let[n,o]of vs(t))xs(n,o,e,e,r)}function xs(t,e,r,n,o){if(Rl(e))o.push(`${r}${_n(t)}: ${El(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${_n(t)}: []`):(o.push(`${r}${_n(t)}:`),Il(e,`${n} `,o));else{let i=vs(e);if(i.length===0)o.push(`${r}${_n(t)}: {}`);else{o.push(`${r}${_n(t)}:`);for(let[s,a]of i)xs(s,a,`${n} `,`${n} `,o)}}}function jr(t){let e=[];return Il(t,"",e),e.join(`
6
6
  `)+`
7
- `}function xl(t){return _r(Ck(t))}function Sl(t){return _r(Ak(t))}function _n(t){return _r(Pk(t))}var bs,Er,Tk,hl,Rk,Ik,ze,gl,yl,kl,vs,wl,Pr,_k,xs=x(()=>{"use strict";bs="model/derived/INDEX.yaml",Er="model/derived/relates.yaml";Tk=["system","container","component","code","task","adr"],hl=["contains","touched_by","correlates","relates","references","depends_on"],Rk=/^e_[0-9a-f]{8}$/;Ik=["system","task","adr"];ze={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};gl=2,yl=5,kl=50,vs=2e3,wl={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},Pr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};_k=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var Tl=x(()=>{"use strict"});var jk,WI,Rl=x(()=>{"use strict";jk=[{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"]}],WI=jk.flatMap(t=>t.phases)});function tr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Il,Ss=x(()=>{"use strict";Il=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function El(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Pl(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Ok.every(o=>e.some(i=>El(o,i.id))))return null;let n=[...e].sort((o,i)=>{let s=o.createdAt??"",a=i.createdAt??"";return s!==a?s<a?1:-1:o.id<i.id?1:-1});for(let o of Nk){let i=n.find(s=>El(o,s.id));if(i)return i.id}return n[0].id}var ut,Cl,Je,jn,Al,Ts,Rs,Nk,Ok,Is=x(()=>{"use strict";ut="claude",Cl=[ut],Je="opus",jn="sonnet",Al="haiku",Ts=[Je,jn,Al],Rs={analyze:Je,implement:Je,"resolve-conflict":Je,rework:Je,estimate:jn,build:jn,"code-review":Je,draft:jn,index:Je,backfill:Je,analysis:Je,chat:Je},Nk=[Je,jn,Al],Ok=Array.from(new Set(Object.values(Rs)))});function At(t){return Dk.has(t)?!0:Lk.some(e=>t.startsWith(e))}function Po(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 Es(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Dl(t,e){let r=Po(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=rr(r.id,"id")??n;if(!_l.test(o))throw new Error(`id must match ${_l} (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=Po(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Be.test(d))throw new Error(`env name "${d}" must match ${Be}`);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>jl)throw new Error(`too many params (max ${jl})`);let p=new Set;a=c.map((d,m)=>Mk(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>Nl)throw new Error(`too many steps (max ${Nl})`);let u=l.map((p,d)=>{let m=Po(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 h=rr(m.name,`steps[${d}].name`),k=Es(m.timeout_sec,`steps[${d}].timeout_sec`);if(k!==void 0&&(!Number.isInteger(k)||k<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:f,...h?{name:h}:{},...k!==void 0?{timeout_sec:k}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function Mk(t,e,r){let n=Po(t,`params[${e}]`),o=rr(n.name,`params[${e}].name`);if(!o||!Be.test(o))throw new Error(`params[${e}].name must match ${Be}`);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=Es(n.min,`params[${e}].min`),p=Es(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 Ll(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 Be,Dk,Lk,Ol,_l,jl,Nl,Cs=x(()=>{"use strict";Be=/^[A-Z][A-Z0-9_]*$/,Dk=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Lk=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Ol=600,_l=/^[a-z0-9-]+$/,jl=32,Nl=64});function Fl(t=Uk){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Fl(r.groups));return e}function Bk(t,e){let r=JSON.stringify(e);return Fl().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Kl(t){let e=Bk(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Ml)return{ok:!1,error:`${e.id} must have \u2264 ${Ml} entries`};let s={};for(let[a,c]of i){if(!Be.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Be}`};if(At(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>Ul)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Ul} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Ml,Ul,Bl,Uk,Gl=x(()=>{"use strict";Cs();Ss();Is();xs();Ml=64,Ul=2e3,Bl=2e3,Uk=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{id:"llm",label:"LLM",fields:[{id:"llm.provider",file:"regimen.yaml",path:["llm","provider"],type:"enum",label:"Provider",nullable:!1,suggestions:[...Cl],help:"LLM backend for this project. Currently only claude is available."}],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Ts],help:"Overrides the recommended defaults for every role not listed below."},...Il.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Ts],help:`recommended: ${Rs[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:Bl,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:Bl,help:'e.g. "Russian, implementation details, bullet list of what was done". Empty \u21D2 the default PR body.'}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${ze.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 ${ze.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 ${ze.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 ${ze.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 ${ze.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 ${ze.topK}.`}]},{id:"implementation",label:"Implementation",help:"How a dependency cluster is serialized into branches and PRs.",fields:[{id:"implementation.mode",file:"regimen.yaml",path:["implementation","mode"],type:"enum",label:"Implementation mode",nullable:!0,suggestions:["cluster-pr","sequential","parallel"],help:"cluster-pr (default for new projects) \u2014 one shared branch and a single PR per dependency cluster; a lone task is a cluster of one. sequential / parallel are an explicit opt-out of that. Clearing removes the key from regimen.yaml but keeps the mode already stored for the project (it is not reset to the default)."}]}]});var Hl=x(()=>{"use strict"});var Wl=x(()=>{"use strict"});var Yl=x(()=>{"use strict"});function ql(t){return`codepipe-host-${t}`}var Vl=x(()=>{"use strict"});function zl(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 bt(t){return`${t}${Fk}`}var nr,Fk,Jl=x(()=>{"use strict";nr=/^[a-z][a-z0-9-]{1,30}$/,Fk="-codepipe-ctx"});var Xl=x(()=>{"use strict"});var Ql=x(()=>{"use strict"});function jr(t){for(let e of Kk){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Kk,Zl=x(()=>{"use strict";Kk=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}]});var eu=x(()=>{"use strict"});var tu=x(()=>{"use strict"});var ru=x(()=>{"use strict"});function nu(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function iu(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=nu(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Nr.test(r))return r;let n=nu(t);return Nr.test(n)?n:As}function su(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 On(t){return`tasks/${t}/issue.yaml`}var ou,_o,As,Nr,Ps,aE,jo,Nn,au=x(()=>{"use strict";ou=["bug","feature","epic"],_o="feature",As="TASK",Nr=/^[A-Z][A-Z0-9]{1,9}$/;Ps={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},aE=Ps.backlog,jo="tracker/config.yaml",Nn="tracker/counter"});var cu=x(()=>{"use strict"});function Or(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 No(t){switch(t){case Dn.gitlab:return"oauth2";case Dn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Dn,or,lu=x(()=>{"use strict";Dn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};or="x-bitbucket-api-token-auth"});var uu=x(()=>{"use strict"});var du=x(()=>{"use strict";cu();lu();uu()});var pu,K=x(()=>{"use strict";ol();il();ul();xs();Tl();Rl();Ss();Is();Gl();Cs();Hl();Wl();Yl();Vl();Jl();Xl();Ql();Zl();eu();tu();ru();au();du();pu=20});function Y(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ae=x(()=>{"use strict"});import{existsSync as fu,renameSync as Gk}from"node:fs";function ir(t,e,r=n=>console.error(n)){if(fu(e)||!fu(t))return!1;try{return Gk(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Oo=x(()=>{"use strict"});import{existsSync as Do,readFileSync as mu,readdirSync as Hk,writeFileSync as Wk}from"node:fs";import{dirname as Yk,join as Pt}from"node:path";import{parse as qk}from"yaml";function Vk(t=process.cwd()){let e=t;for(;;){if(Do(Pt(e,dt,"project.yaml")))return e;if(Do(Pt(e,_s,"project.yaml")))return ir(Pt(e,_s),Pt(e,dt))&&Jk(e),e;let r=Yk(e);if(r===e)return null;e=r}}function zk(t){let e=Pt(t,dt);return Do(e)?e:Pt(t,_s)}function Jk(t){let e=Pt(t,".gitignore");if(!Do(e))return;let r=mu(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
8
- `);n!==r&&Wk(e,n)}function $e(t=process.cwd()){let e=Vk(t);if(!e)return null;let r=zk(e),n=Xk(mu(Pt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function hu(t,e,r){return Hk(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 Lo(t,e=process.cwd()){try{let r=$e(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Xk(t){let e=qk(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,p=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function gu(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 dt,_s,pt=x(()=>{"use strict";Oo();dt=".codepipe",_s=".devpipe"});import{homedir as yu}from"node:os";import{mkdirSync as Qk,readFileSync as Zk,writeFileSync as ew,existsSync as js}from"node:fs";import{dirname as wu,join as Mo,resolve as tw}from"node:path";import{fileURLToPath as rw}from"node:url";function bu(t){let e=Mo(ku,".env");if(js(e)&&process.loadEnvFile(e),t){let r=Mo(ku,"profiles",t,".env");js(r)&&process.loadEnvFile(r)}}function Dr(t){let e=Y("CONFIG");return e||(t?Mo(yu(),".codepipe","profiles",t,"config.json"):Mo(yu(),".codepipe","config.json"))}function Xe(t){let e=Dr(t);if(!js(e))return null;let r=Zk(e,"utf-8");return JSON.parse(r)}function $t(t,e){let r=Dr(e);Qk(wu(r),{recursive:!0}),ew(r,JSON.stringify(t,null,2)+`
9
- `,{mode:384})}function Uo(t){if(t)return{cfg:Fe(t),profile:t};let e;try{e=$e()?.spec.projectId||void 0}catch{}if(e){let r=Xe(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:Fe(void 0),profile:void 0}}function Fe(t){let e=Xe(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 ${Dr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var ku,Oe=x(()=>{"use strict";Ae();pt();ku=tw(wu(rw(import.meta.url)),"..")});import{homedir as Su}from"node:os";import{existsSync as Tu,mkdirSync as Ru,readFileSync as Iu,writeFileSync as Eu}from"node:fs";import{dirname as Cu,join as Au}from"node:path";function Pu(t,e,r){let n=W(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ne(n)}function _u(t,e){let r=W(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ne(r),!0)}function ju(t){return Object.keys(W(t)?.secrets??{}).sort()}function Bo(t,e,r){let n=W(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,ne(n),"pinned")}function Nu(t,e){let r=W(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ne(r),!0):!1}function ft(t){return Au(Su(),".codepipe","secrets",`${t}.json`)}function W(t){let e=ft(t);return Tu(e)?JSON.parse(Iu(e,"utf-8")):null}function ne(t){let e=ft(t.projectId);Ru(Cu(e),{recursive:!0}),Eu(e,JSON.stringify(t,null,2)+`
10
- `,{mode:384})}function Fo(){return Au(Su(),".codepipe","shared.json")}function Ns(){let t=Fo();return Tu(t)?JSON.parse(Iu(t,"utf-8")):null}function Ou(t){let e=Fo();Ru(Cu(e),{recursive:!0}),Eu(e,JSON.stringify(t,null,2)+`
11
- `,{mode:384})}function Lr(t){let e=W(t)?.claude?.oauthToken;return e||Ns()?.claude?.oauthToken}function Ln(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 Os){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Mr(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Os,ue=x(()=>{"use strict";Os=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as nw,existsSync as Lu,mkdirSync as ow,renameSync as Mu,statSync as iw,unlinkSync as sw}from"node:fs";import{Writable as aw}from"node:stream";import{join as cw}from"node:path";function Ko(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=lw(process.env[`${t}_MAX_BYTES`]??String(Uu.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Uu.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function lw(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 Go(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(uw(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 uw(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:dw(o)).join(" ");return`${r} ${t} ${n}`}function dw(t){try{return JSON.stringify(t)}catch{return String(t)}}var Uu,Ur,Ds=x(()=>{"use strict";Uu={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Ur=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&ow(e.dir,{recursive:!0}),this.currentPath=cw(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
7
+ `}function Cl(t){return jr(Bk(t))}function Al(t){return jr(Fk(t))}function jn(t){return jr(Gk(t))}var Ss,Cr,Dk,$l,Lk,Mk,ze,vl,xl,Sl,Es,Tl,_r,Kk,Rs=v(()=>{"use strict";Ss="model/derived/INDEX.yaml",Cr="model/derived/relates.yaml";Dk=["system","container","component","code","task","adr"],$l=["contains","touched_by","correlates","relates","references","depends_on"],Lk=/^e_[0-9a-f]{8}$/;Mk=["system","task","adr"];ze={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};vl=2,xl=5,Sl=50,Es=2e3,Tl={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},_r={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};Kk=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var Pl=v(()=>{"use strict"});var Hk,iI,_l=v(()=>{"use strict";Hk=[{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"]}],iI=Hk.flatMap(t=>t.phases)});function tr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var jl,Is=v(()=>{"use strict";jl=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function Nl(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Ll(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||qk.every(o=>e.some(i=>Nl(o,i.id))))return null;let n=[...e].sort((o,i)=>{let s=o.createdAt??"",a=i.createdAt??"";return s!==a?s<a?1:-1:o.id<i.id?1:-1});for(let o of Wk){let i=n.find(s=>Nl(o,s.id));if(i)return i.id}return n[0].id}var pt,Ol,Je,Nn,Dl,Cs,As,Wk,qk,Ps=v(()=>{"use strict";pt="claude",Ol=[pt],Je="opus",Nn="sonnet",Dl="haiku",Cs=[Je,Nn,Dl],As={analyze:Je,implement:Je,"resolve-conflict":Je,rework:Je,estimate:Nn,build:Nn,"code-review":Je,draft:Nn,index:Je,backfill:Je,analysis:Je,chat:Je},Wk=[Je,Nn,Dl],qk=Array.from(new Set(Object.values(As)))});function At(t){return Yk.has(t)?!0:Vk.some(e=>t.startsWith(e))}function jo(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 _s(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Gl(t,e){let r=jo(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=rr(r.id,"id")??n;if(!Ml.test(o))throw new Error(`id must match ${Ml} (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=jo(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!Be.test(d))throw new Error(`env name "${d}" must match ${Be}`);if(typeof f!="string"&&typeof f!="number"&&typeof f!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(f)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>Ul)throw new Error(`too many params (max ${Ul})`);let p=new Set;a=c.map((d,f)=>zk(d,f,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>Bl)throw new Error(`too many steps (max ${Bl})`);let u=l.map((p,d)=>{let f=jo(p,`steps[${d}]`),m=rr(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=rr(f.name,`steps[${d}].name`),y=_s(f.timeout_sec,`steps[${d}].timeout_sec`);if(y!==void 0&&(!Number.isInteger(y)||y<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...g?{name:g}:{},...y!==void 0?{timeout_sec:y}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function zk(t,e,r){let n=jo(t,`params[${e}]`),o=rr(n.name,`params[${e}].name`);if(!o||!Be.test(o))throw new Error(`params[${e}].name must match ${Be}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=rr(n.label,`params[${e}].label`),c=rr(n.help,`params[${e}].help`),l=n.required===!0,u=_s(n.min,`params[${e}].min`),p=_s(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 Kl(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 Be,Yk,Vk,Fl,Ml,Ul,Bl,js=v(()=>{"use strict";Be=/^[A-Z][A-Z0-9_]*$/,Yk=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Vk=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Fl=600,Ml=/^[a-z0-9-]+$/,Ul=32,Bl=64});var nr,Hl,On,Ns=v(()=>{"use strict";nr="auto",Hl=["primary","context","tasks","docs","code_comments","chat"],On=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"]});function Vl(t=Qk){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Vl(r.groups));return e}function Zk(t,e){let r=JSON.stringify(e);return Vl().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function zl(t){let e=Zk(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>Wl)return{ok:!1,error:`${e.id} must have \u2264 ${Wl} entries`};let s={};for(let[a,c]of i){if(!Be.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Be}`};if(At(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>ql)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${ql} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Jk,Xk,Wl,ql,Yl,Qk,Jl=v(()=>{"use strict";js();Is();Ps();Rs();Ns();Jk={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat"},Xk={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."},Wl=64,ql=2e3,Yl=2e3,Qk=[{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:[...Ol],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:[...Cs],help:"Overrides the recommended defaults for every role not listed below."},...jl.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Cs],help:`recommended: ${As[t]}`}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:Yl,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:Yl,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), a task taken from Develop waits in the QUEUE for a single Confirm before the pipeline starts \u2014 the Confirm pulls in dependency closure and topologically orders the queue. Off \u21D2 conveyor: the task starts the pipeline immediately."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:Hl.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:Jk[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[nr,...On]:[...On],help:Xk[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:"When on, agents are asked to record intent annotations and (once available) receive an assembled context pack. Off \u21D2 the pipeline ignores the map entirely."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${ze.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 ${ze.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 ${ze.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 ${ze.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 ${ze.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 ${ze.topK}.`}]},{id:"implementation",label:"Implementation",help:"How a dependency cluster is serialized into branches and PRs.",fields:[{id:"implementation.mode",file:"regimen.yaml",path:["implementation","mode"],type:"enum",label:"Implementation mode",nullable:!0,suggestions:["cluster-pr","sequential","parallel"],help:"cluster-pr (default for new projects) \u2014 one shared branch and a single PR per dependency cluster; a lone task is a cluster of one. sequential / parallel are an explicit opt-out of that. Clearing removes the key from regimen.yaml but keeps the mode already stored for the project (it is not reset to the default)."}]}]});var Xl=v(()=>{"use strict"});var Ql=v(()=>{"use strict"});var Zl=v(()=>{"use strict"});function eu(t){return`codepipe-host-${t}`}var tu=v(()=>{"use strict"});function ru(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 $t(t){return`${t}${ew}`}var or,ew,nu=v(()=>{"use strict";or=/^[a-z][a-z0-9-]{1,30}$/,ew="-codepipe-ctx"});var ou=v(()=>{"use strict"});var iu=v(()=>{"use strict"});function Nr(t){for(let e of tw){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var tw,su=v(()=>{"use strict";tw=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}]});var au=v(()=>{"use strict"});var cu=v(()=>{"use strict"});var lu=v(()=>{"use strict"});function uu(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function pu(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=uu(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Or.test(r))return r;let n=uu(t);return Or.test(n)?n:Os}function fu(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 du,Oo,Os,Or,Ds,xI,Do,Dn,mu=v(()=>{"use strict";du=["bug","feature","epic"],Oo="feature",Os="TASK",Or=/^[A-Z][A-Z0-9]{1,9}$/;Ds={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},xI=Ds.backlog,Do="tracker/config.yaml",Dn="tracker/counter"});var gu=v(()=>{"use strict"});function Dr(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 Lo(t){switch(t){case Mn.gitlab:return"oauth2";case Mn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Mn,ir,hu=v(()=>{"use strict";Mn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};ir="x-bitbucket-api-token-auth"});var yu=v(()=>{"use strict"});var ku=v(()=>{"use strict";gu();hu();yu()});var wu,G=v(()=>{"use strict";ul();dl();hl();Rs();Pl();_l();Is();Ps();Jl();Ns();js();Xl();Ql();Zl();tu();nu();ou();iu();su();au();cu();lu();mu();ku();wu=20});function z(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var _e=v(()=>{"use strict"});import{existsSync as bu,renameSync as rw}from"node:fs";function sr(t,e,r=n=>console.error(n)){if(bu(e)||!bu(t))return!1;try{return rw(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Mo=v(()=>{"use strict"});import{existsSync as Uo,readFileSync as $u,readdirSync as nw,writeFileSync as ow}from"node:fs";import{dirname as iw,join as Pt}from"node:path";import{parse as sw}from"yaml";function aw(t=process.cwd()){let e=t;for(;;){if(Uo(Pt(e,ft,"project.yaml")))return e;if(Uo(Pt(e,Ls,"project.yaml")))return sr(Pt(e,Ls),Pt(e,ft))&&lw(e),e;let r=iw(e);if(r===e)return null;e=r}}function cw(t){let e=Pt(t,ft);return Uo(e)?e:Pt(t,Ls)}function lw(t){let e=Pt(t,".gitignore");if(!Uo(e))return;let r=$u(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
8
+ `);n!==r&&ow(e,n)}function xe(t=process.cwd()){let e=aw(t);if(!e)return null;let r=cw(e),n=uw($u(Pt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function vu(t,e,r){return nw(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 Bo(t,e=process.cwd()){try{let r=xe(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function uw(t){let e=sw(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,p=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:p,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function xu(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 ft,Ls,mt=v(()=>{"use strict";Mo();ft=".codepipe",Ls=".devpipe"});import{homedir as Su}from"node:os";import{mkdirSync as dw,readFileSync as pw,writeFileSync as fw,existsSync as Ms}from"node:fs";import{dirname as Eu,join as Fo,resolve as mw}from"node:path";import{fileURLToPath as gw}from"node:url";function Ru(t){let e=Fo(Tu,".env");if(Ms(e)&&process.loadEnvFile(e),t){let r=Fo(Tu,"profiles",t,".env");Ms(r)&&process.loadEnvFile(r)}}function Lr(t){let e=z("CONFIG");return e||(t?Fo(Su(),".codepipe","profiles",t,"config.json"):Fo(Su(),".codepipe","config.json"))}function Xe(t){let e=Lr(t);if(!Ms(e))return null;let r=pw(e,"utf-8");return JSON.parse(r)}function vt(t,e){let r=Lr(e);dw(Eu(r),{recursive:!0}),fw(r,JSON.stringify(t,null,2)+`
9
+ `,{mode:384})}function Go(t){if(t)return{cfg:Fe(t),profile:t};let e;try{e=xe()?.spec.projectId||void 0}catch{}if(e){let r=Xe(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:Fe(void 0),profile:void 0}}function Fe(t){let e=Xe(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 ${Lr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Tu,Le=v(()=>{"use strict";_e();mt();Tu=mw(Eu(gw(import.meta.url)),"..")});import{homedir as Pu}from"node:os";import{existsSync as _u,mkdirSync as ju,readFileSync as Nu,writeFileSync as Ou}from"node:fs";import{dirname as Du,join as Lu}from"node:path";function Mu(t,e,r){let n=Y(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},re(n)}function Uu(t,e){let r=Y(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],re(r),!0)}function Bu(t){return Object.keys(Y(t)?.secrets??{}).sort()}function Ko(t,e,r){let n=Y(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,re(n),"pinned")}function Fu(t,e){let r=Y(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],re(r),!0):!1}function gt(t){return Lu(Pu(),".codepipe","secrets",`${t}.json`)}function Y(t){let e=gt(t);return _u(e)?JSON.parse(Nu(e,"utf-8")):null}function re(t){let e=gt(t.projectId);ju(Du(e),{recursive:!0}),Ou(e,JSON.stringify(t,null,2)+`
10
+ `,{mode:384})}function Ho(){return Lu(Pu(),".codepipe","shared.json")}function Us(){let t=Ho();return _u(t)?JSON.parse(Nu(t,"utf-8")):null}function Gu(t){let e=Ho();ju(Du(e),{recursive:!0}),Ou(e,JSON.stringify(t,null,2)+`
11
+ `,{mode:384})}function Mr(t){let e=Y(t)?.claude?.oauthToken;return e||Us()?.claude?.oauthToken}function Un(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 Bs){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Ur(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Bs,de=v(()=>{"use strict";Bs=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as hw,existsSync as Hu,mkdirSync as yw,renameSync as Wu,statSync as kw,unlinkSync as ww}from"node:fs";import{Writable as bw}from"node:stream";import{join as $w}from"node:path";function Wo(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=vw(process.env[`${t}_MAX_BYTES`]??String(qu.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):qu.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function vw(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 qo(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(xw(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 xw(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Sw(o)).join(" ");return`${r} ${t} ${n}`}function Sw(t){try{return JSON.stringify(t)}catch{return String(t)}}var qu,Br,Fs=v(()=>{"use strict";qu={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Br=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&yw(e.dir,{recursive:!0}),this.currentPath=$w(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
12
12
  `)?e:e+`
13
- `;nw(this.currentPath,r,"utf-8")}asWritable(){return new aw({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||!Lu(this.currentPath)||iw(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Lu(n)&&(r>=this.cfg.maxFiles?sw(n):Mu(n,`${this.currentPath}.${r+1}`))}Mu(this.currentPath,`${this.currentPath}.1`)}}}});import{createHash as pw}from"node:crypto";import{existsSync as fw,readFileSync as mw}from"node:fs";import{homedir as hw,hostname as Ls}from"node:os";import{join as gw}from"node:path";function Bu(t){return pw("sha256").update(t).digest("hex").slice(0,12)}function yw(){let t=Y("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=gw(hw(),".claude","credentials.json");if(!fw(e))return;let r=JSON.parse(mw(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 Fu(t){let e=yw(),r=Y("ACCOUNT_ID")?.trim(),n=Y("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Lr(t);return o?{accountId:`acct-${Bu(o)}`,label:n||Ls(),...e?{email:e}:{}}:{accountId:`acct-${Bu(`host:${Ls()}`)}`,label:n||Ls(),...e?{email:e}:{}}}var Ku=x(()=>{"use strict";Ae();ue()});function Wo(t){return t===429||t>=500}function Gu(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
14
- `+t.slice(t.length-e)}async function _t(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Ho);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new Ke(`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(Wo(i.status))throw new Ke(`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 Yo(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Ho);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 Ke(`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(Wo(s.status))throw new Ke(`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 jt(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(),Ho);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new Ke(`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(Wo(s.status))throw new Ke(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await kw(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 kw(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function qo(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=Hu.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: ${Hu.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Nt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Ho);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 Ke(`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(Wo(n.status))throw new Ke(`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 Wu(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 ww(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 Ms(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 Qe(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Bs(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Us(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Fs(e)}return new Ks}var sr,Ke,Ho,Hu,Us,Bs,Fs,Ks,Ot=x(()=>{"use strict";sr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},Ke=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Ho=5e3;Hu=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Us=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 sr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Bs=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 sr(`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(h=>h.conclusion==="failure")){let h=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!h.ok)continue;let k=await h.text();u.push(`### CI job: ${f.name}
15
-
16
- ${Gu(k,8e3)}`)}}return u.length===0?void 0:Gu(u.join(`
17
-
18
- `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Fs=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 sr(`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=ww(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};Ks=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(Ms(e,r,"merge"))}async closePR(e,r,n){throw new Error(Ms(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Ms(e,r,"comment"))}}});import{X509Certificate as Vu}from"node:crypto";import{readFileSync as bw}from"node:fs";import Dt from"node:tls";function $w(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Xu(t=Ju){if(Yu)return;Yu=!0;let e=Y("EXTRA_CA_FILE");if(!(!e||!zu))try{let r=$w(bw(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Dt.setDefaultCACertificates([...Dt.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 Qu(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 vw(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
19
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function xw(t,e,r){return new Promise((n,o)=>{let i=Dt.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 Vu(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Gs(t,e,r){return new Promise(n=>{let o=Dt.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 Sw(t){try{let e=await fetch(t);return e.ok?new Vu(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Zu(t,e=443,r=Ju){let n=`${t}:${e}`,o=qu.get(n);if(o)return o;let i=Tw(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return qu.set(n,i),i}async function Tw(t,e,r){if(!zu)return!1;let n=8e3;if(await Gs(t,e,n))return!0;let o=await xw(t,e,n),i=Dt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=vw(o);if(!c)break;let l=await Sw(c);if(!l)break;if(s.push(l.toString()),Dt.setDefaultCACertificates([...i,...s]),await Gs(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 Gs(t,e,n)}var zu,Yu,qu,Ju,ed=x(()=>{"use strict";Ae();zu=typeof Dt.getCACertificates=="function"&&typeof Dt.setDefaultCACertificates=="function",Yu=!1,qu=new Map,Ju=t=>console.warn(t)});function od(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Ge(t,e,r){Xu();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(Qu(s)&&await Zu(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Rw(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Iw(){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 Hs(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Iw(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Ge(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&&Rw(l.status,u)){await td(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await td(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Lt(t){let e;try{e=await Ge(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 id(t){try{let e=await Ge(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Ew(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=rd.get(o);if(i)return i;let s=await Ge(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 rd.set(o,l.id),l.id}async function sd(t,e,r,n=Mn){let o=await Ew(t,e,r,n);await Hs(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 ad(t,e,r){return await(await Hs(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function cd(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Hs(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function ld(t,e){let r=nd.get(e);if(r)return r;let n=await Ge(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 nd.set(e,i.id),i.id}async function ud(t,e,r,n,o,i=Mn){let s=await ld(t,e),a=await Ge(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 dd(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Ge(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 md(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 hd(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 gd(t,e){let r=e.stageField??Mn,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=${fd}&$top=200`,s=await Ge(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>wd(c,r))}async function yd(t,e,r=Mn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${fd}`,o=await Ge(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return wd(await o.json(),r)}async function kd(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Aw}&$top=500`,o=await Ge(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=md(s.attachments);return c&&(a.attachments=c),a})}function Pw(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 wd(t,e=Mn){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=md(t.attachments);a&&(s.attachments=a);let c=Pw(t.links);return c&&(s.links=c),s}async function bd(t,e){let r=await _w(t,e);return r.length>0?r:jw(t,e)}async function _w(t,e){let r=await ld(t,e),n=await Ge(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:$d(s.bundle)});return i}async function jw(t,e){let r=`project: ${e}`,n=await Ge(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:$d(s.projectCustomField?.bundle)});return i}function $d(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var td,Mn,rd,nd,pd,Cw,fd,Aw,ar=x(()=>{"use strict";ed();td=t=>new Promise(e=>setTimeout(e,t));Mn="Stage",rd=new Map;nd=new Map;pd="attachments(id,name,url,size,mimeType)",Cw="links(direction,linkType(name),issues(idReadable))",fd=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${pd},${Cw}`,Aw=`id,text,created,author(login),${pd}`});function Ze(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function Br(t){return t instanceof Ke}async function vd(t,e){let r=W(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 Lt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:Ze(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Ze(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await _t(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Br(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:Ze(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Ze(c),checkedAt:i()}))}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await jt(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){Br(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:Ze(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Ze(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Nt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Br(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:Ze(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Ze(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await Yo(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){Br(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:Ze(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Yo(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){Br(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:Ze(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Yo(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){Br(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:Ze(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=Lr(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 Mt(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Mt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function xd(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 Fr=x(()=>{"use strict";ue();Ot();ar()});import Nw from"node:http";import Ws from"node:crypto";function Vo(){let t=Ys(Ws.randomBytes(32)),e=Ys(Ws.createHash("sha256").update(t).digest()),r=Ys(Ws.randomBytes(32));return{verifier:t,challenge:e,state:r}}function Vs(t){let e=new URL(Ow);return e.search=new URLSearchParams({response_type:"code",client_id:Sd,redirect_uri:t.redirectUri,scope:Lw,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function Uw(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 Td(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 Bw(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 zs(t){let e=await fetch(Dw,{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:Sd,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return Bw(await e.json())}async function Js(t){let e=t.timeoutMs??Mw,r=Nw.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=Vs({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(Uw(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>zs({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Rd(t){let e=await Js(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
20
- ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var Sd,Ow,Dw,qs,Lw,Mw,Ys,Xs=x(()=>{"use strict";Sd="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Ow="https://platform.claude.com/oauth/authorize",Dw="https://platform.claude.com/v1/oauth/token",qs="https://platform.claude.com/oauth/code/callback",Lw="org:create_api_key user:profile user:inference",Mw=12e4,Ys=t=>Buffer.from(t).toString("base64url")});async function Id(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(Y("ORIGIN")==="farm"||Y("CLAUDE_AUTOLOGIN")==="0"){s("autologin_disabled");return}let a;try{a=await Js(Vo())}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 Mt(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=W(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},ne(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}var Ed=x(()=>{"use strict";Ae();Fr();ue();Xs()});function Cd(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?Y("ORIGIN")==="farm"||Y("CLAUDE_AUTOLOGIN")==="0"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Ad(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}var Pd=x(()=>{"use strict";Ae()});import{spawn as Fw}from"node:child_process";function cr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Fw(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var zo=x(()=>{"use strict"});import{setTimeout as Kw}from"node:timers/promises";import Gw from"ws";function Jo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Gw(r)}async function Ut(t,e,r){return et(t,e,"/projects",r)}async function _d(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Xo(t,e,r,n){return et(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function jd(t,e,r,n){return et(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Nd(t,e,r,n){return et(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Od(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 H(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function Qo(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Qs(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Dd(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Qs(t,e),a=new Set;for(let c of s)c.id!==r.excludeProjectId&&c.trackerProvider==="internal"&&c.youtrackProjectKey&&a.add(c.youtrackProjectKey.toUpperCase());return a}catch(s){o=s,i<n-1&&await Kw(r.delayMs??1500)}throw o}async function Ld(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new Un(e)}if(!r.ok)throw new H(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Md(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new H(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Ud(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new H(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Bd(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 H(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Zs(t,e,r,n){return et(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Fd(t,e,r,n,o){return et(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function Kd(t,e,r,n,o){return et(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function Gd(t,e,r,n,o){return et(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Bn(t,e,r,n){return et(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function ea(t,e,r,n){await et(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Hd(t,e,r,n){return et(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Wd(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 H(o.status,s,a)}return s}async function oe(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new H(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function et(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 H(o.status,s,a)}return s}var H,Un,xe=x(()=>{"use strict";H=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};Un=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});function qd(t){Yd=t}function lr(t,e="info"){Yd(t,e)}var Yd,Zo=x(()=>{"use strict";Yd=t=>console.log(t)});import{homedir as Hw,tmpdir as Ww}from"node:os";import{existsSync as Yw,mkdirSync as qw,mkdtempSync as Vw,rmSync as zw}from"node:fs";import{join as Fn}from"node:path";import{simpleGit as ei}from"simple-git";function Re(t,e,r){let n=r??Fn(Hw(),".codepipe","repos");return Fn(n,t,e)}async function dr(t,e,r={}){let n=Re(t,e.name,r.baseDir),o=r.cloneUrlOverride??Gn(e);if(!Yw(Fn(n,".git"))){qw(n,{recursive:!0});let a=ei();lr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
21
- ${l.trim()}`)}}let i=ei(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
22
- ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function ur(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function pr(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&&lr(`[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 ur(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await ur(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([...ti,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Kn(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await ur(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await ur(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 Vd(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 Kn(t,i,()=>pr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let m=`origin/${c}`;if(await ur(t,m)||(m=`origin/${u??c}`),(await t.revparse([m])).trim()===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{await t.checkout(["-B",a,m]);try{await t.raw([...ti,"cherry-pick",d])}catch(y){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let g=y instanceof Error?y.message:String(y);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
23
- ${g.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),k=r.push!==!1;if(k){let y=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(y)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:h,pushed:k}}async function zd(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 Jd(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await Kn(t,i,()=>pr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function Xd(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,baseRef:a,branchName:c,commitMessage:l,defaultBranch:u}=r,p=await Kn(t,i,()=>pr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));await t.fetch().catch(()=>{});let d=`origin/${a}`;if(await ur(t,d)||(d=`origin/${u??a}`),(await t.revparse([d])).trim()===s)return await t.raw(["branch","-f",c,p]),{commit:p,branch:c};let f=Vw(Fn(Ww(),"codepipe-apply-")),h=Fn(f,"wt");try{await t.raw(["worktree","add","--detach",h,d]);let k=ei(h);try{await k.raw([...ti,"cherry-pick",p])}catch(g){await k.raw(["cherry-pick","--abort"]).catch(()=>{});let $=g instanceof Error?g.message:String(g);throw new Error(`cherry-pick of ${i.slice(0,10)} onto ${a} hit conflicts
24
- ${$.trim()}`)}let y=(await k.revparse(["HEAD"])).trim();return await t.raw(["branch","-f",c,y]),{commit:y,branch:c}}finally{await t.raw(["worktree","remove","--force",h]).catch(()=>{}),zw(f,{recursive:!0,force:!0}),await t.raw(["worktree","prune"]).catch(()=>{})}}async function Qd(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await ur(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
25
- `).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(`
26
- `).map(k=>k.trim().toUpperCase()).filter(k=>k.length>0).some(k=>l.has(k))?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([...ti,"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 h=f instanceof Error?f.message:String(f);throw new Error(`rewrite_cluster_branch: replaying ${m.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
27
- ${h.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function Zd(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 Gn(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 ep(t){return(await ei().listRemote(["--heads",t])).split(`
28
- `).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function tp(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var ti,Kr=x(()=>{"use strict";Zo();ti=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{existsSync as ni,readFileSync as Jw,writeFileSync as Xw}from"node:fs";import{join as mr}from"node:path";import{simpleGit as ri}from"simple-git";function np(t){return mr(t,Qw)}function hr(t){let e=np(t);if(!ni(e))return{};try{return JSON.parse(Jw(e,"utf-8"))}catch{return{}}}function ra(t,e){Xw(np(t),JSON.stringify(e,null,2)+`
29
- `)}async function op(t,e,r,n,o){let i;try{i=await Zs(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(d){return{ok:!1,message:`claim failed: ${d instanceof Error?d.message:String(d)}`}}let s=[];for(let d of i.repos){let m=t.spec.repos.find(y=>y.name===d.repoName);if(!m)return{ok:!1,message:`repo "${d.repoName}" not in project.yaml \u2014 run /sync`};let f=mr(t.root,m.mountAs);if(!ni(mr(f,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await ri(f).status()).isClean())return{ok:!1,message:`${m.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:d,spec:m,dir:f})}let a=[];for(let d of s){let m=ri(d.dir),f=await Zw(m),h=d.claimRepo;try{await m.fetch()}catch(g){return await ta(a,o),{ok:!1,message:`fetch failed in ${d.spec.mountAs}: ${fr(g)}`}}let k=`origin/${h.baseRef}`,y;try{y=await pr(m,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(g){return await ta(a,o),{ok:!1,message:`fetch delivery failed in ${d.spec.mountAs}: ${fr(g)}`}}a.push({git:m,dir:d.dir,mountAs:d.spec.mountAs,originalRef:f,branch:h.branchName,baseSha:k,deliveryCommit:y,startPoint:k})}let c=[];for(let d of a)try{if(n==="apply"){await d.git.checkout(["-B",d.branch,d.startPoint]),await d.git.raw([...rp,"cherry-pick",d.deliveryCommit]);let m=(await d.git.revparse(["HEAD"])).trim();c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha,appliedSha:m})}else await d.git.checkout(["--detach",d.startPoint]),await d.git.raw([...rp,"cherry-pick","--no-commit",d.deliveryCommit]),await d.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha})}catch(m){return await d.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await ta(a,o),{ok:!1,message:`apply failed in ${d.mountAs}: ${fr(m)} (rolled back all repos)`}}let l=hr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},ra(t.contextDir,l);let u=c.map(d=>d.mountAs).join(", "),p=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
13
+ `;hw(this.currentPath,r,"utf-8")}asWritable(){return new bw({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||!Hu(this.currentPath)||kw(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Hu(n)&&(r>=this.cfg.maxFiles?ww(n):Wu(n,`${this.currentPath}.${r+1}`))}Wu(this.currentPath,`${this.currentPath}.1`)}}}});import{createHash as Tw}from"node:crypto";import{existsSync as Ew,readFileSync as Rw}from"node:fs";import{homedir as Iw,hostname as Gs}from"node:os";import{join as Cw}from"node:path";function Yu(t){return Tw("sha256").update(t).digest("hex").slice(0,12)}function Aw(){let t=z("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Cw(Iw(),".claude","credentials.json");if(!Ew(e))return;let r=JSON.parse(Rw(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 Vu(t){let e=Aw(),r=z("ACCOUNT_ID")?.trim(),n=z("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Mr(t);return o?{accountId:`acct-${Yu(o)}`,label:n||Gs(),...e?{email:e}:{}}:{accountId:`acct-${Yu(`host:${Gs()}`)}`,label:n||Gs(),...e?{email:e}:{}}}var zu=v(()=>{"use strict";_e();de()});function Vo(t){return t===429||t>=500}function Ju(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
14
+ `+t.slice(t.length-e)}async function _t(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Yo);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new Ge(`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(Vo(i.status))throw new Ge(`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 zo(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Yo);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 Ge(`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(Vo(s.status))throw new Ge(`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 jt(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(),Yo);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new Ge(`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(Vo(s.status))throw new Ge(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await Pw(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 Pw(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Jo(t,e,r,n){let o;try{o=await fetch(`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}/${encodeURIComponent(n)}/pullrequests?pagelen=1`,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch{return}if(o.status!==403)return;let i={};try{i=await o.json()}catch{}let s=i.error?.detail?.granted;if(Array.isArray(s)){let c=Xu.filter(l=>!s.includes(l));return c.length===0?void 0:`token lacks scope(s) ${c.join(", ")} \u2014 the pipeline would fail at PR time; re-create the API token with all of: ${Xu.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Nt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Yo);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 Ge(`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(Vo(n.status))throw new Ge(`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 Qu(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 _w(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 Ks(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 Qe(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Ws(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Hs(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new qs(e)}return new Ys}var ar,Ge,Yo,Xu,Hs,Ws,qs,Ys,Ot=v(()=>{"use strict";ar=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},Ge=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Yo=5e3;Xu=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Hs=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 ar(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Ws=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 ar(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let p of l.filter(d=>d.conclusion&&i.includes(d.conclusion))){let d=await fetch(`${o}/actions/runs/${p.id}/jobs?per_page=50`,{headers:n});if(!d.ok)continue;let f=(await d.json()).jobs??[];for(let m of f.filter(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${m.id}/logs`,{headers:n});if(!g.ok)continue;let y=await g.text();u.push(`### CI job: ${m.name}
15
+
16
+ ${Ju(y,8e3)}`)}}return u.length===0?void 0:Ju(u.join(`
17
+
18
+ `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},qs=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 ar(`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=_w(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};Ys=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(Ks(e,r,"merge"))}async closePR(e,r,n){throw new Error(Ks(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Ks(e,r,"comment"))}}});import{X509Certificate as td}from"node:crypto";import{readFileSync as jw}from"node:fs";import Dt from"node:tls";function Nw(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function od(t=nd){if(Zu)return;Zu=!0;let e=z("EXTRA_CA_FILE");if(!(!e||!rd))try{let r=Nw(jw(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Dt.setDefaultCACertificates([...Dt.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 id(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 Ow(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
19
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Dw(t,e,r){return new Promise((n,o)=>{let i=Dt.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 td(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Vs(t,e,r){return new Promise(n=>{let o=Dt.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function Lw(t){try{let e=await fetch(t);return e.ok?new td(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function sd(t,e=443,r=nd){let n=`${t}:${e}`,o=ed.get(n);if(o)return o;let i=Mw(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return ed.set(n,i),i}async function Mw(t,e,r){if(!rd)return!1;let n=8e3;if(await Vs(t,e,n))return!0;let o=await Dw(t,e,n),i=Dt.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Ow(o);if(!c)break;let l=await Lw(c);if(!l)break;if(s.push(l.toString()),Dt.setDefaultCACertificates([...i,...s]),await Vs(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 Vs(t,e,n)}var rd,Zu,ed,nd,ad=v(()=>{"use strict";_e();rd=typeof Dt.getCACertificates=="function"&&typeof Dt.setDefaultCACertificates=="function",Zu=!1,ed=new Map,nd=t=>console.warn(t)});function dd(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Ke(t,e,r){od();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(id(s)&&await sd(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Uw(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Bw(){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 zs(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Bw(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Ke(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&&Uw(l.status,u)){await cd(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await cd(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Lt(t){let e;try{e=await Ke(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 pd(t){try{let e=await Ke(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Fw(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=ld.get(o);if(i)return i;let s=await Ke(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 ld.set(o,l.id),l.id}async function fd(t,e,r,n=Bn){let o=await Fw(t,e,r,n);await zs(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 md(t,e,r){return await(await zs(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function gd(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await zs(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function hd(t,e){let r=ud.get(e);if(r)return r;let n=await Ke(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 ud.set(e,i.id),i.id}async function yd(t,e,r,n,o,i=Bn){let s=await hd(t,e),a=await Ke(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 kd(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Ke(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 $d(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 vd(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 xd(t,e){let r=e.stageField??Bn,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=${bd}&$top=200`,s=await Ke(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Ed(c,r))}async function Sd(t,e,r=Bn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${bd}`,o=await Ke(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Ed(await o.json(),r)}async function Td(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Kw}&$top=500`,o=await Ke(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=$d(s.attachments);return c&&(a.attachments=c),a})}function Hw(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Ed(t,e=Bn){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=$d(t.attachments);a&&(s.attachments=a);let c=Hw(t.links);return c&&(s.links=c),s}async function Rd(t,e){let r=await Ww(t,e);return r.length>0?r:qw(t,e)}async function Ww(t,e){let r=await hd(t,e),n=await Ke(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:Id(s.bundle)});return i}async function qw(t,e){let r=`project: ${e}`,n=await Ke(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:Id(s.projectCustomField?.bundle)});return i}function Id(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var cd,Bn,ld,ud,wd,Gw,bd,Kw,cr=v(()=>{"use strict";ad();cd=t=>new Promise(e=>setTimeout(e,t));Bn="Stage",ld=new Map;ud=new Map;wd="attachments(id,name,url,size,mimeType)",Gw="links(direction,linkType(name),issues(idReadable))",bd=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${wd},${Gw}`,Kw=`id,text,created,author(login),${wd}`});function Ze(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function Fr(t){return t instanceof Ge}async function Cd(t,e){let r=Y(t),n=[],o=[],i=()=>Date.now();if(e?.trackerProvider==="internal")n.push({name:"tracker",ok:!0,detail:"built-in tracker"});else if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Lt({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:Ze(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Ze(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await _t(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Fr(c)?(n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"github",ok:!1,detail:Ze(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Ze(c),checkedAt:i()}))}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await jt(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){Fr(c)?(n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"bitbucket",ok:!1,detail:Ze(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Ze(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Nt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Fr(c)?(n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,detail:"check inconclusive",checkedAt:i()})):(n.push({name:"gitlab",ok:!1,detail:Ze(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Ze(c),checkedAt:i()}))}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await zo(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){Fr(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:Ze(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await zo(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){Fr(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:Ze(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await zo(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){Fr(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:Ze(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=Mr(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 Mt(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Mt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function Ad(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 Gr=v(()=>{"use strict";de();Ot();cr()});import Yw from"node:http";import Js from"node:crypto";function Xo(){let t=Xs(Js.randomBytes(32)),e=Xs(Js.createHash("sha256").update(t).digest()),r=Xs(Js.randomBytes(32));return{verifier:t,challenge:e,state:r}}function Zs(t){let e=new URL(Vw);return e.search=new URLSearchParams({response_type:"code",client_id:Pd,redirect_uri:t.redirectUri,scope:Jw,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function Qw(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 _d(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 Zw(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 ea(t){let e=await fetch(zw,{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:Pd,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return Zw(await e.json())}async function ta(t){let e=t.timeoutMs??Xw,r=Yw.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=Zs({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let f=new URL(p.url??"/",o);if(f.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(Qw(f.searchParams,t.state))}catch(m){u(m)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>ea({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function jd(t){let e=await ta(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
20
+ ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var Pd,Vw,zw,Qs,Jw,Xw,Xs,ra=v(()=>{"use strict";Pd="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Vw="https://platform.claude.com/oauth/authorize",zw="https://platform.claude.com/v1/oauth/token",Qs="https://platform.claude.com/oauth/code/callback",Jw="org:create_api_key user:profile user:inference",Xw=12e4,Xs=t=>Buffer.from(t).toString("base64url")});async function Nd(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(z("ORIGIN")==="farm"||z("CLAUDE_AUTOLOGIN")==="0"){s("autologin_disabled");return}let a;try{a=await ta(Xo())}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 Mt(c.oauthToken);if(l==="invalid"){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"token rejected (401) \u2014 previous token kept"}),n.warn("[agent-auth] new Claude token rejected (401) \u2014 previous token kept");return}let u=Y(t.projectId);if(!u){i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:"no secrets file for this project on the CLI"}),n.warn("[agent-auth] no secrets file for this project \u2014 token not saved");return}u.claude={oauthToken:c.oauthToken},re(u),n.info(`[agent-auth] Claude token replaced (${c.oauthToken.slice(0,12)}\u2026, ${c.oauthToken.length} chars)`),i({type:"agent_login_result",projectId:t.projectId,ok:!0,...l==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}}),o()}catch(c){let l=c instanceof Error?c.message:String(c);i({type:"agent_login_result",projectId:t.projectId,ok:!1,detail:l}),n.warn(`[agent-auth] browser authorization failed: ${l}`)}finally{a.close()}}var Od=v(()=>{"use strict";_e();Gr();de();ra()});function Dd(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?z("ORIGIN")==="farm"||z("CLAUDE_AUTOLOGIN")==="0"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Ld(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}var Md=v(()=>{"use strict";_e()});import{spawn as eb}from"node:child_process";function lr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=eb(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var Qo=v(()=>{"use strict"});import{setTimeout as tb}from"node:timers/promises";import rb from"ws";function Zo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new rb(r)}async function Ut(t,e,r){return et(t,e,"/projects",r)}async function Ud(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function ei(t,e,r,n){return et(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Bd(t,e,r,n){return et(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Fd(t,e,r,n){return et(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Gd(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 H(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function ti(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function na(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new H(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Kd(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await na(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 tb(r.delayMs??1500)}throw o}async function Hd(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new Fn(e)}if(!r.ok)throw new H(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Wd(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new H(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function qd(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new H(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Yd(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 H(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function oa(t,e,r,n){return et(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Vd(t,e,r,n,o){return et(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function zd(t,e,r,n,o){return et(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function Jd(t,e,r,n,o){return et(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Gn(t,e,r,n){return et(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function ia(t,e,r,n){await et(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Xd(t,e,r,n){return et(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Qd(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 H(o.status,s,a)}return s}async function ne(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new H(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function et(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 H(o.status,s,a)}return s}var H,Fn,Te=v(()=>{"use strict";H=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};Fn=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});function ep(t){Zd=t}function ur(t,e="info"){Zd(t,e)}var Zd,ri=v(()=>{"use strict";Zd=t=>console.log(t)});import{homedir as nb,tmpdir as ob}from"node:os";import{existsSync as ib,mkdirSync as sb,mkdtempSync as ab,rmSync as cb}from"node:fs";import{join as Kn}from"node:path";import{simpleGit as ni}from"simple-git";function Ie(t,e,r){let n=r??Kn(nb(),".codepipe","repos");return Kn(n,t,e)}async function pr(t,e,r={}){let n=Ie(t,e.name,r.baseDir),o=r.cloneUrlOverride??Wn(e);if(!ib(Kn(n,".git"))){sb(n,{recursive:!0});let a=ni();ur(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
21
+ ${l.trim()}`)}}let i=ni(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
22
+ ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function dr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function fr(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&&ur(`[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 dr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await dr(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([...oi,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Hn(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await dr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await dr(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 tp(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 Hn(t,i,()=>fr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let f=`origin/${c}`;if(await dr(t,f)||(f=`origin/${u??c}`),(await t.revparse([f])).trim()===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{await t.checkout(["-B",a,f]);try{await t.raw([...oi,"cherry-pick",d])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let h=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
23
+ ${h.trim()}`)}}let g=(await t.revparse(["HEAD"])).trim(),y=r.push!==!1;if(y){let w=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(w)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:g,pushed:y}}async function rp(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 np(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await Hn(t,i,()=>fr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function op(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,baseRef:a,branchName:c,commitMessage:l,defaultBranch:u}=r,p=await Hn(t,i,()=>fr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));await t.fetch().catch(()=>{});let d=`origin/${a}`;if(await dr(t,d)||(d=`origin/${u??a}`),(await t.revparse([d])).trim()===s)return await t.raw(["branch","-f",c,p]),{commit:p,branch:c};let m=ab(Kn(ob(),"codepipe-apply-")),g=Kn(m,"wt");try{await t.raw(["worktree","add","--detach",g,d]);let y=ni(g);try{await y.raw([...oi,"cherry-pick",p])}catch(h){await y.raw(["cherry-pick","--abort"]).catch(()=>{});let $=h instanceof Error?h.message:String(h);throw new Error(`cherry-pick of ${i.slice(0,10)} onto ${a} hit conflicts
24
+ ${$.trim()}`)}let w=(await y.revparse(["HEAD"])).trim();return await t.raw(["branch","-f",c,w]),{commit:w,branch:c}}finally{await t.raw(["worktree","remove","--force",g]).catch(()=>{}),cb(m,{recursive:!0,force:!0}),await t.raw(["worktree","prune"]).catch(()=>{})}}async function ip(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await dr(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
25
+ `).map(f=>f.trim()).filter(f=>f.length>0),l=new Set(o.map(f=>f.toUpperCase())),u=[],p=0;for(let f of c)(await t.raw(["show","-s","--format=%(trailers:key=CodePipe-Task,valueonly)",f])).split(`
26
+ `).map(y=>y.trim().toUpperCase()).filter(y=>y.length>0).some(y=>l.has(y))?p++:u.push(f);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let f of u)try{await t.raw([...oi,"cherry-pick","--allow-empty","--keep-redundant-commits",f])}catch(m){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let g=m instanceof Error?m.message:String(m);throw new Error(`rewrite_cluster_branch: replaying ${f.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
27
+ ${g.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function sp(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 Wn(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 ap(t){return(await ni().listRemote(["--heads",t])).split(`
28
+ `).map(r=>r.trim()).filter(r=>r.length>0).map(r=>r.split(/\s+/)[1]??"").filter(r=>r.startsWith("refs/heads/")).map(r=>r.slice(11))}function cp(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var oi,Kr=v(()=>{"use strict";ri();oi=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{existsSync as si,readFileSync as lb,writeFileSync as ub}from"node:fs";import{join as gr}from"node:path";import{simpleGit as ii}from"simple-git";function up(t){return gr(t,db)}function hr(t){let e=up(t);if(!si(e))return{};try{return JSON.parse(lb(e,"utf-8"))}catch{return{}}}function aa(t,e){ub(up(t),JSON.stringify(e,null,2)+`
29
+ `)}async function dp(t,e,r,n,o){let i;try{i=await oa(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(d){return{ok:!1,message:`claim failed: ${d instanceof Error?d.message:String(d)}`}}let s=[];for(let d of i.repos){let f=t.spec.repos.find(w=>w.name===d.repoName);if(!f)return{ok:!1,message:`repo "${d.repoName}" not in project.yaml \u2014 run /sync`};let m=gr(t.root,f.mountAs);if(!si(gr(m,".git")))return{ok:!1,message:`${f.mountAs}/ not cloned \u2014 run /sync first`};if(!(await ii(m).status()).isClean())return{ok:!1,message:`${f.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:d,spec:f,dir:m})}let a=[];for(let d of s){let f=ii(d.dir),m=await pb(f),g=d.claimRepo;try{await f.fetch()}catch(h){return await sa(a,o),{ok:!1,message:`fetch failed in ${d.spec.mountAs}: ${mr(h)}`}}let y=`origin/${g.baseRef}`,w;try{w=await fr(f,{contextRepoCloneUrl:g.contextRepoCloneUrl,deliveryRef:g.deliveryRef,deliverySha:g.deliverySha,baseSha:g.baseSha,commitMessage:g.commitMessage})}catch(h){return await sa(a,o),{ok:!1,message:`fetch delivery failed in ${d.spec.mountAs}: ${mr(h)}`}}a.push({git:f,dir:d.dir,mountAs:d.spec.mountAs,originalRef:m,branch:g.branchName,baseSha:y,deliveryCommit:w,startPoint:y})}let c=[];for(let d of a)try{if(n==="apply"){await d.git.checkout(["-B",d.branch,d.startPoint]),await d.git.raw([...lp,"cherry-pick",d.deliveryCommit]);let f=(await d.git.revparse(["HEAD"])).trim();c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha,appliedSha:f})}else await d.git.checkout(["--detach",d.startPoint]),await d.git.raw([...lp,"cherry-pick","--no-commit",d.deliveryCommit]),await d.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:d.mountAs,branch:d.branch,baseSha:d.baseSha})}catch(f){return await d.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await sa(a,o),{ok:!1,message:`apply failed in ${d.mountAs}: ${mr(f)} (rolled back all repos)`}}let l=hr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},aa(t.contextDir,l);let u=c.map(d=>d.mountAs).join(", "),p=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
30
30
  ${p}
31
- or: /abort ${r} --reason "..."`}}async function ip(t,e,r){let n=[];for(let c of e.repos){let l=t.repos.find(p=>p.name===c.repoName);if(!l)return{ok:!1,message:`repo "${c.repoName}" not in project.yaml \u2014 run /sync`};let u=mr(t.root,l.mountAs);if(!ni(mr(u,".git")))return{ok:!1,message:`${l.mountAs}/ not cloned \u2014 run /sync first`};n.push({git:ri(u),dir:u,spec:l,cr:c})}let o=[],i=[];for(let c of n)try{let{commit:l}=await Xd(c.git,c.dir,{contextRepoCloneUrl:c.cr.contextRepoCloneUrl,deliveryRef:c.cr.deliveryRef,deliverySha:c.cr.deliverySha,baseSha:c.cr.baseSha,baseRef:c.cr.baseRef,branchName:c.cr.branchName,commitMessage:c.cr.commitMessage,defaultBranch:c.spec.defaultBranch});r.info(`[apply] ${e.taskKey}: ${c.cr.branchName} \u2192 ${c.spec.mountAs} (${l.slice(0,10)})`),o.push({git:c.git,branch:c.cr.branchName}),i.push({mountAs:c.spec.mountAs,branch:c.cr.branchName,baseSha:`origin/${c.cr.baseRef}`,appliedSha:l})}catch(l){for(let u of o)await u.git.raw(["branch","-D",u.branch]).catch(()=>{});return{ok:!1,message:`auto-apply failed in ${c.spec.mountAs}: ${fr(l)}`}}try{await Zs(t.hubUrl,t.cliToken,t.projectId,e.taskKey)}catch(c){return{ok:!1,message:`branch created but claim failed: ${fr(c)} \u2014 retried on the next reconnect`,branches:o.map(l=>l.branch)}}let s=hr(t.contextDir);s[e.taskKey]={mode:"apply",claimedAt:new Date().toISOString(),repos:i},ra(t.contextDir,s);let a=i.map(c=>`${c.branch} (${c.mountAs})`).join(", ");return{ok:!0,branches:i.map(c=>c.branch),message:`branch created locally without touching your checkout: ${a}
31
+ or: /abort ${r} --reason "..."`}}async function pp(t,e,r){let n=[];for(let c of e.repos){let l=t.repos.find(p=>p.name===c.repoName);if(!l)return{ok:!1,message:`repo "${c.repoName}" not in project.yaml \u2014 run /sync`};let u=gr(t.root,l.mountAs);if(!si(gr(u,".git")))return{ok:!1,message:`${l.mountAs}/ not cloned \u2014 run /sync first`};n.push({git:ii(u),dir:u,spec:l,cr:c})}let o=[],i=[];for(let c of n)try{let{commit:l}=await op(c.git,c.dir,{contextRepoCloneUrl:c.cr.contextRepoCloneUrl,deliveryRef:c.cr.deliveryRef,deliverySha:c.cr.deliverySha,baseSha:c.cr.baseSha,baseRef:c.cr.baseRef,branchName:c.cr.branchName,commitMessage:c.cr.commitMessage,defaultBranch:c.spec.defaultBranch});r.info(`[apply] ${e.taskKey}: ${c.cr.branchName} \u2192 ${c.spec.mountAs} (${l.slice(0,10)})`),o.push({git:c.git,branch:c.cr.branchName}),i.push({mountAs:c.spec.mountAs,branch:c.cr.branchName,baseSha:`origin/${c.cr.baseRef}`,appliedSha:l})}catch(l){for(let u of o)await u.git.raw(["branch","-D",u.branch]).catch(()=>{});return{ok:!1,message:`auto-apply failed in ${c.spec.mountAs}: ${mr(l)}`}}try{await oa(t.hubUrl,t.cliToken,t.projectId,e.taskKey)}catch(c){return{ok:!1,message:`branch created but claim failed: ${mr(c)} \u2014 retried on the next reconnect`,branches:o.map(l=>l.branch)}}let s=hr(t.contextDir);s[e.taskKey]={mode:"apply",claimedAt:new Date().toISOString(),repos:i},aa(t.contextDir,s);let a=i.map(c=>`${c.branch} (${c.mountAs})`).join(", ");return{ok:!0,branches:i.map(c=>c.branch),message:`branch created locally without touching your checkout: ${a}
32
32
  review, push, then: /applied ${e.taskKey} --pr <url>
33
- or: /abort ${e.taskKey} --reason "..."`}}function na(t,e){let r=hr(t);r[e]&&(delete r[e],ra(t,r))}async function ta(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${fr(n)} \u2014 check manually`)}}async function sp(t,e,r){let o=hr(t.contextDir)[e];if(o){for(let i of o.repos){let s=mr(t.root,i.mountAs);if(!ni(mr(s,".git")))continue;let a=ri(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${fr(u)} \u2014 check manually`)}}na(t.contextDir,e)}}async function Zw(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function fr(t){return t instanceof Error?t.message.trim():String(t)}var rp,Qw,oa=x(()=>{"use strict";xe();Kr();rp=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Qw="apply-queue.json"});import{existsSync as eb}from"node:fs";import{join as tb}from"node:path";import{simpleGit as rb}from"simple-git";async function ap(t,e){if(!eb(tb(t,".git")))return{status:"skipped"};let r=rb(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${nb(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 nb(t){return t instanceof Error?t.message.trim():String(t)}var cp=x(()=>{"use strict"});import{existsSync as lp,readFileSync as up,readdirSync as ob,statSync as ib}from"node:fs";import{join as ia}from"node:path";import{parse as dp}from"yaml";function oi(t){let e=ia(t,"actions"),r=[],n=[];if(!lp(e))return{defs:r,errors:n};let o;try{o=ob(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=ia(e,s);try{if(!ib(a).isFile())continue;let c=Dl(s,dp(up(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 pp(t){let e={},r=ia(t,"project.yaml");if(!lp(r))return e;let n;try{n=dp(up(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))!Be.test(i)||At(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var sa=x(()=>{"use strict";K()});import{existsSync as aa,readFileSync as fp,readdirSync as sb,watch as ab}from"node:fs";import{join as Hn}from"node:path";var ii,mp=x(()=>{"use strict";sa();ii=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,Hn(this.contextDir,"prompts"),Hn(this.contextDir,"actions")];for(let n of r)if(aa(n))try{let o=ab(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=oi(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=Hn(this.contextDir,e);if(!aa(r))return null;try{return fp(r,"utf-8")}catch{return null}}readPrompts(){let e=Hn(this.contextDir,"prompts"),r={};if(!aa(e))return r;let n;try{n=sb(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=fp(Hn(e,o),"utf-8")}catch{}}return r}}});import{existsSync as Bt,mkdirSync as hp,readFileSync as ca,writeFileSync as Gr}from"node:fs";import{homedir as cb}from"node:os";import{join as mt}from"node:path";import{simpleGit as lb}from"simple-git";function Wn(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=mt(t,o);Bt(s)||(Gr(s,i),r.push(o))}return r}function gr(t,e,r){let n=mt(cb(),".codepipe","profiles",t,"context-config");return hp(n,{recursive:!0}),Gr(mt(n,"project.yaml"),e.projectYaml),Gr(mt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function si(t,e,r){if(Bt(e))for(let n of Hr){let o=mt(e,n),i=mt(t,n);if(!(!Bt(o)||Bt(i)))try{Gr(i,ca(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 Wr(t){let e=mt(t,".gitignore"),r=Bt(e)?ca(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Hr.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
33
+ or: /abort ${e.taskKey} --reason "..."`}}function ca(t,e){let r=hr(t);r[e]&&(delete r[e],aa(t,r))}async function sa(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${mr(n)} \u2014 check manually`)}}async function fp(t,e,r){let o=hr(t.contextDir)[e];if(o){for(let i of o.repos){let s=gr(t.root,i.mountAs);if(!si(gr(s,".git")))continue;let a=ii(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${mr(u)} \u2014 check manually`)}}ca(t.contextDir,e)}}async function pb(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function mr(t){return t instanceof Error?t.message.trim():String(t)}var lp,db,la=v(()=>{"use strict";Te();Kr();lp=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],db="apply-queue.json"});import{existsSync as fb}from"node:fs";import{join as mb}from"node:path";import{simpleGit as gb}from"simple-git";async function mp(t,e){if(!fb(mb(t,".git")))return{status:"skipped"};let r=gb(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${hb(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 hb(t){return t instanceof Error?t.message.trim():String(t)}var gp=v(()=>{"use strict"});import{existsSync as hp,readFileSync as yp,readdirSync as yb,statSync as kb}from"node:fs";import{join as ua}from"node:path";import{parse as kp}from"yaml";function ai(t){let e=ua(t,"actions"),r=[],n=[];if(!hp(e))return{defs:r,errors:n};let o;try{o=yb(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=ua(e,s);try{if(!kb(a).isFile())continue;let c=Gl(s,kp(yp(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 wp(t){let e={},r=ua(t,"project.yaml");if(!hp(r))return e;let n;try{n=kp(yp(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))!Be.test(i)||At(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var da=v(()=>{"use strict";G()});import{existsSync as pa,readFileSync as bp,readdirSync as wb,watch as bb}from"node:fs";import{join as qn}from"node:path";var ci,$p=v(()=>{"use strict";da();ci=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,qn(this.contextDir,"prompts"),qn(this.contextDir,"actions")];for(let n of r)if(pa(n))try{let o=bb(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=ai(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=qn(this.contextDir,e);if(!pa(r))return null;try{return bp(r,"utf-8")}catch{return null}}readPrompts(){let e=qn(this.contextDir,"prompts"),r={};if(!pa(e))return r;let n;try{n=wb(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=bp(qn(e,o),"utf-8")}catch{}}return r}}});import{existsSync as Bt,mkdirSync as vp,readFileSync as fa,writeFileSync as Hr}from"node:fs";import{homedir as $b}from"node:os";import{join as ht}from"node:path";import{simpleGit as vb}from"simple-git";function Yn(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=ht(t,o);Bt(s)||(Hr(s,i),r.push(o))}return r}function yr(t,e,r){let n=ht($b(),".codepipe","profiles",t,"context-config");return vp(n,{recursive:!0}),Hr(ht(n,"project.yaml"),e.projectYaml),Hr(ht(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function li(t,e,r){if(Bt(e))for(let n of Wr){let o=ht(e,n),i=ht(t,n);if(!(!Bt(o)||Bt(i)))try{Hr(i,fa(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 qr(t){let e=ht(t,".gitignore"),r=Bt(e)?fa(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Wr.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
34
34
  `)?"":`
35
- `;return Gr(e,r+i+ub.join(`
35
+ `;return Hr(e,r+i+xb.join(`
36
36
  `)+`
37
- `),!0}async function gp(t,e){try{if(!Bt(mt(t,".git")))return;let r=lb(t),n=(await r.raw(["ls-files","--",...Hr])).split(`
38
- `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;Wr(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 da(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 la(t){let e=new Map;for(let r of Hr){let n=mt(t,r);Bt(n)&&e.set(r,ca(n))}return e}function ua(t,e){hp(t,{recursive:!0});for(let[r,n]of e){let o=mt(t,r);Bt(o)||Gr(o,n)}}var Hr,ub,vt=x(()=>{"use strict";tt();Hr=["project.yaml","regimen.yaml"];ub=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as db,mkdirSync as pb,rmSync as fb,writeFileSync as pa}from"node:fs";import{dirname as mb,isAbsolute as hb,join as wp,normalize as li}from"node:path";import{simpleGit as bp}from"simple-git";async function fa(t,e){let r=li(t),o=(ci.get(r)??Promise.resolve()).catch(()=>{}).then(e);ci.set(r,o);try{return await o}finally{ci.get(r)===o&&ci.delete(r)}}async function Se(t,e,r){return fa(t,()=>ma(t,e,r))}async function ma(t,e,r){if(!db(wp(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=we(t,a.path);if(a.deleted){fb(c,{force:!0});continue}pb(mb(c),{recursive:!0}),a.encoding==="base64"?pa(c,Buffer.from(a.content,"base64")):pa(c,a.content)}let n=bp(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+=ai)await n.raw(["add","-A","-f","--",...o.slice(a,a+ai)]);for(let a=0;a<i.length;a+=ai)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+ai)]);await n.raw(["reset","-q","--",...Hr]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await da(t))}async function da(t){let e=bp(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=yp;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 wb(e);if(i.length>0&&i.every(a=>gb.has(a)||kp.test(a)||yb.test(a))){for(let a of i)kp.test(a)?await kb(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 ${yp} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function kb(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
39
- `)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);pa(we(e,r),i.join(`
37
+ `),!0}async function xp(t,e){try{if(!Bt(ht(t,".git")))return;let r=vb(t),n=(await r.raw(["ls-files","--",...Wr])).split(`
38
+ `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;qr(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 ha(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 ma(t){let e=new Map;for(let r of Wr){let n=ht(t,r);Bt(n)&&e.set(r,fa(n))}return e}function ga(t,e){vp(t,{recursive:!0});for(let[r,n]of e){let o=ht(t,r);Bt(o)||Hr(o,n)}}var Wr,xb,xt=v(()=>{"use strict";tt();Wr=["project.yaml","regimen.yaml"];xb=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Sb,mkdirSync as Tb,rmSync as Eb,writeFileSync as ya}from"node:fs";import{dirname as Rb,isAbsolute as Ib,join as Ep,normalize as pi}from"node:path";import{simpleGit as Rp}from"simple-git";async function ka(t,e){let r=pi(t),o=(di.get(r)??Promise.resolve()).catch(()=>{}).then(e);di.set(r,o);try{return await o}finally{di.get(r)===o&&di.delete(r)}}async function Ee(t,e,r){return ka(t,()=>wa(t,e,r))}async function wa(t,e,r){if(!Sb(Ep(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=$e(t,a.path);if(a.deleted){Eb(c,{force:!0});continue}Tb(Rb(c),{recursive:!0}),a.encoding==="base64"?ya(c,Buffer.from(a.content,"base64")):ya(c,a.content)}let n=Rp(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","--",...Wr]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await ha(t))}async function ha(t){let e=Rp(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Sp;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 _b(e);if(i.length>0&&i.every(a=>Cb.has(a)||Tp.test(a)||Ab.test(a))){for(let a of i)Tp.test(a)?await Pb(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 ${Sp} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Pb(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
39
+ `)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);ya($e(e,r),i.join(`
40
40
  `)+(i.length>0?`
41
- `:""))}async function wb(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
42
- `).map(r=>r.trim()).filter(Boolean)}function we(t,e){if(hb(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=li(wp(t,e)),n=li(t+"/");if(r!==li(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var yp,gb,yb,kp,ai,ci,tt=x(()=>{"use strict";vt();yp=3,gb=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),yb=/^model\/derived\//,kp=/^tasks\/[^/]+\/comments\.jsonl$/,ai=500,ci=new Map});import{existsSync as ha,readFileSync as $p,readdirSync as bb}from"node:fs";import{join as vp}from"node:path";import{simpleGit as $b}from"simple-git";function Sb(t){let e=t.split(`
43
- `),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function Tb(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
44
- `),a=s.findIndex(y=>y.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 y=m;y<s.length;y++){let g=(s[y]??"").trim();if(g===""){m=y+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(g);if(!$)break;let T=($[1]??"").trim().toLowerCase(),C=($[2]??"").trim(),S=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(g);S&&(d=parseInt(S[1]??"",10)),T==="tasks"&&(p=C),l.has(T)||u.push(g),m=y+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,h=s.slice(m).join(`
45
- `).replace(/^\n+/,""),k=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",h].join(`
46
- `);return{content:k.endsWith(`
47
- `)?k:k+`
48
- `,supersedes:d}}function Rb(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
49
-
50
- - **Status:** superseded by ADR-${r}`):n}function Ib(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(`
41
+ `:""))}async function _b(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
42
+ `).map(r=>r.trim()).filter(Boolean)}function $e(t,e){if(Ib(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=pi(Ep(t,e)),n=pi(t+"/");if(r!==pi(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Sp,Cb,Ab,Tp,ui,di,tt=v(()=>{"use strict";xt();Sp=3,Cb=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),Ab=/^model\/derived\//,Tp=/^tasks\/[^/]+\/comments\.jsonl$/,ui=500,di=new Map});import{existsSync as ba,readFileSync as Ip,readdirSync as jb}from"node:fs";import{join as Cp}from"node:path";import{simpleGit as Nb}from"simple-git";function Lb(t){let e=t.split(`
43
+ `),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function Mb(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
44
+ `),a=s.findIndex(w=>w.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,f=a>=0?a+1:0;for(let w=f;w<s.length;w++){let h=(s[w]??"").trim();if(h===""){f=w+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(h);if(!$)break;let x=($[1]??"").trim().toLowerCase(),R=($[2]??"").trim(),S=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(h);S&&(d=parseInt(S[1]??"",10)),x==="tasks"&&(p=R),l.has(x)||u.push(h),f=w+1}let m=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(f).join(`
45
+ `).replace(/^\n+/,""),y=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${m}`,...u,"",g].join(`
46
+ `);return{content:y.endsWith(`
47
+ `)?y:y+`
48
+ `,supersedes:d}}function Ub(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
49
+
50
+ - **Status:** superseded by ADR-${r}`):n}function Bb(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((n,o)=>n.num-o.num)){let n=String(r.num).padStart(4,"0"),o=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${n} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${o}`)}return e.join(`
51
51
  `)+`
52
- `}async function xp(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await $b(t).pull(void 0,void 0,["--rebase"])}catch{}let i=k=>o==="staging"?`adr/DRAFT-${k}.md`:`tasks/${e}/adr/DRAFT-${k}.md`,s=[],a=[];for(let k of r){let y=we(t,i(k));if(!ha(y)){a.push(k);continue}s.push({slug:k,content:$p(y,"utf-8")})}let c=vp(t,"adr"),l=new Map;if(ha(c))for(let k of bb(c)){let y=vb.exec(k);!y||k===xb||l.set(k,{num:parseInt(y[1]??"",10),slug:y[2]??"",content:$p(vp(c,k),"utf-8")})}let u=Math.max(0,...[...l.values()].map(k=>k.num))+1,p=new Map,d=[],m=[];for(let k of s){if([...l.entries()].find(([,S])=>S.slug===k.slug&&S.content.includes(e))){m.push(k.slug);continue}let g=u++,$=`${String(g).padStart(4,"0")}-${k.slug}.md`,{content:T,supersedes:C}=Tb(k.content,g,k.slug,e,n);if(p.set($,T),l.set($,{num:g,slug:k.slug,content:T}),d.push(`adr/${$}`),C!==null){let S=[...l.keys()].find(b=>b.startsWith(`${String(C).padStart(4,"0")}-`));if(S&&S!==$){let b=Rb(p.get(S)??l.get(S).content,g);p.set(S,b),l.set(S,{...l.get(S),content:b})}}}let f=[];if(o==="staging")for(let k of s)ha(we(t,`adr/DRAFT-${k.slug}.md`))&&f.push({path:`adr/DRAFT-${k.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let k=[...l.entries()].map(([y,g])=>({num:g.num,file:y,header:Sb(g.content)}));p.set("INDEX.md",Ib(k))}for(let[k,y]of p.entries())f.push({path:`adr/${k}`,content:y});let h=d.length>0?`adr(${e}): promote ${s.map(k=>k.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Se(t,f,h),{promoted:d,skipped:m,missing:a}}var vb,xb,Sp=x(()=>{"use strict";tt();vb=/^(\d{4})-(.+)\.md$/,xb="0000-template.md"});import{existsSync as Tp,readFileSync as Cb}from"node:fs";import{join as Rp}from"node:path";function Ab(t){for(let e of[ct,An]){let r=Rp(t,e);if(Tp(r))try{return al(Cb(r,"utf-8"))}catch{return 0}}return 0}function Pb(t,e,r,n=4){let o=e<n,i=o?cl(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function ui(t,e){return Pb(e,Ab(t),r=>Tp(Rp(t,r)))}var ga=x(()=>{"use strict";K()});import{existsSync as Ft,readFileSync as Yr,readdirSync as Ep}from"node:fs";import{join as ya}from"node:path";import{simpleGit as Cp}from"simple-git";import{parse as Ap}from"yaml";function Pp(t){try{let e=we(t,jo);if(!Ft(e))return null;let r=Ap(Yr(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Nr.test(n)?null:{prefix:n}}catch{return null}}function _p(t){return`# Built-in tracker configuration \u2014 shared by every team member.
52
+ `}async function Ap(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Nb(t).pull(void 0,void 0,["--rebase"])}catch{}let i=y=>o==="staging"?`adr/DRAFT-${y}.md`:`tasks/${e}/adr/DRAFT-${y}.md`,s=[],a=[];for(let y of r){let w=$e(t,i(y));if(!ba(w)){a.push(y);continue}s.push({slug:y,content:Ip(w,"utf-8")})}let c=Cp(t,"adr"),l=new Map;if(ba(c))for(let y of jb(c)){let w=Ob.exec(y);!w||y===Db||l.set(y,{num:parseInt(w[1]??"",10),slug:w[2]??"",content:Ip(Cp(c,y),"utf-8")})}let u=Math.max(0,...[...l.values()].map(y=>y.num))+1,p=new Map,d=[],f=[];for(let y of s){if([...l.entries()].find(([,S])=>S.slug===y.slug&&S.content.includes(e))){f.push(y.slug);continue}let h=u++,$=`${String(h).padStart(4,"0")}-${y.slug}.md`,{content:x,supersedes:R}=Mb(y.content,h,y.slug,e,n);if(p.set($,x),l.set($,{num:h,slug:y.slug,content:x}),d.push(`adr/${$}`),R!==null){let S=[...l.keys()].find(b=>b.startsWith(`${String(R).padStart(4,"0")}-`));if(S&&S!==$){let b=Ub(p.get(S)??l.get(S).content,h);p.set(S,b),l.set(S,{...l.get(S),content:b})}}}let m=[];if(o==="staging")for(let y of s)ba($e(t,`adr/DRAFT-${y.slug}.md`))&&m.push({path:`adr/DRAFT-${y.slug}.md`,content:"",deleted:!0});if(d.length===0&&m.length===0)return{promoted:d,skipped:f,missing:a};if(d.length>0){let y=[...l.entries()].map(([w,h])=>({num:h.num,file:w,header:Lb(h.content)}));p.set("INDEX.md",Bb(y))}for(let[y,w]of p.entries())m.push({path:`adr/${y}`,content:w});let g=d.length>0?`adr(${e}): promote ${s.map(y=>y.slug).join(", ")}`:`adr(${e}): drop stale staged ${f.join(", ")}`;return await Ee(t,m,g),{promoted:d,skipped:f,missing:a}}var Ob,Db,Pp=v(()=>{"use strict";tt();Ob=/^(\d{4})-(.+)\.md$/,Db="0000-template.md"});import{existsSync as _p,readFileSync as Gb}from"node:fs";import{join as jp}from"node:path";function Kb(t){for(let e of[ut,Pn]){let r=jp(t,e);if(_p(r))try{return fl(Gb(r,"utf-8"))}catch{return 0}}return 0}function Hb(t,e,r,n=4){let o=e<n,i=o?ml(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function fi(t,e){return Hb(e,Kb(t),r=>_p(jp(t,r)))}var $a=v(()=>{"use strict";G()});import{existsSync as Ft,readFileSync as Yr,readdirSync as Op}from"node:fs";import{join as va}from"node:path";import{simpleGit as Dp}from"simple-git";import{parse as Lp}from"yaml";function Mp(t){try{let e=$e(t,Do);if(!Ft(e))return null;let r=Lp(Yr(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Or.test(n)?null:{prefix:n}}catch{return null}}function Up(t){return`# Built-in tracker configuration \u2014 shared by every team member.
53
53
  # The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
54
54
  # later would orphan existing tasks/<KEY>/ directories.
55
55
  prefix: ${t}
@@ -57,15 +57,15 @@ prefix: ${t}
57
57
  # Statuses are the built-in default set for now:
58
58
  # Backlog | To Do | In Progress | Review | Done | Rejected
59
59
  # A configurable status set / pipeline mapping is a planned extension.
60
- `}function ka(t=0){return`${t}
61
- `}function _b(t){return t==="depends_on"||t==="subtask"}function jb(t){let e;try{e=Ap(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=ou.includes(r.type)?r.type:_o,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;_b(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 wa(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(`
60
+ `}function xa(t=0){return`${t}
61
+ `}function Wb(t){return t==="depends_on"||t==="subtask"}function qb(t){let e;try{e=Lp(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=du.includes(r.type)?r.type:Oo,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;Wb(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 Sa(t){let e=[`key: ${t.key}`,`title: ${JSON.stringify(t.title)}`,`type: ${t.type}`,`status: ${JSON.stringify(t.status)}`];if(t.assignee&&e.push(`assignee: ${JSON.stringify(t.assignee)}`),t.links.length>0){e.push("links:");for(let r of t.links)e.push(` - type: ${r.type}`,` target: ${r.targetKey}`)}return e.push(`created: ${t.created}`,`updated: ${t.updated}`),e.join(`
62
62
  `)+`
63
- `}function qn(t,e){let r=we(t,On(e));return Ft(r)?jb(Yr(r,"utf-8")):null}function jp(t){let e=ya(t,"tasks");if(!Ft(e))return[];let r=[];for(let n of Ep(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=qn(t,n.name);o&&r.push(o)}return r}function Nb(t,e){let r=we(t,`tasks/${e}/task.md`);if(!Ft(r))return;let n=Yr(r,"utf-8").split(`
63
+ `}function zn(t,e){let r=$e(t,Ln(e));return Ft(r)?qb(Yr(r,"utf-8")):null}function Bp(t){let e=va(t,"tasks");if(!Ft(e))return[];let r=[];for(let n of Op(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=zn(t,n.name);o&&r.push(o)}return r}function Yb(t,e){let r=$e(t,`tasks/${e}/task.md`);if(!Ft(r))return;let n=Yr(r,"utf-8").split(`
64
64
  `),o=n.indexOf("---");if(o<0)return;let i=n.slice(o+1),s=i.lastIndexOf("## Attachments");s>=0&&i.slice(s+1).every(u=>u.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(u.trim()))&&(i=i.slice(0,s));let a=i.join(`
65
- `).trim();if(!(!a||a==="_(no description)_"))return a}function Vn(t,e,r={}){let n=r.withDescription?Nb(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:Ob(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function Ob(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Db(t){let e=we(t,Nn);if(!Ft(e))return 0;let r=Number.parseInt(Yr(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function Lb(t,e){let r=ya(t,"tasks");if(!Ft(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of Ep(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 Mb(t,e){return Math.max(Db(t),Lb(t,e))+1}async function Np(t,e,r,n){return fa(t,()=>Ub(t,e,r,n))}async function Ub(t,e,r,n){if(!Ft(ya(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Yn(t);let o=null;for(let i=0;i<Ip;i++){let s=Mb(t,e),a=`${e}-${s}`,c=[...r(a),{path:Nn,content:ka(s)}];try{return await ma(t,c,n(a)),a}catch(l){if(o=l,await Fb(t,n(a)),await Yn(t),Bb(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Ip} attempts: ${o instanceof Error?o.message:String(o)}`)}function Bb(t,e){for(let r of e){let n=we(t,r.path);if(!Ft(n)||(r.encoding==="base64"?Yr(n).toString("base64"):Yr(n,"utf-8"))!==r.content)return!1}return!0}async function Yn(t){let e=Cp(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 Fb(t,e){let r=Cp(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
65
+ `).trim();if(!(!a||a==="_(no description)_"))return a}function Jn(t,e,r={}){let n=r.withDescription?Yb(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:Vb(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function Vb(t){return t.charAt(0).toUpperCase()+t.slice(1)}function zb(t){let e=$e(t,Dn);if(!Ft(e))return 0;let r=Number.parseInt(Yr(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function Jb(t,e){let r=va(t,"tasks");if(!Ft(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of Op(r,{withFileTypes:!0})){if(!i.isDirectory())continue;let s=n.exec(i.name);if(!s)continue;let a=Number.parseInt(s[1],10);Number.isFinite(a)&&a>o&&(o=a)}return o}function Xb(t,e){return Math.max(zb(t),Jb(t,e))+1}async function Fp(t,e,r,n){return ka(t,()=>Qb(t,e,r,n))}async function Qb(t,e,r,n){if(!Ft(va(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Vn(t);let o=null;for(let i=0;i<Np;i++){let s=Xb(t,e),a=`${e}-${s}`,c=[...r(a),{path:Dn,content:xa(s)}];try{return await wa(t,c,n(a)),a}catch(l){if(o=l,await e$(t,n(a)),await Vn(t),Zb(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Np} attempts: ${o instanceof Error?o.message:String(o)}`)}function Zb(t,e){for(let r of e){let n=$e(t,r.path);if(!Ft(n)||(r.encoding==="base64"?Yr(n).toString("base64"):Yr(n,"utf-8"))!==r.content)return!1}return!0}async function Vn(t){let e=Dp(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 e$(t,e){let r=Dp(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
66
66
  `)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
67
67
  `).some(i=>i.trim()===e.split(`
68
- `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Ip,di=x(()=>{"use strict";K();tt();Ip=5});function qr(t,e,r,n){return[{path:"README.md",content:Zb(t,e)},{path:".gitignore",content:qb()},{path:"CLAUDE.md",content:zb(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Vb()},{path:"knowledge/README.md",content:Jb()},{path:"knowledge/build.yaml",content:Qb()},{path:"actions/README.md",content:Xb()},{path:"model/README.md",content:Kb()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Yb()},{path:"adr/README.md",content:Gb()},{path:"adr/0000-template.md",content:Hb()},{path:"adr/INDEX.md",content:Wb()},{path:ct,content:Ro()},...t.trackerProvider==="internal"?[{path:jo,content:_p(t.youtrackProjectKey??As)},{path:Nn,content:ka()}]:[]]}function Kb(){return`# model/ \u2014 the project map
68
+ `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Np,mi=v(()=>{"use strict";G();tt();Np=5});function Vr(t,e,r,n){return[{path:"README.md",content:p$(t,e)},{path:".gitignore",content:s$()},{path:"CLAUDE.md",content:c$(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:a$()},{path:"knowledge/README.md",content:l$()},{path:"knowledge/build.yaml",content:d$()},{path:"actions/README.md",content:u$()},{path:"model/README.md",content:t$()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:i$()},{path:"adr/README.md",content:r$()},{path:"adr/0000-template.md",content:n$()},{path:"adr/INDEX.md",content:o$()},{path:ut,content:Io()},...t.trackerProvider==="internal"?[{path:Do,content:Up(t.youtrackProjectKey??Os)},{path:Dn,content:xa()}]:[]]}function t$(){return`# model/ \u2014 the project map
69
69
 
70
70
  A graph of the project built from **git history and task artifacts**: files
71
71
  and directories connected by the fact of changing together and the fact of
@@ -92,7 +92,7 @@ asset \u2014 treat it like \`knowledge/\`.
92
92
 
93
93
  Every YAML file carries \`modelFormatVersion\`; a reader that meets a
94
94
  different version treats it as "rebuild needed", not as an error.
95
- `}function Gb(){return`# ADR \u2014 architecture decision records
95
+ `}function r$(){return`# ADR \u2014 architecture decision records
96
96
 
97
97
  Accepted architectural decisions of this project \u2014 its **framework**. The
98
98
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -120,7 +120,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
120
120
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
121
121
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
122
122
  open a PR to this repository.
123
- `}function Hb(){return`# ADR-NNNN: <title>
123
+ `}function n$(){return`# ADR-NNNN: <title>
124
124
 
125
125
  - **Status:** accepted | superseded by ADR-NNNN
126
126
  - **Date:** YYYY-MM-DD
@@ -142,12 +142,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
142
142
  ## Alternatives considered
143
143
 
144
144
  - **<alternative>** \u2014 why it was rejected.
145
- `}function Wb(){return`# ADR index
145
+ `}function o$(){return`# ADR index
146
146
 
147
147
  <!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
148
148
 
149
149
  (no accepted ADRs yet)
150
- `}function Yb(){return`# Audit
150
+ `}function i$(){return`# Audit
151
151
 
152
152
  Pipeline event logs. Naming is per-writer: each codepipe
153
153
  project appends only to its own file \u2014
@@ -156,14 +156,14 @@ project appends only to its own file \u2014
156
156
 
157
157
  \u2014 so several team members' CLIs never contend on one file. Do not create a
158
158
  shared aggregate here.
159
- `}function ht(t,e,r,n,o="auto",i=ut,s){let a=t.trackerProvider==="internal";return{projectYaml:a?e$(t,o):t$(t,r,n,o),regimenYaml:r$(t.automationLevel,a?!0:e,a,i,s)}}function qb(){return`# codepipe project config is local to each member's workspace
159
+ `}function yt(t,e,r,n,o="auto",i=pt,s){let a=t.trackerProvider==="internal";return{projectYaml:a?f$(t,o):m$(t,r,n,o),regimenYaml:g$(t.automationLevel,a?!0:e,a,i,s)}}function s$(){return`# codepipe project config is local to each member's workspace
160
160
  project.yaml
161
161
  regimen.yaml
162
162
 
163
163
  # codepipe runtime
164
164
  session.log
165
165
  apply-queue.json
166
- `}function Vb(){return`# Index prompt
166
+ `}function a$(){return`# Index prompt
167
167
 
168
168
  You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
169
169
  navigation map of this project's repositories and save it to the Context Repo, so
@@ -220,7 +220,7 @@ current working directory; write nothing else under the Context Repo.
220
220
  Keep both durable and skimmable \u2014 they are read at the start of every future
221
221
  task. Prefer structure (headings, bullet lists) over prose. If a repository is
222
222
  empty or unavailable, say so briefly rather than inventing content.
223
- `}function zb(t){return`# Project context for the CodePipe agent
223
+ `}function c$(t){return`# Project context for the CodePipe agent
224
224
 
225
225
  Instructions for AI agents working on **${t.name}** tasks. Claude Code
226
226
  auto-loads this file when the Context Repo is mounted. Keep it short and
@@ -248,7 +248,7 @@ project's architectural invariants: read them at the start of a task and treat
248
248
  them as binding. New or changed decisions do **not** go here directly \u2014 during
249
249
  analysis you draft them as task artifacts, and they are promoted into \`adr/\`
250
250
  only after the analysis is approved.
251
- `}function Jb(){return`# Knowledge
251
+ `}function l$(){return`# Knowledge
252
252
 
253
253
  Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
254
254
  **memory** across tasks. Architectural decisions, domain rules,
@@ -265,7 +265,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
265
265
  concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
266
266
  REGENERATED from the entries by the index job: don't hand-edit it, and treat
267
267
  any merge conflict in it as noise (either side converges on the next run).
268
- `}function Xb(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
268
+ `}function u$(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
269
269
 
270
270
  One \`<id>.yml\` per action. Every file here appears as a button on the
271
271
  project's **RUN** tab; an action with \`params\` opens a small wizard first.
@@ -304,7 +304,7 @@ steps:
304
304
  Parameter values are passed to the commands **only as env vars** \u2014 reference
305
305
  them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
306
306
  command text itself.
307
- `}function Qb(){return`# BUILD phase config. Discovered & maintained by the agent.
307
+ `}function d$(){return`# BUILD phase config. Discovered & maintained by the agent.
308
308
  # Steps run in a rootless Podman container in the SANDBOX, before the PR.
309
309
  # Success = every step exits 0. Credentials are NOT available inside the container.
310
310
  #
@@ -320,7 +320,7 @@ command text itself.
320
320
  # - name: test
321
321
  # run: npm test
322
322
  # timeout_sec: 600 # per-step timeout (optional, default 600)
323
- `}function Zb(t,e){return`# ${e.name}
323
+ `}function p$(t,e){return`# ${e.name}
324
324
 
325
325
  Context Repo for the **${t.name}** project (CodePipe).
326
326
 
@@ -346,7 +346,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
346
346
  pipeline \u2014 don't edit them by hand.
347
347
 
348
348
  Automation level: **${t.automationLevel}**.
349
- `}function e$(t,e="auto"){return`# Project description for CodePipe.
349
+ `}function f$(t,e="auto"){return`# Project description for CodePipe.
350
350
  id: ${t.projectId}
351
351
  name: ${t.name}
352
352
 
@@ -367,17 +367,24 @@ apply:
367
367
  # Branch (must keep the <TASK_ID> placeholder).
368
368
  branch:
369
369
  pattern: codepipe/<TASK_ID>
370
-
370
+ ${Gp(t)}
371
371
  repos:
372
- ${Op(t)}
373
- `}function Op(t){return t.repos.length===0?` [] # add repos here
372
+ ${Kp(t)}
373
+ `}function Gp(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
374
+ # Languages the agent writes in, per area. \`auto\` = mirror the language of
375
+ # the user's material. Also editable from the dashboard: project card \u2192
376
+ # Settings \u2192 Language.
377
+ language:
378
+ ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
379
+ `)}
380
+ `}function Kp(t){return t.repos.length===0?` [] # add repos here
374
381
  `:t.repos.map(e=>` - name: ${e.name}
375
382
  host: ${e.host}
376
383
  owner: ${e.owner}
377
384
  repo: ${e.repoName}
378
385
  mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
379
386
  default_branch: ${e.defaultBranch}`:"")).join(`
380
- `)}function t$(t,e,r,n="auto"){let o=e?`
387
+ `)}function m$(t,e,r,n="auto"){let o=e?`
381
388
  tracker_url: ${e}`:`
382
389
  # tracker_url: https://your.youtrack.cloud`,i=r?`require_assignee: true
383
390
  assignee: ${r}`:`require_assignee: false
@@ -425,7 +432,7 @@ ${Op(t)}
425
432
  # non-empty assignee. assignee only takes effect when require_assignee=true.
426
433
  ${i}`:` # project_key: \u2026
427
434
  # tracker_url: https://your.youtrack.cloud
428
- poll_interval_sec: 60`,a=Op(t);return`# Project description for CodePipe.
435
+ poll_interval_sec: 60`,a=Kp(t);return`# Project description for CodePipe.
429
436
  id: ${t.projectId}
430
437
  name: ${t.name}
431
438
 
@@ -453,10 +460,10 @@ apply:
453
460
  # Branch (must keep the <TASK_ID> placeholder).
454
461
  branch:
455
462
  pattern: codepipe/<TASK_ID>
456
-
463
+ ${Gp(t)}
457
464
  repos:
458
465
  ${a}
459
- `}function r$(t,e,r=!1,n=ut,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
466
+ `}function g$(t,e,r=!1,n=pt,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
460
467
  # model in the recommended per-role split, so CodePipe set a single default
461
468
  # your subscription can serve for all roles. Tune per role later from the
462
469
  # dashboard (Project Settings \u2192 llm.models) or by editing this file.
@@ -607,47 +614,47 @@ ${a}
607
614
  # # While this key stays commented out, the project keeps its current mode \u2014
608
615
  # # only new projects start on cluster-pr. Uncomment and set a value to switch.
609
616
  # mode: cluster-pr
610
- `}var yr=x(()=>{"use strict";K();di()});import{existsSync as Dp,mkdirSync as n$,mkdtempSync as o$,rmSync as Lp,writeFileSync as Mp}from"node:fs";import{tmpdir as i$}from"node:os";import{dirname as s$,join as pi}from"node:path";import{simpleGit as ba}from"simple-git";function a$(t){return`codepipe/context-migration-v${t}`}function c$(t){let e=ll(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 \`${ct}\` stamp (renamed from \`${An}\``,"when the legacy file is present). Hand-edited files are never touched.","","## Format changes",""];for(let n of e){r.push(`- **v${n.version}** \u2014 ${n.summary}`);for(let o of n.addedPaths)r.push(` - \`${o}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
611
- `)}async function Up(t,e,r,n){let o=ba(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=ui(t,e);if(!i.outdated)return i;let s=a$(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 l$(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=Qe(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:c$(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 l$(t,e,r,n,o,i,s){let a=ba(t),c=o$(pi(i$(),"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(qr(l,u).map(h=>[h.path,h.content])),d=0;for(let h of n.missingPaths){if(h===ct)continue;let k=p.get(h);if(k==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let y=pi(c,h);Dp(y)||(n$(s$(y),{recursive:!0}),Mp(y,k),d++)}Mp(pi(c,ct),Ro(n.currentVersion)),d++;let m=pi(c,An);Dp(m)&&(Lp(m,{force:!0}),d++);let f=ba(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(()=>{}),Lp(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var Bp=x(()=>{"use strict";K();Ot();ga();yr()});import{existsSync as u$,readFileSync as d$,writeFileSync as p$}from"node:fs";import{homedir as f$}from"node:os";import{join as Fp}from"node:path";import{parseDocument as m$}from"yaml";function h$(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function g$(t,e){let r=m$(t);return r.set("repos",e.map(h$)),r.toString()}function y$(t,e){let r=[Fp(f$(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Fp(e,"project.yaml")),r}function zn(t,e,r){let n=[],o=[];for(let i of y$(t,r))if(u$(i))try{let s=d$(i,"utf-8"),a=g$(s,e);a!==s&&(p$(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}var $a=x(()=>{"use strict"});import{createCipheriv as k$,createDecipheriv as w$,createHash as b$,createPrivateKey as $$,createPublicKey as va,diffieHellman as Kp,generateKeyPairSync as Gp,hkdfSync as Hp,randomBytes as v$}from"node:crypto";function fi(){let{publicKey:t,privateKey:e}=Gp("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Pe(t){let e=Buffer.from(t,"base64");return(b$("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function xt(t,e){let r=va({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Gp("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Kp({privateKey:o,publicKey:r}),c=Buffer.from(Hp("sha256",a,Buffer.concat([i,s]),Wp,32)),l=v$(12),u=k$("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 Vr(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=$$({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=va({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=va(n).export({type:"spki",format:"der"}),a=Kp({privateKey:n,publicKey:o}),c=Buffer.from(Hp("sha256",a,Buffer.concat([i,s]),Wp,32)),l=w$("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 Wp,He=x(()=>{"use strict";Wp=Buffer.from("devpipe-sealedbox-v1","utf-8")});function x$(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function Yp(t,e,r,n){let o=x$(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=Bo(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=xt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}var qp=x(()=>{"use strict";He();ue()});function Jn(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 Xn(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 Qn(t,e=process.env){if(!t)return!1;let r=`https://${or}:${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 xa(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 Vp(t,e=process.env){return xa(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Jn(t,e),e)}function zp(t,e=process.env){return xa(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Xn(t,e),e)}function Jp(t,e=process.env){return xa(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${or}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Qn(t,e),e)}var mi=x(()=>{"use strict";K()});function Xp(t){let e=W(t);if(!e)return null;if(!e.sealKey){let r=fi();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ne(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Pe(e.sealKey.publicKey)}}async function Qp(t,e,r,n){let o;try{o=JSON.parse(Vr(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=W(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 _t(o.token);return i.github={token:o.token},zr(i,()=>{process.env.GH_TOKEN=o.token,Vp(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Nt(o.token);return i.gitlab={token:o.token},zr(i,()=>{process.env.GITLAB_TOKEN=o.token,zp(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 jt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},zr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Jp(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 Lt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},zr(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 Mt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},zr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},zr(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 zr(t,e){ne(t),e()}var Zp=x(()=>{"use strict";He();ue();Ot();ar();Fr();mi()});import{spawn as S$}from"node:child_process";function R$(t,e,r,n,o,i){let s={...t},a=(c,l)=>{At(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 rf(t){let{def:e,onEvent:r}=t,n=R$(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
612
- `,o.length>ef&&(o=o.slice(o.length-ef))},s=(a,c)=>{let l=c.length>tf?c.slice(0,tf)+"\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 I$(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 I$(t,e,r,n,o){return new Promise(i=>{let s=S$("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Ol)*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:h=>{f+=h.toString("utf-8");let k;for(;(k=f.indexOf(`
613
- `))!==-1;)o(m,f.slice(0,k).replace(/\r$/,"")),f=f.slice(k+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?T$:m??(f?1:0))})})}var T$,ef,tf,nf=x(()=>{"use strict";K();T$=124,ef=16*1024,tf=4e3});import{existsSync as E$,readFileSync as C$,statSync as of}from"node:fs";function A$(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function af(t,e){let r=we(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!E$(r)||!of(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=of(r);if(n>sf)throw new Error(`file too large: ${e} is ${n} bytes (limit ${sf})`);let o=C$(r);return A$(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}var sf,cf=x(()=>{"use strict";tt();sf=2*1024*1024});import{existsSync as P$,readFileSync as _$,writeFileSync as j$}from"node:fs";import{join as N$}from"node:path";import{parseDocument as O$}from"yaml";async function lf(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=Kl(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=N$(t,o);if(!P$(s))throw new Error(`${o} not found in context repo (${t})`);let a=O$(_$(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);j$(s,a.toString()),n.push(o)}return{files:n}}var uf=x(()=>{"use strict";K()});import{existsSync as D$,readFileSync as L$,writeFileSync as M$}from"node:fs";import{join as U$}from"node:path";import{isMap as df,parseDocument as B$}from"yaml";async function pf(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||!zl(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=U$(t,"project.yaml");if(!D$(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=B$(L$(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>df(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!df(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),M$(o,i.toString()),{repoName:r,defaultBranch:n}}var ff=x(()=>{"use strict";K()});import{existsSync as Sa,readFileSync as Ta,writeFileSync as F$}from"node:fs";import{join as hi}from"node:path";import{parseDocument as Ra}from"yaml";async function mf(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=hi(t,"project.yaml");if(!Sa(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Ra(Ta(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=hi(t,"regimen.yaml");if(!Sa(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Ra(Ta(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)F$(hi(t,i.path),i.content);return{files:r.map(i=>i.path)}}function gi(t){if(!t)return"Stage";try{let e=hi(t,"project.yaml");if(!Sa(e))return"Stage";let n=Ra(Ta(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var Ia=x(()=>{"use strict"});import{existsSync as hf,readFileSync as gf,readdirSync as K$}from"node:fs";import{join as Ea}from"node:path";import{simpleGit as G$}from"simple-git";function H$(t,e){let r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(e);if(!r)return null;let n="",o="";for(let s of r[1].split(`
614
- `)){let a=/^(\w+):\s*(.+)$/.exec(s.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let i=r[2].trim();return!n||!o||!i||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:i,source:t}}function W$(t,e){let r=Ea(t,`tasks/${e}/annotations`);if(!hf(r))return[];let n=[];for(let o of K$(r).sort())if(o.endsWith(".md")){try{let i=H$(o,gf(Ea(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=yl)break}return n}async function yf(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=G$(o),p=[];for(let d of W$(e,r)){if(d.repo!==n)continue;let m=pe("code",n,d.path);if(!a.has(m))continue;let f=l.get(m);if(!f)continue;let h=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,Y$),k=dl(f),y=Ea(e,k),g=p.find(I=>I.path===k),$=g?.content??(hf(y)?gf(y,"utf-8"):null),T=`<!-- ${r}${h?`:${h}`:""} -->`;if($?.includes(T))continue;let C=$??`---
615
- entityId: ${f}
617
+ `}var kr=v(()=>{"use strict";G();mi()});import{existsSync as Hp,mkdirSync as h$,mkdtempSync as y$,rmSync as Wp,writeFileSync as qp}from"node:fs";import{tmpdir as k$}from"node:os";import{dirname as w$,join as gi}from"node:path";import{simpleGit as Ta}from"simple-git";function b$(t){return`codepipe/context-migration-v${t}`}function $$(t){let e=gl(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 \`${ut}\` stamp (renamed from \`${Pn}\``,"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(`
618
+ `)}async function Yp(t,e,r,n){let o=Ta(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=fi(t,e);if(!i.outdated)return i;let s=b$(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 v$(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=Qe(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:$$(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 v$(t,e,r,n,o,i,s){let a=Ta(t),c=y$(gi(k$(),"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(Vr(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===ut)continue;let y=p.get(g);if(y==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let w=gi(c,g);Hp(w)||(h$(w$(w),{recursive:!0}),qp(w,y),d++)}qp(gi(c,ut),Io(n.currentVersion)),d++;let f=gi(c,Pn);Hp(f)&&(Wp(f,{force:!0}),d++);let m=Ta(c);await m.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await m.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await m.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Wp(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var Vp=v(()=>{"use strict";G();Ot();$a();kr()});import{existsSync as x$,readFileSync as S$,writeFileSync as T$}from"node:fs";import{homedir as E$}from"node:os";import{join as zp}from"node:path";import{parseDocument as R$}from"yaml";function I$(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function C$(t,e){let r=R$(t);return r.set("repos",e.map(I$)),r.toString()}function A$(t,e){let r=[zp(E$(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(zp(e,"project.yaml")),r}function Xn(t,e,r){let n=[],o=[];for(let i of A$(t,r))if(x$(i))try{let s=S$(i,"utf-8"),a=C$(s,e);a!==s&&(T$(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}var Ea=v(()=>{"use strict"});import{createCipheriv as P$,createDecipheriv as _$,createHash as j$,createPrivateKey as N$,createPublicKey as Ra,diffieHellman as Jp,generateKeyPairSync as Xp,hkdfSync as Qp,randomBytes as O$}from"node:crypto";function hi(){let{publicKey:t,privateKey:e}=Xp("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function je(t){let e=Buffer.from(t,"base64");return(j$("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function St(t,e){let r=Ra({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Xp("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Jp({privateKey:o,publicKey:r}),c=Buffer.from(Qp("sha256",a,Buffer.concat([i,s]),Zp,32)),l=O$(12),u=P$("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),f=u.getAuthTag(),m={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:f.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(m),"utf-8").toString("base64")}function zr(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=N$({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Ra({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Ra(n).export({type:"spki",format:"der"}),a=Jp({privateKey:n,publicKey:o}),c=Buffer.from(Qp("sha256",a,Buffer.concat([i,s]),Zp,32)),l=_$("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 Zp,He=v(()=>{"use strict";Zp=Buffer.from("devpipe-sealedbox-v1","utf-8")});function D$(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function ef(t,e,r,n){let o=D$(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=Ko(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=St(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}var tf=v(()=>{"use strict";He();de()});function Qn(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Zn(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 eo(t,e=process.env){if(!t)return!1;let r=`https://${ir}:${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 Ia(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 rf(t,e=process.env){return Ia(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Qn(t,e),e)}function nf(t,e=process.env){return Ia(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Zn(t,e),e)}function of(t,e=process.env){return Ia(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${ir}:${encodeURIComponent(t)}@bitbucket.org/`,()=>eo(t,e),e)}var yi=v(()=>{"use strict";G()});function sf(t){let e=Y(t);if(!e)return null;if(!e.sealKey){let r=hi();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},re(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:je(e.sealKey.publicKey)}}async function af(t,e,r,n){let o;try{o=JSON.parse(zr(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=Y(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await _t(o.token);return i.github={token:o.token},Jr(i,()=>{process.env.GH_TOKEN=o.token,rf(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Nt(o.token);return i.gitlab={token:o.token},Jr(i,()=>{process.env.GITLAB_TOKEN=o.token,nf(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 jt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Jr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,of(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 Lt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Jr(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 Mt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Jr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Jr(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 Jr(t,e){re(t),e()}var cf=v(()=>{"use strict";He();de();Ot();cr();Gr();yi()});import{spawn as L$}from"node:child_process";function U$(t,e,r,n,o,i){let s={...t},a=(c,l)=>{At(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 df(t){let{def:e,onEvent:r}=t,n=U$(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
619
+ `,o.length>lf&&(o=o.slice(o.length-lf))},s=(a,c)=>{let l=c.length>uf?c.slice(0,uf)+"\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 B$(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 B$(t,e,r,n,o){return new Promise(i=>{let s=L$("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Fl)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=f=>{let m="";return{data:g=>{m+=g.toString("utf-8");let y;for(;(y=m.indexOf(`
620
+ `))!==-1;)o(f,m.slice(0,y).replace(/\r$/,"")),m=m.slice(y+1)},flush:()=>{m.length>0&&o(f,m.replace(/\r$/,"")),m=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",f=>{clearTimeout(l),o("stderr",`spawn failed: ${f.message}`),i(127)}),s.on("close",(f,m)=>{clearTimeout(l),p.flush(),d.flush(),i(a?M$:f??(m?1:0))})})}var M$,lf,uf,pf=v(()=>{"use strict";G();M$=124,lf=16*1024,uf=4e3});import{existsSync as F$,readFileSync as G$,statSync as ff}from"node:fs";function K$(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function gf(t,e){let r=$e(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!F$(r)||!ff(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=ff(r);if(n>mf)throw new Error(`file too large: ${e} is ${n} bytes (limit ${mf})`);let o=G$(r);return K$(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}var mf,hf=v(()=>{"use strict";tt();mf=2*1024*1024});import{existsSync as H$,readFileSync as W$,writeFileSync as q$}from"node:fs";import{join as Y$}from"node:path";import{parseDocument as V$}from"yaml";async function yf(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=zl(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=Y$(t,o);if(!H$(s))throw new Error(`${o} not found in context repo (${t})`);let a=V$(W$(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);q$(s,a.toString()),n.push(o)}return{files:n}}var kf=v(()=>{"use strict";G()});import{existsSync as z$,readFileSync as J$,writeFileSync as X$}from"node:fs";import{join as Q$}from"node:path";import{isMap as wf,parseDocument as Z$}from"yaml";async function bf(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||!ru(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=Q$(t,"project.yaml");if(!z$(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Z$(J$(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>wf(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!wf(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),X$(o,i.toString()),{repoName:r,defaultBranch:n}}var $f=v(()=>{"use strict";G()});import{existsSync as Ca,readFileSync as Aa,writeFileSync as ev}from"node:fs";import{join as ki}from"node:path";import{parseDocument as Pa}from"yaml";async function vf(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=ki(t,"project.yaml");if(!Ca(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Pa(Aa(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=ki(t,"regimen.yaml");if(!Ca(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Pa(Aa(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)ev(ki(t,i.path),i.content);return{files:r.map(i=>i.path)}}function wi(t){if(!t)return"Stage";try{let e=ki(t,"project.yaml");if(!Ca(e))return"Stage";let n=Pa(Aa(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var _a=v(()=>{"use strict"});import{existsSync as xf,readFileSync as Sf,readdirSync as tv}from"node:fs";import{join as ja}from"node:path";import{simpleGit as rv}from"simple-git";function nv(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(`
621
+ `)){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 ov(t,e){let r=ja(t,`tasks/${e}/annotations`);if(!xf(r))return[];let n=[];for(let o of tv(r).sort())if(o.endsWith(".md")){try{let i=nv(o,Sf(ja(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=xl)break}return n}async function Tf(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=rv(o),p=[];for(let d of ov(e,r)){if(d.repo!==n)continue;let f=fe("code",n,d.path);if(!a.has(f))continue;let m=l.get(f);if(!m)continue;let g=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,iv),y=yl(m),w=ja(e,y),h=p.find(E=>E.path===y),$=h?.content??(xf(w)?Sf(w,"utf-8"):null),x=`<!-- ${r}${g?`:${g}`:""} -->`;if($?.includes(x))continue;let R=$??`---
622
+ entityId: ${m}
616
623
  ---
617
624
 
618
625
  # Intent log
619
626
 
620
627
  Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
621
- `,S=["",`## ${s} \u2014 ${r}`,T,"",d.body,""].join(`
622
- `),b=C+S;g?g.content=b:p.push({path:k,content:b})}return p}var Y$,kf=x(()=>{"use strict";K();Y$=12});import{existsSync as Ca,readFileSync as Aa}from"node:fs";import{join as Pa}from"node:path";import{simpleGit as bf}from"simple-git";import{parse as _a}from"yaml";function vf(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(q$.source,"g")}function xf(t){let e=Pa(t,"project.yaml");if(Ca(e))try{let o=_a(Aa(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=Pa(t,"tracker","config.yaml");if(Ca(r))try{let o=_a(Aa(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function Sf(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 V$(t,e,r){let o=await bf(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
623
- `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),m=l.slice(2),f=ja.exec(u)??$f.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:Sf(c[3]),churn:l+u})}return i}async function z$(t,e){let n=await bf(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
624
- `)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:Sf(s[3]),churn:a+c})}return o}function J$(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(ja,"").trim();else if(c.prNumber!==null)u=`PR-${c.prNumber}`,p=c.subject.replace(ja,"").replace($f,"").replace(/^from\s+/,"").trim()||c.subject;else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let k of c.files){let y=o.get(k.path)??k.path;s(y)||m.set(y,(m.get(y)??0)+k.churn)}if(m.size===0)continue;let h=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(h.title=p),c.timeSec>0&&(h.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),h.commits.push(c.sha);for(let[k,y]of m){let g=pe("code",e,k),$=h.files.find(T=>T.key===g);if($)$.churn=($.churn??0)+y;else{let T=i.get(g);h.files.push({key:g,...T?{entityId:T}:{},churn:y})}}if(d.length>0){let k=new Set([...h.links?.tasks??[],...d]);k.delete(u),h.links={...h.links??{},tasks:[...k].sort()}}a.set(u,h)}return a}function wf(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 Tf(t){let e=await V$(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 z$(t.repoDir,r.sha))}return J$({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored})}function Rf(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?wf(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=wf(yi(t,i),s);if(!a){o++;continue}n.push({path:Cr(i),content:_n(a)})}return{files:n,skippedPipeline:o}}function yi(t,e){let r=Pa(t,Cr(e));if(!Ca(r))return null;try{let n=Ct(_a(Aa(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var q$,ja,$f,Na=x(()=>{"use strict";K();q$=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,ja=/\(#(\d+)\)\s*$/,$f=/^Merge pull request #(\d+)\b/});import{simpleGit as X$}from"simple-git";async function Ef(t,e,r){let o=await X$(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
625
- `))if(a.startsWith("@@@ ")){let[c,l]=a.slice(4).trim().split(/\s+/);s={sha:c??"",timeSec:Number(l??0),files:[]},i.push(s)}else a.trim()&&s&&s.files.push(a.trim());return i}function ki(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=Q(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=Q(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function Cf(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 y of n){let g=new Set;for(let S of y.files){let b=o.get(S)??S;!i.has(b)||s(b)||g.add(b)}if(g.size<2||g.size>a.commitFileCap)continue;let $=Math.max(0,r-y.timeSec),T=Math.pow(.5,$/c),C=[...g].sort();for(let S of C)l.set(S,(l.get(S)??0)+T);for(let S=0;S<C.length;S++)for(let b=S+1;b<C.length;b++){let I=`${C[S]}\0${C[b]}`;u.set(I,(u.get(I)??0)+T),p.set(I,(p.get(I)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[y,g]of u){if((p.get(y)??0)<a.supportMin)continue;let[$,T]=y.split("\0"),C=(l.get($)??0)+(l.get(T)??0)-g,S=C>0?g/C:0;S<m||d.push({a:$,b:T,weight:Math.round(S*If)/If})}let f=new Map;for(let y of d)for(let g of[y.a,y.b])f.has(g)||f.set(g,[]),f.get(g).push(y);let h=new Map;for(let[,y]of f)y.sort((g,$)=>$.weight-g.weight||(g.a<$.a?-1:g.a>$.a?1:g.b<$.b?-1:1)).slice(0,a.topK).forEach(g=>h.set(g,(h.get(g)??0)+1));return[...h.entries()].filter(([,y])=>y===2).map(([y])=>y).map(y=>({kind:"correlates",from:pe("code",e,y.a),to:pe("code",e,y.b),weight:y.weight})).sort((y,g)=>y.from<g.from?-1:y.from>g.from?1:y.to<g.to?-1:1)}var Jr,If,wi=x(()=>{"use strict";K();Jr=["package-lock.json","pnpm-lock.yaml","yarn.lock"];If=1e4});import{createHash as Q$}from"node:crypto";function ev(t,e,r,n){for(let o=0;;o++){let s=`e_${Q$("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function Af(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(b=>b.entityId)),d=new Set,m=[],f=new Map,h=(b,I)=>{d.add(I),f.set(I,b.entityId),m.push(b)},k=[];for(let b of u)l.has(b.currentKey)&&!d.has(b.currentKey)?h({...b,status:"active",lastSeen:r},b.currentKey):k.push(b);let y=[],g=[];for(let b of k){let I=Q(b.currentKey),M=I?i.get(I.path):void 0;if(I&&M){let G=pe(I.level,e,M.finalPath);if(l.has(G)&&!d.has(G)){y.push({entity:b,newKey:G,untilCommit:M.commit}),d.add(G);continue}}g.push(b)}let $=[];if(s){let b=new Map;for(let M of c){if(d.has(M))continue;let G=Q(M);if(G?.level!=="code")continue;let E=a.get(G.path);E&&b.set(E,b.has(E)?null:M)}let I=new Map;for(let M of g){let G=Q(M.currentKey);if(G?.level!=="code")continue;let E=s.get(G.path);E&&I.set(E,I.has(E)?null:M)}for(let M of g){let G=Q(M.currentKey),E=G?.level==="code"?s.get(G.path):void 0,w=E?b.get(E):void 0;E&&w&&I.get(E)===M&&!d.has(w)?(y.push({entity:M,newKey:w,untilCommit:r}),d.add(w)):$.push(M)}}else $.push(...g);let T=new Map;for(let b of y){let I=Q(b.entity.currentKey),M=Q(b.newKey);if(I?.level!=="code"||!M)continue;let G=I.path,E=M.path;for(let w=G.lastIndexOf("/");w>0;w=G.lastIndexOf("/",w-1)){let N=G.slice(0,w),_=G.slice(w+1);if(!E.endsWith(`/${_}`))continue;let B=E.slice(0,E.length-_.length-1);if(B===N)continue;let V=`${N}\0${B}`,ee=T.get(V);T.set(V,{count:(ee?.count??0)+1,commit:ee&&ee.commit>b.untilCommit?ee.commit:b.untilCommit})}}let C=[...T.entries()].filter(([,b])=>b.count>=Z$).map(([b,I])=>{let[M,G]=b.split("\0");return{from:M,to:G,commit:I.commit}}).sort((b,I)=>I.from.length-b.from.length||(b.from<I.from?-1:1)),S=[];for(let b of $){let I=Q(b.currentKey),M=!1;if(I?.level==="component")for(let G of C){let E=null;if(I.path===G.from?E=G.to:I.path.startsWith(`${G.from}/`)&&(E=G.to+I.path.slice(G.from.length)),E===null)continue;let w=pe("component",e,E);l.has(w)&&!d.has(w)&&(y.push({entity:b,newKey:w,untilCommit:G.commit}),d.add(w),M=!0);break}M||S.push(b)}for(let b of y.sort((I,M)=>I.newKey<M.newKey?-1:1))h({...b.entity,currentKey:b.newKey,aliases:[...b.entity.aliases??[],{key:b.entity.currentKey,until:b.untilCommit}],status:"active",lastSeen:r},b.newKey);for(let b of S)m.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let I=ev(e,b,r,p);p.add(I),h({entityId:I,currentKey:b,firstSeen:n,lastSeen:r,status:"active"},b)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}var Z$,Pf=x(()=>{"use strict";K();Z$=5});import{simpleGit as tv}from"simple-git";async function _f(t,e,r){let n=tv(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
626
- `).map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let c=(await n.raw(["diff","-M","-C","-z","--name-status","--diff-filter=R",`${s}^`,s]).catch(()=>"")).split("\0");for(let l=0;l+2<c.length;){if(!(c[l]??"").startsWith("R")){l+=1;continue}let p=c[l+1]??"",d=c[l+2]??"";p&&d&&i.push({fromPath:p,toPath:d,commit:s}),l+=3}}return i}function jf(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 Nf=x(()=>{"use strict"});function bi(t){return pe("container",t,rv)}function Of(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function Df(t,e,r,n){let o=[],i=u=>{let p=pe("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:Of(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,nv)}},s=(u,p)=>{let d=pe("component",t,u),m=n.get(d);return{key:d,level:"component",label:Of(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],h=[p,...m.map(i)],k=[...m.map(y=>({kind:"contains",from:p.key,to:pe("code",t,y.path)})),...f.map(y=>({kind:"contains",from:p.key,to:pe("component",t,y)}))];c(u,h,k)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Et(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:ml(t,u),content:xl(m)})},l={key:bi(t),level:"container",label:t,...n.get(bi(t))?{entityId:n.get(bi(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 Lf(t,e){let r=[bi(t)];for(let n of e.components)r.push(pe("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(pe("code",t,o.path));return r.sort()}var rv,nv,Mf=x(()=>{"use strict";K();rv=".";nv=12});import{simpleGit as Bf}from"simple-git";function kr(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 Kf(t,e="HEAD"){let r=Bf(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 Zn(t,n)}}async function Zn(t,e){let n=await Bf(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 Uf(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Gf(t,e){let r=[...t].sort((f,h)=>f.path<h.path?-1:f.path>h.path?1:0),n=new Map,o=new Map;for(let f of r){let h=Uf(f.path);n.has(h)||n.set(h,[]),n.get(h).push(f);let k=h;for(;k!=="";){let y=Uf(k);o.has(y)||o.set(y,new Set),o.get(y).add(k),k=y}}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(),h=(n.get(f)??[]).length+i(f).length;if(h<=s)s-=h,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 h=n.get(f)??[];p.set(f,h),d.set(f,i(f)),m+=h.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 Ff,eo=x(()=>{"use strict";Ff=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Hf,readFileSync as Wf}from"node:fs";import{join as Yf}from"node:path";import{simpleGit as ov}from"simple-git";import{parse as qf}from"yaml";function Xr(t){let e={ignore:Ff,containerNodeCap:iv,cochange:{...ze},issueKeyPattern:null,enabled:!1},r=Yf(t,"regimen.yaml");if(!Hf(r))return e;let n;try{n=qf(Wf(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===!0}}function Oa(t,e){let r=Yf(t,Io(e));if(!Hf(r))return null;let n=qf(Wf(r,"utf-8")),o=Ao(n);if(!o.ok)throw new Error(`model: ${Io(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Da(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await Kf(r,t.ref??"HEAD"),s=kr(o.ignore),a=i.files.filter(g=>!s(g.path)),c=Gf(a,o.containerNodeCap),l=Oa(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await ov(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=jf(await _f(r,l.builtFromCommit,i.commit)),p=new Map((await Zn(r,l.builtFromCommit)).map(T=>[T.path,T.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(g=>[g.path,g.blobHash])));let d=new Map(a.map(g=>[g.path,g.blobHash])),m=Af({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Lf(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=Df(e,i.commit,c,m.byKey),h=kr([...o.ignore,...Jr]),k=Cf({repo:e,headTimeSec:i.commitTimeSec,filesets:await Ef(r,i.commit,o.cochange.windowCommits),pathToCurrent:ki(m.table),currentPaths:new Set(a.map(g=>g.path)),ignored:h,settings:o.cochange}),y=[{path:Io(e),content:Sl(m.table)},...f.files.map(g=>({path:g.path,content:g.content})),{path:pl(e),content:Ar({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:k})}];return{repo:e,headCommit:i.commit,files:y,emittedShardPaths:new Set(f.files.map(g=>g.path)),counts:{...f.counts,correlates:k.length},identityTable:m.table,entityByKey:m.byKey}}var iv,La=x(()=>{"use strict";K();wi();Pf();Nf();Mf();eo();iv=1500});import{existsSync as zf,readFileSync as Jf,readdirSync as sv}from"node:fs";import{join as Ma}from"node:path";import{parse as Xf}from"yaml";function av(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 Qf(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<gl)return null;let s=i/Math.min(n.size,o.size),a=av(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*Vf)/Vf;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[ke(t.taskKey),ke(e.taskKey)]:[ke(e.taskKey),ke(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function Zf(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=Qf(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 em(t,e,r,n){let o=ke(r),i=t.filter(a=>a.from!==o&&a.to!==o),s=e.find(a=>a.taskKey===r);if(s){let a=new Set(s.files.map(c=>c.key));for(let c of e){if(c.taskKey===r||!c.files.some(u=>a.has(u.key)))continue;let l=Qf(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 $i(t){let e=Ma(t,"model/facts/events");if(!zf(e))return[];let r=[];for(let n of sv(e).sort())if(n.endsWith(".yaml"))try{let o=Ct(Xf(Jf(Ma(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function tm(t){let e=Ma(t,Er);if(!zf(e))return[];try{let r=Eo(Xf(Jf(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function vi(t){return Ar({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Vf,Ua=x(()=>{"use strict";K();Vf=1e4});var to={};Rr(to,{collectSearchRows:()=>nm,readContextIndexHub:()=>cv,rebuildSearchIndex:()=>om,searchIndexPath:()=>Ri,searchModelIndex:()=>lv,toFtsQuery:()=>im});import{existsSync as Zr,readFileSync as Qr,readdirSync as Si}from"node:fs";import{join as rt}from"node:path";import{parse as Ti}from"yaml";function Ri(t){return rt(t,".git","codepipe-model-index.sqlite")}function cv(t){let e=rt(t,"regimen.yaml");if(!Zr(e))return"off";try{let n=Ti(Qr(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 rm(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function xi(t){return t.length>vs?t.slice(0,vs):t}function Ba(t){if(!Zr(t))return[];let e=[];for(let r of Si(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=rt(t,r.name);r.isDirectory()?e.push(...Ba(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function nm(t){let e=[];for(let i of Ba(rt(t,"model/derived/structure"))){let s;try{s=Ti(Qr(i,"utf-8"))}catch{continue}let a=Et(s);if(a.ok)for(let c of a.value.nodes){let l=Q(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:xi(`${l.path} ${c.label??""}`.trim())})}}let r=rt(t,"model/facts/events");if(Zr(r)){for(let i of Si(r).sort())if(i.endsWith(".yaml"))try{let s=Ct(Ti(Qr(rt(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:xi(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=rt(t,"model/facts/annotations");if(Zr(n)){let i=new Map;for(let s of Ba(rt(t,"model/facts/identity")))try{let a=Ti(Qr(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 Si(n).sort())if(s.endsWith(".md"))try{let a=Qr(rt(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:xi(c[2].trim())})}catch{}}let o=rt(t,"adr");if(Zr(o))for(let i of Si(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=Qr(rt(o,i),"utf-8").split(`
627
- `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:xi(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function om(t){let e=nm(t),r=await rm();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(Ri(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 im(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 lv(t,e,r){let n=await rm();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");Zr(Ri(t))||await om(t);let o=im(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),kl),s=new n.DatabaseSync(Ri(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
628
+ `,S=["",`## ${s} \u2014 ${r}`,x,"",d.body,""].join(`
629
+ `),b=R+S;h?h.content=b:p.push({path:y,content:b})}return p}var iv,Ef=v(()=>{"use strict";G();iv=12});import{existsSync as Na,readFileSync as Oa}from"node:fs";import{join as Da}from"node:path";import{simpleGit as If}from"simple-git";import{parse as La}from"yaml";function Af(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(sv.source,"g")}function Pf(t){let e=Da(t,"project.yaml");if(Na(e))try{let o=La(Oa(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=Da(t,"tracker","config.yaml");if(Na(r))try{let o=La(Oa(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function _f(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 av(t,e,r){let o=await If(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
630
+ `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),f=l.slice(2),m=Ma.exec(u)??Cf.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:m?Number(m[1]):null,isMerge:f.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:_f(c[3]),churn:l+u})}return i}async function cv(t,e){let n=await If(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
631
+ `)){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:_f(s[3]),churn:a+c})}return o}function lv(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(Ma,"").trim();else if(c.prNumber!==null)u=`PR-${c.prNumber}`,p=c.subject.replace(Ma,"").replace(Cf,"").replace(/^from\s+/,"").trim()||c.subject;else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let f=new Map;for(let y of c.files){let w=o.get(y.path)??y.path;s(w)||f.set(w,(f.get(w)??0)+y.churn)}if(f.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[y,w]of f){let h=fe("code",e,y),$=g.files.find(x=>x.key===h);if($)$.churn=($.churn??0)+w;else{let x=i.get(h);g.files.push({key:h,...x?{entityId:x}:{},churn:w})}}if(d.length>0){let y=new Set([...g.links?.tasks??[],...d]);y.delete(u),g.links={...g.links??{},tasks:[...y].sort()}}a.set(u,g)}return a}function Rf(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 jf(t){let e=await av(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 cv(t.repoDir,r.sha))}return lv({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored})}function Nf(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?Rf(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=Rf(bi(t,i),s);if(!a){o++;continue}n.push({path:Ar(i),content:jn(a)})}return{files:n,skippedPipeline:o}}function bi(t,e){let r=Da(t,Ar(e));if(!Na(r))return null;try{let n=Ct(La(Oa(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var sv,Ma,Cf,Ua=v(()=>{"use strict";G();sv=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Ma=/\(#(\d+)\)\s*$/,Cf=/^Merge pull request #(\d+)\b/});import{simpleGit as uv}from"simple-git";async function Df(t,e,r){let o=await uv(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
632
+ `))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 $i(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=Q(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=Q(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function Lf(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let h=new Set;for(let S of w.files){let b=o.get(S)??S;!i.has(b)||s(b)||h.add(b)}if(h.size<2||h.size>a.commitFileCap)continue;let $=Math.max(0,r-w.timeSec),x=Math.pow(.5,$/c),R=[...h].sort();for(let S of R)l.set(S,(l.get(S)??0)+x);for(let S=0;S<R.length;S++)for(let b=S+1;b<R.length;b++){let E=`${R[S]}\0${R[b]}`;u.set(E,(u.get(E)??0)+x),p.set(E,(p.get(E)??0)+1)}}let d=[],f=a.jaccardMinPct/100;for(let[w,h]of u){if((p.get(w)??0)<a.supportMin)continue;let[$,x]=w.split("\0"),R=(l.get($)??0)+(l.get(x)??0)-h,S=R>0?h/R:0;S<f||d.push({a:$,b:x,weight:Math.round(S*Of)/Of})}let m=new Map;for(let w of d)for(let h of[w.a,w.b])m.has(h)||m.set(h,[]),m.get(h).push(w);let g=new Map;for(let[,w]of m)w.sort((h,$)=>$.weight-h.weight||(h.a<$.a?-1:h.a>$.a?1:h.b<$.b?-1:1)).slice(0,a.topK).forEach(h=>g.set(h,(g.get(h)??0)+1));return[...g.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:fe("code",e,w.a),to:fe("code",e,w.b),weight:w.weight})).sort((w,h)=>w.from<h.from?-1:w.from>h.from?1:w.to<h.to?-1:1)}var Xr,Of,vi=v(()=>{"use strict";G();Xr=["package-lock.json","pnpm-lock.yaml","yarn.lock"];Of=1e4});import{createHash as dv}from"node:crypto";function fv(t,e,r,n){for(let o=0;;o++){let s=`e_${dv("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function Mf(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(b=>b.entityId)),d=new Set,f=[],m=new Map,g=(b,E)=>{d.add(E),m.set(E,b.entityId),f.push(b)},y=[];for(let b of u)l.has(b.currentKey)&&!d.has(b.currentKey)?g({...b,status:"active",lastSeen:r},b.currentKey):y.push(b);let w=[],h=[];for(let b of y){let E=Q(b.currentKey),O=E?i.get(E.path):void 0;if(E&&O){let B=fe(E.level,e,O.finalPath);if(l.has(B)&&!d.has(B)){w.push({entity:b,newKey:B,untilCommit:O.commit}),d.add(B);continue}}h.push(b)}let $=[];if(s){let b=new Map;for(let O of c){if(d.has(O))continue;let B=Q(O);if(B?.level!=="code")continue;let A=a.get(B.path);A&&b.set(A,b.has(A)?null:O)}let E=new Map;for(let O of h){let B=Q(O.currentKey);if(B?.level!=="code")continue;let A=s.get(B.path);A&&E.set(A,E.has(A)?null:O)}for(let O of h){let B=Q(O.currentKey),A=B?.level==="code"?s.get(B.path):void 0,k=A?b.get(A):void 0;A&&k&&E.get(A)===O&&!d.has(k)?(w.push({entity:O,newKey:k,untilCommit:r}),d.add(k)):$.push(O)}}else $.push(...h);let x=new Map;for(let b of w){let E=Q(b.entity.currentKey),O=Q(b.newKey);if(E?.level!=="code"||!O)continue;let B=E.path,A=O.path;for(let k=B.lastIndexOf("/");k>0;k=B.lastIndexOf("/",k-1)){let D=B.slice(0,k),j=B.slice(k+1);if(!A.endsWith(`/${j}`))continue;let K=A.slice(0,A.length-j.length-1);if(K===D)continue;let V=`${D}\0${K}`,ee=x.get(V);x.set(V,{count:(ee?.count??0)+1,commit:ee&&ee.commit>b.untilCommit?ee.commit:b.untilCommit})}}let R=[...x.entries()].filter(([,b])=>b.count>=pv).map(([b,E])=>{let[O,B]=b.split("\0");return{from:O,to:B,commit:E.commit}}).sort((b,E)=>E.from.length-b.from.length||(b.from<E.from?-1:1)),S=[];for(let b of $){let E=Q(b.currentKey),O=!1;if(E?.level==="component")for(let B of R){let A=null;if(E.path===B.from?A=B.to:E.path.startsWith(`${B.from}/`)&&(A=B.to+E.path.slice(B.from.length)),A===null)continue;let k=fe("component",e,A);l.has(k)&&!d.has(k)&&(w.push({entity:b,newKey:k,untilCommit:B.commit}),d.add(k),O=!0);break}O||S.push(b)}for(let b of w.sort((E,O)=>E.newKey<O.newKey?-1:1))g({...b.entity,currentKey:b.newKey,aliases:[...b.entity.aliases??[],{key:b.entity.currentKey,until:b.untilCommit}],status:"active",lastSeen:r},b.newKey);for(let b of S)f.push({...b,status:"orphaned"});for(let b of c){if(d.has(b))continue;let E=fv(e,b,r,p);p.add(E),g({entityId:E,currentKey:b,firstSeen:n,lastSeen:r,status:"active"},b)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:f},byKey:m}}var pv,Uf=v(()=>{"use strict";G();pv=5});import{simpleGit as mv}from"simple-git";async function Bf(t,e,r){let n=mv(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
633
+ `).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 Ff(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 Gf=v(()=>{"use strict"});function xi(t){return fe("container",t,gv)}function Kf(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function Hf(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:Kf(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,hv)}},s=(u,p)=>{let d=fe("component",t,u),f=n.get(d);return{key:d,level:"component",label:Kf(u),...f?{entityId:f}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let f=r.filesByDir.get(d)??[],m=r.childDirs.get(d)??[],g=[p,...f.map(i)],y=[...f.map(w=>({kind:"contains",from:p.key,to:fe("code",t,w.path)})),...m.map(w=>({kind:"contains",from:p.key,to:fe("component",t,w)}))];c(u,g,y)},c=(u,p,d)=>{let f={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},m=It(f);if(!m.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${m.errors.join("; ")}`);o.push({path:bl(t,u),content:Cl(f)})},l={key:xi(t),level:"container",label:t,...n.get(xi(t))?{entityId:n.get(xi(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 Wf(t,e){let r=[xi(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 gv,hv,qf=v(()=>{"use strict";G();gv=".";hv=12});import{simpleGit as Vf}from"simple-git";function wr(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function Jf(t,e="HEAD"){let r=Vf(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 to(t,n)}}async function to(t,e){let n=await Vf(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 Yf(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Xf(t,e){let r=[...t].sort((m,g)=>m.path<g.path?-1:m.path>g.path?1:0),n=new Map,o=new Map;for(let m of r){let g=Yf(m.path);n.has(g)||n.set(g,[]),n.get(g).push(m);let y=g;for(;y!=="";){let w=Yf(y);o.has(w)||o.set(w,new Set),o.get(w).add(y),y=w}}let i=m=>[...o.get(m)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let m=l.shift(),g=(n.get(m)??[]).length+i(m).length;if(g<=s)s-=g,c.add(m),l.push(...i(m));else{if(m==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(m)}}let u=[],p=new Map,d=new Map,f=0;for(let m of[...c].sort()){let g=n.get(m)??[];p.set(m,g),d.set(m,i(m)),f+=g.length,m!==""&&u.push(m)}for(let m of a)u.push(m);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:f}}}var zf,ro=v(()=>{"use strict";zf=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Qf,readFileSync as Zf}from"node:fs";import{join as em}from"node:path";import{simpleGit as yv}from"simple-git";import{parse as tm}from"yaml";function Qr(t){let e={ignore:zf,containerNodeCap:kv,cochange:{...ze},issueKeyPattern:null,enabled:!1},r=em(t,"regimen.yaml");if(!Qf(r))return e;let n;try{n=tm(Zf(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(f=>typeof f=="string"&&f.trim().length>0):e.ignore,c=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>0?f:m,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled===!0}}function Ba(t,e){let r=em(t,Co(e));if(!Qf(r))return null;let n=tm(Zf(r,"utf-8")),o=_o(n);if(!o.ok)throw new Error(`model: ${Co(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Fa(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await Jf(r,t.ref??"HEAD"),s=wr(o.ignore),a=i.files.filter(h=>!s(h.path)),c=Xf(a,o.containerNodeCap),l=Ba(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await yv(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=Ff(await Bf(r,l.builtFromCommit,i.commit)),p=new Map((await to(r,l.builtFromCommit)).map(x=>[x.path,x.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(h=>[h.path,h.blobHash])));let d=new Map(a.map(h=>[h.path,h.blobHash])),f=Mf({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Wf(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),m=Hf(e,i.commit,c,f.byKey),g=wr([...o.ignore,...Xr]),y=Lf({repo:e,headTimeSec:i.commitTimeSec,filesets:await Df(r,i.commit,o.cochange.windowCommits),pathToCurrent:$i(f.table),currentPaths:new Set(a.map(h=>h.path)),ignored:g,settings:o.cochange}),w=[{path:Co(e),content:Al(f.table)},...m.files.map(h=>({path:h.path,content:h.content})),{path:kl(e),content:Pr({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:y})}];return{repo:e,headCommit:i.commit,files:w,emittedShardPaths:new Set(m.files.map(h=>h.path)),counts:{...m.counts,correlates:y.length},identityTable:f.table,entityByKey:f.byKey}}var kv,Ga=v(()=>{"use strict";G();vi();Uf();Gf();qf();ro();kv=1500});import{existsSync as nm,readFileSync as om,readdirSync as wv}from"node:fs";import{join as Ka}from"node:path";import{parse as im}from"yaml";function bv(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 sm(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<vl)return null;let s=i/Math.min(n.size,o.size),a=bv(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*rm)/rm;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[be(t.taskKey),be(e.taskKey)]:[be(e.taskKey),be(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function am(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=sm(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 cm(t,e,r,n){let o=be(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=sm(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 Si(t){let e=Ka(t,"model/facts/events");if(!nm(e))return[];let r=[];for(let n of wv(e).sort())if(n.endsWith(".yaml"))try{let o=Ct(im(om(Ka(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function lm(t){let e=Ka(t,Cr);if(!nm(e))return[];try{let r=Ao(im(om(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Ti(t){return Pr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var rm,Ha=v(()=>{"use strict";G();rm=1e4});var no={};Rr(no,{collectSearchRows:()=>dm,readContextIndexHub:()=>$v,rebuildSearchIndex:()=>pm,searchIndexPath:()=>Ci,searchModelIndex:()=>vv,toFtsQuery:()=>fm});import{existsSync as en,readFileSync as Zr,readdirSync as Ri}from"node:fs";import{join as rt}from"node:path";import{parse as Ii}from"yaml";function Ci(t){return rt(t,".git","codepipe-model-index.sqlite")}function $v(t){let e=rt(t,"regimen.yaml");if(!en(e))return"off";try{let n=Ii(Zr(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 um(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Ei(t){return t.length>Es?t.slice(0,Es):t}function Wa(t){if(!en(t))return[];let e=[];for(let r of Ri(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=rt(t,r.name);r.isDirectory()?e.push(...Wa(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function dm(t){let e=[];for(let i of Wa(rt(t,"model/derived/structure"))){let s;try{s=Ii(Zr(i,"utf-8"))}catch{continue}let a=It(s);if(a.ok)for(let c of a.value.nodes){let l=Q(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Ei(`${l.path} ${c.label??""}`.trim())})}}let r=rt(t,"model/facts/events");if(en(r)){for(let i of Ri(r).sort())if(i.endsWith(".yaml"))try{let s=Ct(Ii(Zr(rt(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:Ei(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=rt(t,"model/facts/annotations");if(en(n)){let i=new Map;for(let s of Wa(rt(t,"model/facts/identity")))try{let a=Ii(Zr(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 Ri(n).sort())if(s.endsWith(".md"))try{let a=Zr(rt(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:Ei(c[2].trim())})}catch{}}let o=rt(t,"adr");if(en(o))for(let i of Ri(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=Zr(rt(o,i),"utf-8").split(`
634
+ `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:Ei(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function pm(t){let e=dm(t),r=await um();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(Ci(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 fm(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 vv(t,e,r){let n=await um();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");en(Ci(t))||await pm(t);let o=fm(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),Sl),s=new n.DatabaseSync(Ci(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
628
635
  bm25(model_fts) AS rank
629
- FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,i).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{s.close()}}var ro=x(()=>{"use strict";K()});var am={};Rr(am,{attachPrToBranchTasks:()=>Ga,attachPrToEvent:()=>sm,recordPipelineEvent:()=>Ka});import{existsSync as uv,readFileSync as dv}from"node:fs";import{join as pv}from"node:path";import{simpleGit as Fa}from"simple-git";async function fv(t,e){let n=await Fa(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
630
- `)){let s=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(i);if(!s)continue;let a=s[1]==="-"?0:Number(s[1]),c=s[2]==="-"?0:Number(s[2]);o.push({path:s[3],churn:a+c})}return o}function mv(t,e){let r=`tasks/${e}/SOLUTION.md`,n=pv(t,r);if(!uv(n))return{};try{let o=dv(n,"utf-8"),i=[...new Set(o.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:r,...i.length>0?{adr:i}:{}}}catch{return{solution:r}}}async function Ka(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Xr(e),a=kr([...s.ignore,...Jr]),c=await fv(r,i),l=(await Fa(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Oa(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 S=pe("code",n,C.path),b=p.get(S);d.push({key:S,...b?{entityId:b}:{},churn:C.churn})}if(d.length===0)return{recorded:!1};let m=mv(e,o),f=yi(e,o),h=f?.origin==="pipeline"?f.files.filter(C=>Q(C.key)?.repo!==n):[],k=f?.origin==="pipeline"?f.commits:[],y={modelFormatVersion:2,taskKey:o,origin:"pipeline",...f?.title?{title:f.title}:{},...l?{date:l}:{},commits:[...new Set([...k,i])],files:[...h,...d],links:{...f?.origin==="pipeline"?f.links:{},...m}};y.links&&Object.keys(y.links).length===0&&delete y.links;let g=[...$i(e).filter(C=>C.taskKey!==o),y],$=em(tm(e),g,o,s.cochange.halfLifeDays),T=await yf({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(C=>C.key)),identity:u}).catch(()=>[]);await Se(e,[{path:Cr(o),content:_n(y)},{path:Er,content:vi($)},...T],`model: task event ${o}`);{let{rebuildSearchIndex:C}=await Promise.resolve().then(()=>(ro(),to));await C(e).catch(()=>{})}return{recorded:!0}}async function Ga(t){let e=new Set([t.fallbackTaskKey]);try{let r=Fa(t.repoDir),n=(await r.raw(["rev-parse","--verify",`origin/${t.baseBranch}`]).catch(()=>r.raw(["rev-parse","--verify",t.baseBranch]))).trim(),o=await r.raw(["log","--format=%(trailers:key=CodePipe-Task,valueonly)",`${n}..${t.branchName}`]);for(let i of o.split(`
631
- `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await sm(t.contextDir,r,t.prUrl)}async function sm(t,e,r){let n=yi(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Se(t,[{path:Cr(e),content:_n(o)}],`model: pr link for ${e}`)}var Ha=x(()=>{"use strict";K();tt();kf();Na();La();wi();Ua();eo()});var no,Wa=x(()=>{"use strict";Ia();ar();no=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return gd(this.cfg,e)}getIssue(e,r){return yd(this.cfg,e,r??gi(this.contextDir))}listComments(e,r){return kd(this.cfg,e,r)}downloadAttachment(e){return hd(this.cfg,e)}updateStatus(e,r){return sd(this.cfg,e,r,gi(this.contextDir))}addComment(e,r,n){return ad(this.cfg,e,r)}createIssue(e){return ud(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,gi(this.contextDir))}editIssue(e,r){return cd(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return dd(this.cfg,e,r,n)}fetchStateFields(e){return bd(this.cfg,e)}}});import{existsSync as cm,readFileSync as hv,readdirSync as gv}from"node:fs";function Ii(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=bv(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:yv(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:wv(kv(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 Ei(t,e,r){if(r.length===0)return;let n=Ii(t,e,r),o=r.map(i=>i.issue.key);await Se(t,n,`sync(${o.join(", ")}): task data`)}function yv(t,e,r){let n=new Date(t.updatedAt).toISOString(),o=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${n}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){o.push("## Attachments","");for(let i of r)o.push(`- [${i}](attachments/${encodeURI(i)})`);o.push("")}return o.join(`
632
- `)}function kv(t,e,r){let n=new Map,o=we(t,`tasks/${e}/comments.jsonl`);if(cm(o))for(let i of hv(o,"utf-8").split(`
633
- `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){if(n.has(i.id))continue;let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=jr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function wv(t){return t.map(e=>JSON.stringify(e)).join(`
636
+ 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 oo=v(()=>{"use strict";G()});var gm={};Rr(gm,{attachPrToBranchTasks:()=>Va,attachPrToEvent:()=>mm,recordPipelineEvent:()=>Ya});import{existsSync as xv,readFileSync as Sv}from"node:fs";import{join as Tv}from"node:path";import{simpleGit as qa}from"simple-git";async function Ev(t,e){let n=await qa(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
637
+ `)){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 Rv(t,e){let r=`tasks/${e}/SOLUTION.md`,n=Tv(t,r);if(!xv(n))return{};try{let o=Sv(n,"utf-8"),i=[...new Set(o.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:r,...i.length>0?{adr:i}:{}}}catch{return{solution:r}}}async function Ya(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Qr(e),a=wr([...s.ignore,...Xr]),c=await Ev(r,i),l=(await qa(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Ba(e,n),u&&(p=new Map(u.entities.filter(R=>R.status==="active").map(R=>[R.currentKey,R.entityId])))}catch{}let d=[];for(let R of c){if(a(R.path))continue;let S=fe("code",n,R.path),b=p.get(S);d.push({key:S,...b?{entityId:b}:{},churn:R.churn})}if(d.length===0)return{recorded:!1};let f=Rv(e,o),m=bi(e,o),g=m?.origin==="pipeline"?m.files.filter(R=>Q(R.key)?.repo!==n):[],y=m?.origin==="pipeline"?m.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...m?.title?{title:m.title}:{},...l?{date:l}:{},commits:[...new Set([...y,i])],files:[...g,...d],links:{...m?.origin==="pipeline"?m.links:{},...f}};w.links&&Object.keys(w.links).length===0&&delete w.links;let h=[...Si(e).filter(R=>R.taskKey!==o),w],$=cm(lm(e),h,o,s.cochange.halfLifeDays),x=await Tf({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(R=>R.key)),identity:u}).catch(()=>[]);await Ee(e,[{path:Ar(o),content:jn(w)},{path:Cr,content:Ti($)},...x],`model: task event ${o}`);{let{rebuildSearchIndex:R}=await Promise.resolve().then(()=>(oo(),no));await R(e).catch(()=>{})}return{recorded:!0}}async function Va(t){let e=new Set([t.fallbackTaskKey]);try{let r=qa(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(`
638
+ `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await mm(t.contextDir,r,t.prUrl)}async function mm(t,e,r){let n=bi(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Ee(t,[{path:Ar(e),content:jn(o)}],`model: pr link for ${e}`)}var za=v(()=>{"use strict";G();tt();Ef();Ua();Ga();vi();Ha();ro()});var io,Ja=v(()=>{"use strict";_a();cr();io=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return xd(this.cfg,e)}getIssue(e,r){return Sd(this.cfg,e,r??wi(this.contextDir))}listComments(e,r){return Td(this.cfg,e,r)}downloadAttachment(e){return vd(this.cfg,e)}updateStatus(e,r){return fd(this.cfg,e,r,wi(this.contextDir))}addComment(e,r,n){return md(this.cfg,e,r)}createIssue(e){return yd(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,wi(this.contextDir))}editIssue(e,r){return gd(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return kd(this.cfg,e,r,n)}fetchStateFields(e){return Rd(this.cfg,e)}}});import{existsSync as hm,readFileSync as Iv,readdirSync as Cv}from"node:fs";function Ai(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=jv(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Av(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:_v(Pv(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 Pi(t,e,r){if(r.length===0)return;let n=Ai(t,e,r),o=r.map(i=>i.issue.key);await Ee(t,n,`sync(${o.join(", ")}): task data`)}function Av(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(`
639
+ `)}function Pv(t,e,r){let n=new Map,o=$e(t,`tasks/${e}/comments.jsonl`);if(hm(o))for(let i of Iv(o,"utf-8").split(`
640
+ `)){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=Nr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function _v(t){return t.map(e=>JSON.stringify(e)).join(`
634
641
  `)+(t.length>0?`
635
- `:"")}function bv(t,e,r){let n=[],o=we(t,`tasks/${e}/attachments`);if(cm(o))for(let i of gv(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var Ci=x(()=>{"use strict";K();tt()});import{existsSync as $v,readFileSync as vv}from"node:fs";import{randomBytes as xv}from"node:crypto";function lm(t,e){let r=we(t,`tasks/${e}/comments.jsonl`);if(!$v(r))return[];let n=[];for(let o of vv(r,"utf-8").split(`
636
- `)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}var oo,Ya=x(()=>{"use strict";K();tt();Ci();di();oo=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Yn(this.contextDir);let r=e.columns??[];return jp(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Vn(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=qn(this.contextDir,e);return r?Vn(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return lm(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 Yn(this.contextDir),!qn(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${xv(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=jr(r);s&&(i.parsedCommand=s);let c=[...lm(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
642
+ `:"")}function jv(t,e,r){let n=[],o=$e(t,`tasks/${e}/attachments`);if(hm(o))for(let i of Cv(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var _i=v(()=>{"use strict";G();tt()});import{existsSync as Nv,readFileSync as Ov}from"node:fs";import{randomBytes as Dv}from"node:crypto";function ym(t,e){let r=$e(t,`tasks/${e}/comments.jsonl`);if(!Nv(r))return[];let n=[];for(let o of Ov(r,"utf-8").split(`
643
+ `)){let i=o.trim();if(i)try{let s=JSON.parse(i);s&&typeof s.id=="string"&&typeof s.body=="string"&&n.push(s)}catch{}}return n}var so,Xa=v(()=>{"use strict";G();tt();_i();mi();so=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Vn(this.contextDir);let r=e.columns??[];return Bp(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Jn(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=zn(this.contextDir,e);return r?Jn(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return ym(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 Vn(this.contextDir),!zn(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${Dv(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Nr(r);s&&(i.parsedCommand=s);let c=[...ym(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
637
644
  `)+`
638
- `;return await Se(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:i.id}}async createIssue(e){let r=new Date().toISOString(),n=await Np(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:Ps.statusColumns}]}async mutateRecord(e,r,n){let o=qn(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Vn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:On(e),content:wa(i)},...Ii(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Se(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:_o,status:r.targetStatus,links:[],created:n,updated:n},i=Vn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:On(e),content:wa(o)},...Ii(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}}});import{existsSync as um,readFileSync as dm}from"node:fs";import{join as pm}from"node:path";import{parseDocument as fm}from"yaml";function qa(t){if(!t)return"youtrack";try{let e=pm(t,"project.yaml");return um(e)&&fm(dm(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function gt(t){let e=qa(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=Pp(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Sv(n);return i?{ok:!0,kind:e,provider:new oo(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=od();return r?{ok:!0,kind:e,provider:new no(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Sv(t){try{let e=pm(t,"project.yaml");if(!um(e))return null;let r=fm(dm(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Ai=x(()=>{"use strict";ar();Wa();Ya();di();Wa();Ya()});async function en(t,e){let n=(Pi.get(t)??Promise.resolve()).catch(()=>{}).then(e);Pi.set(t,n);try{return await n}finally{Pi.get(t)===n&&Pi.delete(t)}}async function mm(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;lr(`[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 en(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Re(i,r.name,t.baseDir),{commit:c,pushed:l}=await Vd(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let u=e.taskId.split(":")[1]??"";u&&await Ka({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:u,commitSha:c}).catch(p=>{lr(`[model] task event for ${u} failed: ${p instanceof Error?p.message:String(p)}`)})}return ce({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return en(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Re(i,r.name,t.baseDir);return await zd(s,a,{branchName:e.branchName,force:e.force}),ce({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return en(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Re(i,r.name,t.baseDir),{commit:c,pushed:l}=await Jd(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ce({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return z("no repo spec");let i=Qe(r),s=await i.createPullRequest(r,e);if(t.contextDir){let a=e.taskId.split(":")[1]??"",c=e.taskId.split(":",2)[0]??"?";a&&await Ga({contextDir:t.contextDir,repoDir:Re(c,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:a,prUrl:s.url}).catch(l=>{lr(`[model] pr link for ${a} failed: ${l instanceof Error?l.message:String(l)}`)})}return ce({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return z("no repo spec");let i=Qe(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ce({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return z("no repo spec");let i=Qe(r);return await i.closePR(r,e.prNumber,e.comment),ce({prNumber:e.prNumber,host:i.name})}case"rewrite_cluster_branch":{if(!r)return z("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return en(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Re(i,r.name,t.baseDir),{commit:c,dropped:l}=await Qd(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ce({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 en(`${i}/${r.name}`,async()=>{let s=await dr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Re(i,r.name,t.baseDir),{mergedSha:c}=await Zd(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ce({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return z("no repo spec");let i=t.cloneUrlOverride??Gn(r),a=(await ep(i)).filter(u=>tp(u,e.issueKey)),c=Qe(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 ce({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return z("no repo spec");let i=Qe(r);return await i.addPRComment(r,e.prNumber,e.body),ce({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=gt({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ce({issueId:t.trackerIssueId,newStatus:e.newStatus})):z("no tracker_issue_id provided"):z(i.error)}case"tracker_comment":{let i=gt({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 ce({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=gt({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 ce({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=gt({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 ce({applied:s})}case"set_project_setting":{if(!t.contextDir)return z("no context repo clone on this CLI");let i=await lf(t.contextDir,e.edits);return ce({files:i.files})}case"tracker_edit":{let i=gt({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 Ei(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ce({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return z("no context repo clone on this CLI");let i=await mf(t.contextDir,e);return ce({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return z("no context repo clone on this CLI");let i=await pf(t.contextDir,e);return ce({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ce({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 ce({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}=oi(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=Ll(c,e.input);if(!l.ok)return z(l.error);let u=pp(t.contextDir),p=W(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),en(`${e.projectId}/${r.name}`,async()=>{await dr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=Re(e.projectId,r.name,t.baseDir),f=await rf({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:h=>i(e.runId,h)});return ce({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=af(t.contextDir,e.path);return ce({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(()=>(ro(),to)),s=await i(t.contextDir,e.q,e.limit);return ce({hits:s})}case"model_drift":return z("model_drift requires a local workspace (handled by the daemon)");case"local_apply":return z("local_apply 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 ce(t){return{status:"done",result:t}}function z(t){return{status:"failed",error:t}}var Pi,hm=x(()=>{"use strict";K();sa();nf();cf();ue();uf();ff();Ia();Ot();Zo();Kr();Ha();Ai();Ci();Pi=new Map});import{existsSync as Tv,mkdtempSync as Rv,rmSync as Iv}from"node:fs";import{tmpdir as Ev}from"node:os";import{join as Va}from"node:path";import{simpleGit as gm}from"simple-git";async function ym(t,e,r){let n=[];for(let a of e){let c=t.repos.find(u=>u.name===a.repoName);if(!c)return{ok:!1,error:`repo "${a.repoName}" not in project.yaml \u2014 run /sync`};let l=Va(t.root,c.mountAs);if(!Tv(Va(l,".git")))return{ok:!1,error:`${c.mountAs}/ not cloned \u2014 run /sync first`};n.push({payload:a,dir:l,mountAs:c.mountAs,defaultBranch:c.defaultBranch})}let o=[];for(let a of n){let c=gm(a.dir),l=a.payload;try{await c.fetch()}catch(m){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${io(m)}`}}let u=`origin/${l.baseRef}`;await _v(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(m){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${io(m)}`}}let d;try{d=await Kn(c,l.deliverySha,()=>pr(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(m){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${io(m)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let i=[],s=[];for(let a of o){let c=await jv(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await Av(a);await a.git.raw(["branch","-f",a.branch,u]),i.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),s.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await Pv(i,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${io(l)} (rolled back all repos)`}}}return{ok:!0,repos:s}}async function Av(t){let e=Rv(Va(Ev(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=gm(e);try{await r.raw([...Cv,"cherry-pick",t.deliveryCommit])}catch(n){throw await r.raw(["cherry-pick","--abort"]).catch(()=>{}),n}return(await r.revparse(["HEAD"])).trim()}finally{await t.git.raw(["worktree","remove","--force",e]).catch(()=>{}),Iv(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function Pv(t,e){for(let r of t)try{r.priorSha?await r.git.raw(["branch","-f",r.branch,r.priorSha]):await r.git.raw(["branch","-D",r.branch])}catch(n){e.warn(`[local-apply] rollback of ${r.mountAs}#${r.branch} failed: ${io(n)} \u2014 check manually`)}}async function _v(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function jv(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function io(t){return t instanceof Error?t.message.trim():String(t)}var Cv,km=x(()=>{"use strict";Kr();Cv=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as Nv}from"node:os";import{existsSync as Ov,mkdirSync as Dv,readFileSync as Lv,writeFileSync as Mv}from"node:fs";import{dirname as Uv,join as Bv}from"node:path";function za(){return Y("FARM_PINS")??Bv(Nv(),".codepipe","farm-pins.json")}function wm(){let t=za();if(!Ov(t))return{};try{return JSON.parse(Lv(t,"utf-8"))}catch{return{}}}function Fv(t){let e=za();Dv(Uv(e),{recursive:!0}),Mv(e,JSON.stringify(t,null,2)+`
639
- `,{mode:384})}function Kv(t){return wm()[t]}function _i(t,e){let r=wm();r[t]=e,Fv(r)}function ji(t,e){let r=Pe(e),n=Kv(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 ${za()}.`);return r}var Ja=x(()=>{"use strict";Ae();He()});import{existsSync as bm,readFileSync as $m}from"node:fs";import{join as vm}from"node:path";async function xm(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=Pe(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");ji(e.farmId,e.farmPublicKey);let s=W(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await oe(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=vm(r,"project.yaml"),m=vm(r,"regimen.yaml");bm(d)&&bm(m)?c={projectYaml:$m(d,"utf-8"),regimenYaml:$m(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=xt(e.farmPublicKey,JSON.stringify(l));_i(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await Xo(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}var Sm=x(()=>{"use strict";He();Ja();xe();ue()});import{homedir as Gv}from"node:os";import{existsSync as Hv,mkdirSync as Wv,readFileSync as Yv,writeFileSync as qv}from"node:fs";import{dirname as Vv,join as zv}from"node:path";function Xa(){return Y("RUNNER_PINS")??zv(Gv(),".codepipe","runner-pins.json")}function Tm(){let t=Xa();if(!Hv(t))return{};try{return JSON.parse(Yv(t,"utf-8"))}catch{return{}}}function Jv(t){let e=Xa();Wv(Vv(e),{recursive:!0}),qv(e,JSON.stringify(t,null,2)+`
640
- `,{mode:384})}function Xv(t){return Tm()[t]}function Qa(t,e){let r=Tm();r[t]=e,Jv(r)}function Rm(t,e){let r=Pe(e),n=Xv(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 ${Xa()}.`);return r}var Im=x(()=>{"use strict";Ae();He()});async function Em(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Cm(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}async function Pm(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(Pe(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Rm(e.runnerId,e.runnerPublicKey);let i=W(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 _m(t,e,r,n=Am){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 Pm(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:[ql(e.runnerId)]},c=xt(e.runnerPublicKey,JSON.stringify(a));Qa(e.runnerId,e.fingerprint),r.info(`[ghr] registration token for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let l=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:c});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:l.ok,...l.runners?{runners:l.runners}:{},...l.error?{error:l.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function jm(t,e,r,n=Am){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 Pm(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=xt(e.runnerPublicKey,JSON.stringify(c));Qa(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var Cm,Qv,Am,Nm=x(()=>{"use strict";K();He();Im();xe();ue();Cm=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});Qv={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Cm(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)=>Em(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Em(t,e,r,"remove-token")},Am={api:Qv,fetchProject:oe,provisionOnRunner:jd,teardownOnRunner:Nd}});function Zv(t){return Be.test(t)?At(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Be}`}function Dm(t,e,r,n){let o=Zv(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Vr(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>Om)return{ok:!1,detail:`secret value too large (max ${Om} chars)`};try{return Pu(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Lm(t,e){try{return _u(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}var Om,Mm=x(()=>{"use strict";K();He();ue();Om=16*1024});function ex(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Ni,Um=x(()=>{"use strict";Ot();Ni=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=Qe(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof sr){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Qe(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=ex(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}}});function Bm(t){let{description:e,...r}=t;return r}function tx(t){let{body:e,...r}=t;return r}function rx(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 nx(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 Fm(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Oi,Km=x(()=>{"use strict";K();Ci();Ai();Oi=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??(()=>gt({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 $=e.stageField?{stageField:e.stageField}:{},T=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},S=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(S){let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[I,M]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...$,...T}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...$})]),G=new Map;for(let E of[...I,...M])G.set(E.id,E);o=[...G.values()]}else{let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:b,...$,...T})}}catch($){this.log.warn(`[yt-sync] listIssues failed: ${$ instanceof Error?$.message:String($)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let $ of o){if(s.add($.id),a.has($.status))continue;let T=await Fm(r,$.id,e.sinceMs,this.log);T&&i.set($.id,T)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let T=await Fm(r,$,e.sinceMs,this.log);if(T&&T.length>0&&i.set($,T),e.requireAssignee||T&&T.length>0){let C=await nx(r,$,e.stageField,this.log);if(C)c.push(C);else if(T&&T.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter($=>!a.has($.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($=>({issue:$,comments:i.get($.id)??[],attachments:u.get($.id)??[]}));try{await Ei(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let $ of p)this.shippedAttachments.add($)}catch($){let T=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${T}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],h=[];for(let[$,T]of i){let C=T.filter(b=>!m(b.id));if(C.length===0)continue;f.push({issueId:$,comments:C.map(tx)});let S=C.flatMap(b=>{let I=jr(b.body);return I?[{commentId:b.id,author:b.author,name:I.name,args:I.args,createdAt:b.createdAt}]:[]});S.length>0&&h.push({issueId:$,commands:S})}let k={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Bm),commentsBatch:f,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Bm)}:{},observedAtMs:n};this.send(k);let y=f.reduce(($,T)=>$+T.comments.length,0),g=h.reduce(($,T)=>$+T.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${y} commands=${g} (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=rx(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}}}});import{existsSync as Gm,readFileSync as ox,readdirSync as ix}from"node:fs";import{join as Hm}from"node:path";import{simpleGit as sx}from"simple-git";import{parse as ax}from"yaml";function Za(t){let e=new Map,r=Hm(t,bs);if(!Gm(r))return e;let n;try{n=ax(ox(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 cx(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return _r({modelFormatVersion:2,repos:e})}function Wm(t,e){let r=Hm(t,e);if(!Gm(r))return[];let n=[];for(let o of ix(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Wm(t,i)):n.push(i)}return n}async function Di(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 Wm(t,m))d.emittedShardPaths.has(f)||(n.push({path:f,content:"",deleted:!0}),o++)}let i=Za(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:bs,content:cx(i)});let s=$i(t),a=Zf(s,r.halfLifeDays??ze.halfLifeDays);n.push({path:Er,content:vi(a)});for(let d of e){let m=[];for(let f of s)for(let h of f.files)Q(h.key)?.repo===d.repo&&m.push({kind:"touched_by",from:ke(f.taskKey),to:h.key,...h.churn!==void 0?{weight:h.churn}:{}});n.push({path:fl(d.repo),content:Ar({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:m})})}let c=sx(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Se(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(ro(),to));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var Ym=x(()=>{"use strict";K();Ua();tt()});var oc={};Rr(oc,{bootstrapWorkspaceModel:()=>Zm,modelBootstrapCommand:()=>nc,modelBuildCommand:()=>rc,rebuildWorkspaceModelIfStale:()=>ux});import{existsSync as qm}from"node:fs";import{join as Li}from"node:path";import{cancel as lx,intro as Vm,log as tc,outro as ec}from"@clack/prompts";import{simpleGit as zm}from"simple-git";function so(t){lx(t),process.exit(1)}function Jm(t,e){let r=t.spec.repos.filter(o=>!e||o.name===e);r.length===0&&so(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let n=[];for(let o of r){let i=o.mountAs==="."?t.root:Li(t.root,o.mountAs);if(!qm(Li(i,".git"))){tc.warn(`${o.name}: no local clone at ${i} \u2014 skipped (run \`codepipe clone\` first)`);continue}n.push({name:o.name,dir:i,defaultBranch:o.defaultBranch||"main"})}return n.length===0&&so("nothing to do \u2014 no repo clones found"),n}async function Xm(t){let e=zm(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function Qm(t,e,r){let n=[];for(let o of e)try{let i=await Da({repo:o.name,repoDir:o.dir,contextDir:t.contextDir,settings:r,ref:await Xm(o)});n.push(i),tc.info(`${o.name}: ${i.counts.code} files, ${i.counts.component} components, ${i.counts.correlates} co-change edges @ ${i.headCommit.slice(0,10)}`)}catch(i){so(`${o.name}: ${i instanceof Error?i.message:String(i)}`)}return n}async function rc(t){Vm("codepipe model build");let e=$e();e||so("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");let r=Xr(e.contextDir),n=await Qm(e,Jm(e,t.repo),r),o=await Di(e.contextDir,n,{halfLifeDays:r.cochange.halfLifeDays});o.committed?ec(`model updated: ${o.filesWritten} files written, ${o.filesDeleted} stale removed`):ec("model already up to date (no changes)")}async function nc(t){Vm("codepipe model bootstrap");let e=$e();e||so("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)"),await Zm(e,t.repo,{onLog:r=>tc.info(r)}),ec("bootstrap complete")}async function Zm(t,e,r){let n=Xr(t.contextDir),o=Jm(t,e),i=await Qm(t,o,n),s=xf(t.contextDir),a=vf(n.issueKeyPattern,s),c=kr([...n.ignore,...Jr]),l=[];for(let d of i){let m=o.find(h=>h.name===d.repo),f=await Tf({repo:d.repo,repoDir:m.dir,headCommit:d.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:a,pathToCurrent:ki(d.identityTable),entityByKey:d.entityByKey,ignored:c});l.push(f),r.onLog(`${d.repo}: ${f.size} task events mined from history`)}let{files:u,skippedPipeline:p}=Rf(t.contextDir,l);return p>0&&r.onLog(`${p} events already recorded by the live pipeline \u2014 left untouched`),u.length>0&&await Se(t.contextDir,u,`model: bootstrap ${u.length} task events from history`),await Di(t.contextDir,i,{halfLifeDays:n.cochange.halfLifeDays}),{events:u.length}}async function ux(t,e={}){let r=e.onLog??(()=>{}),n=Xr(t.contextDir);if(!n.enabled)return{rebuilt:[],skipped:[]};let o=[],i=[],s=Za(t.contextDir),a=[];for(let c of t.repos){let l=c.mountAs==="."?t.root:Li(t.root,c.mountAs);if(!qm(Li(l,".git")))continue;let u=zm(l),p=c.defaultBranch||"main";e.fetch&&await u.fetch(["origin",p]).catch(()=>{});let d=await Xm({name:c.name,dir:l,defaultBranch:p}),m=(await u.revparse([d]).catch(()=>"")).trim();if(m){if(s.get(c.name)?.builtFromCommit===m){i.push(c.name);continue}try{a.push(await Da({repo:c.name,repoDir:l,contextDir:t.contextDir,settings:n,ref:m})),o.push(c.name)}catch(f){r(`[model] rebuild of ${c.name} failed: ${f instanceof Error?f.message:String(f)}`)}}}return a.length>0&&(await Di(t.contextDir,a,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${o.join(", ")} (skipped up-to-date: ${i.join(", ")||"\u2014"})`)),{rebuilt:o,skipped:i}}var Mi=x(()=>{"use strict";tt();Ym();La();Na();wi();eo();pt()});var th={};Rr(th,{computeDriftReport:()=>hx,supersededAdrIds:()=>eh});import{existsSync as ic,readFileSync as sc,readdirSync as ac}from"node:fs";import{join as tn}from"node:path";import{parse as dx}from"yaml";import{simpleGit as px}from"simple-git";function mx(t,e){let r=tn(t,`model/derived/structure/${e}`),n=[],o="";if(!ic(r))return{nodes:n,builtFromCommit:o};for(let i of ac(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Et(dx(sc(tn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=Q(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 eh(t){let e=new Set,r=tn(t,"adr");if(!ic(r))return e;for(let n of ac(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=sc(tn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function hx(t,e,r){let{nodes:n,builtFromCommit:o}=mx(e,r),i=(await px(t).revparse(["HEAD"])).trim(),s=await Zn(t,i),a=new Map(s.map(y=>[y.path,y.blobHash])),c=[],l=[],u=new Set,p=[];for(let y of n){if(y.level==="component"){p.push(y);continue}u.add(y.path);let g=a.get(y.path);g?y.contentHash&&g.slice(0,fx)!==y.contentHash&&c.push(y.key):l.push(y.key)}let d=0,m=new Map;for(let y of s){let g=y.path.lastIndexOf("/"),$=g<0?"":y.path.slice(0,g);m.has($)||m.set($,new Set),m.get($).add(y.path),u.has(y.path)||d++}let f=new Map;for(let y of u){let g=y.lastIndexOf("/"),$=g<0?"":y.slice(0,g);f.has($)||f.set($,new Set),f.get($).add(y)}for(let y of p){let g=f.get(y.path)??new Set,$=m.get(y.path)??new Set;if($.size===0){l.push(y.key);continue}(g.size!==$.size||[...g].some(C=>!$.has(C)))&&c.push(y.key)}let h=[],k=eh(e);if(k.size>0){let y=tn(e,"model/facts/annotations"),g=new Map(n.filter($=>$.entityId).map($=>[$.entityId,$.key]));if(ic(y))for(let $ of ac(y).sort()){if(!$.endsWith(".md"))continue;let T=$.replace(/\.md$/,""),C=g.get(T);if(C)try{(sc(tn(y,$),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(I=>`ADR-${I.slice(4).padStart(4,"0")}`).some(I=>k.has(I))&&h.push(C)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(h)].sort(),newFiles:d}}var fx,rh=x(()=>{"use strict";K();eo();fx=12});import{existsSync as oh,rmSync as gx}from"node:fs";import{join as wr}from"node:path";import{simpleGit as yx}from"simple-git";import"ws";function Ui(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${Ue} (protocol ${at})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&gp(o.contextDir,r);let i=nh("CLI_TRACKING_POLL_INTERVAL_SEC"),s=nh("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=new Set,m=f();function f(){let h=Jo(t.hubUrl,t.cliToken),k=null,y=new Ni(i,P=>{h.readyState===h.OPEN&&h.send(JSON.stringify(P))},r),g=new Oi(s,P=>{h.readyState===h.OPEN&&h.send(JSON.stringify(P))},r,{contextDir:o?.contextDir??null,isSelfComment:P=>d.has(P)}),$=null,T=async()=>{try{let P={trackerProvider:qa(o?.contextDir??null)};try{let D=await oe(t.hubUrl,t.cliToken,t.projectId);P={...P,repos:D.repos,contextRepo:D.contextRepo}}catch(D){r.warn(`[readiness] could not fetch project summary for push checks: ${D instanceof Error?D.message:String(D)}`)}let L=await vd(t.projectId,P);if(h.readyState!==h.OPEN)return;let j={type:"cli_readiness",projectId:t.projectId,ready:L.ready,checks:L.checks,creds:L.creds,secretNames:ju(t.projectId),checkedAt:L.checkedAt};if(h.send(JSON.stringify(j)),L.ready)r.info("[readiness] ready");else{let D=L.checks.filter(R=>!R.ok).map(R=>`${R.name}(${R.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${D.join(", ")}`)}let q=Cd(L.creds,u);if(q==="open"){u=!0;let D=Ad(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${D}`),cr(D)}else q==="rearm"&&(u=!1)}catch(P){r.warn(`[readiness] check failed: ${P instanceof Error?P.message:String(P)}`)}},C=()=>{T(),$=setInterval(()=>void T(),a),typeof $.unref=="function"&&$.unref()},S=()=>{$&&(clearInterval($),$=null)},b=150,I=new Map,M=P=>{let L=I.get(P);if(!L||(L.timer&&clearTimeout(L.timer),I.delete(P),L.events.length===0||h.readyState!==h.OPEN))return;let j={type:"run_activity",projectId:t.projectId,runId:P,events:L.events};h.send(JSON.stringify(j))},G=(P,L)=>{let j=I.get(P);if(j||(j={events:[],timer:null},I.set(P,j)),j.events.push(L),L.kind==="result"){M(P);return}j.timer||(j.timer=setTimeout(()=>M(P),b),j.timer.unref?.())},E=o?.contextDir?new ii(o.contextDir,t.projectId,P=>{h.readyState===h.OPEN&&h.send(JSON.stringify(P))},r):null,w=async()=>{let P=o?.contextDir;if(!P)throw new Error("no context repo clone on this CLI");let L;try{L=(await oe(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let j=await Up(P,t.projectId,L,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(j)),j},N=null,_=async()=>{let P=o?.contextDir;if(P)try{let{readContextIndexHub:L,collectSearchRows:j}=await Promise.resolve().then(()=>(ro(),to));if(L(P)!=="metadata")return;let q=j(P);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:q})),r.info(`[model] tier-2 index snapshot pushed (${q.length} rows)`))}catch(L){r.warn(`[model] tier-2 index push failed (non-fatal): ${L instanceof Error?L.message:String(L)}`)}},B=()=>{N&&clearTimeout(N),N=setTimeout(()=>void _(),5e3)},V=null,ee=async P=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:L}=await Promise.resolve().then(()=>(Mi(),oc));(await L({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:P,onLog:q=>r.info(q)})).rebuilt.length>0&&B()}catch(L){r.warn(`[model] release-path rebuild failed (non-fatal): ${L instanceof Error?L.message:String(L)}`)}},Le=P=>{V&&clearTimeout(V),V=setTimeout(()=>void ee(P),6e4)},Me=setInterval(()=>void ee(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let P=Fu(t.projectId),L=Y("ORIGIN")==="farm"?"farm":"local",j=Y("FARM_ID"),q=t.accountEmail??P.email,D;try{let v=Xp(t.projectId);v&&(D=v.publicKey,r.info(`[cred-channel] key fingerprint: ${v.fingerprint}`))}catch(v){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${v instanceof Error?v.message:String(v)}`)}let R={type:"register",projectId:t.projectId,platformVersion:Ue,protocolVersion:at,accountId:P.accountId,accountLabel:P.label,origin:L,inFlightActionIds:[...p],...q?{accountEmail:q}:{},...L==="farm"&&j?{farmId:j}:{},...D?{sealPublicKey:D}:{}};h.send(JSON.stringify(R))}),h.on("message",async P=>{let L=P.toString("utf-8");if(L==="pong"||L==="ping")return;let j;try{j=JSON.parse(L)}catch{return}if(!j||typeof j!="object")return;let q=j.type;if(q==="registered"){let R=j;if(R.ok){if(r.info(`[ws] registered for project ${R.projectId}`),n({kind:"registered",projectId:R.projectId??t.projectId}),y.start(),E?.start(),C(),lc(t,o,r),o?.contextDir){try{let v=ui(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify(v)),v.outdated&&(r.warn(`[ctx] context format outdated: v${v.templateVersion} \u2192 v${v.currentVersion}`+(v.missingPaths.length>0?` (missing: ${v.missingPaths.join(", ")})`:"")),l||(l=!0,w().catch(()=>{})))}catch(v){r.warn(`[ctx] context-format detect failed (non-fatal): ${v instanceof Error?v.message:String(v)}`)}_(),Le(!0)}}else r.warn(`[ws] register rejected: ${R.reason??"unknown"}`),n({kind:"register_rejected",reason:R.reason??"unknown"}),c=!0,h.close();return}if(q==="hello"){let R=j;k=To(R.protocolVersion);let v=k?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${R.platformVersion} (protocol ${R.protocolVersion}) \u2014 ${v}`),k||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ue}, protocol ${at}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${cc}`),n({kind:"incompatible",hubVersion:typeof R.platformVersion=="string"?R.platformVersion:null,hubProtocol:typeof R.protocolVersion=="number"?R.protocolVersion:null,updateCommand:cc}));return}if(q==="tracking_targets"){y.setTargets(j.targets);return}if(q==="youtrack_sync_request"){g.setRequest(j);return}if(q==="youtrack_force_sync"){g.forceSync();return}if(q==="sync_local"){await bx(j,o,h,r);return}if(q==="provision_repo"){let R=j;r.info(`[repo] provision_repo: ${R.repo.name} (${R.repo.host}:${R.repo.owner}/${R.repo.repoName})`),await kx(t,o,R.repo,r),await lc(t,o,r);return}if(q==="remove_repo"){let R=j;r.info(`[repo] remove_repo: ${R.repoName}${R.purge?" (purge)":""}`),await lc(t,o,r),R.purge&&wx(t,o,R.repoName,r);return}if(q==="context_write"){await $x(j,o,h,r);return}if(q==="adr_promote"){await vx(j,o,h,r);return}if(q==="cred_update"){let R=j,v=W(t.projectId),O=v?.sealKey?await Qp(t.projectId,R.kind,R.sealed,v.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},X={type:"cred_update_result",updateId:R.updateId,projectId:t.projectId,ok:O.ok,...O.detail?{detail:O.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(X)),O.ok?(r.info(`[cred] ${R.kind} replaced${O.detail?` \u2014 ${O.detail}`:""}`),T()):r.warn(`[cred] ${R.kind} replacement rejected: ${O.detail??"unknown"}`);return}if(q==="readiness_check"){r.info("[readiness] on-demand check requested"),T();return}if(q==="agent_login_start"){Id(t,h,j,r,T);return}if(q==="move_to_farm"){let R=j;r.info(`[farm-move] request to move ${t.projectId} onto farm ${R.farmName} (${R.farmId})`);let v=await xm(t,R,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify(v)),v.ok?r.info(`[farm-move] done \u2014 farm daemon ${v.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${v.error??"unknown error"}`);return}if(q==="gh_runner_setup"){let R=j;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${R.runnerName} (${R.runnerId})`);let v=await _m(t,R,r);h.readyState===h.OPEN&&h.send(JSON.stringify(v)),v.ok?r.info(`[ghr] runners connected on ${R.runnerName}`):r.warn(`[ghr] setup failed: ${v.error??"see per-repo statuses"}`);return}if(q==="gh_runner_teardown"){let R=j;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${R.runnerName} (${R.runnerId})`);let v=await jm(t,R,r);h.readyState===h.OPEN&&h.send(JSON.stringify(v)),v.ok?r.info(`[ghr] runners disconnected from ${R.runnerName}`):r.warn(`[ghr] teardown failed: ${v.error??"unknown error"}`);return}if(q==="tracker_fields_request"){let R=j,v={type:"tracker_fields_result",requestId:R.requestId,projectId:t.projectId,ok:!1},O=gt({contextDir:o?.contextDir??null});if(!O.ok)v.error=O.error;else try{v.fields=await O.provider.fetchStateFields(R.projectKey),v.ok=!0}catch(X){v.error=X instanceof Error?X.message:String(X)}h.readyState===h.OPEN&&h.send(JSON.stringify(v)),v.ok||r.warn(`[yt-fields] listing failed: ${v.error??"unknown"}`);return}if(q==="project_secret_update"||q==="project_secret_delete"){let R=j,v;if(R.type==="project_secret_update"){let X=W(t.projectId);v=X?.sealKey?Dm(t.projectId,R.name,R.sealed,X.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else v=Lm(t.projectId,R.name);let O={type:"project_secret_update_result",updateId:R.updateId,projectId:t.projectId,ok:v.ok,...v.detail?{detail:v.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(O)),v.ok?(r.info(`[secret] ${R.name} ${R.type==="project_secret_update"?"saved":"deleted"}`+(v.detail?` \u2014 ${v.detail}`:"")),T()):r.warn(`[secret] ${R.name} rejected: ${v.detail??"unknown"}`);return}if(q==="auto_apply_local"){let R=j;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${R.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let v=await ip({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},R.claim,r).catch(O=>({ok:!1,message:O instanceof Error?O.message:String(O)}));v.ok?r.info(`[apply] ${R.claim.taskKey}: ${v.message}`):r.warn(`[apply] ${R.claim.taskKey}: ${v.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:R.claim.taskKey,ok:v.ok,...v.ok?{branches:v.branches??[]}:{error:v.message}});return}if(q==="sandbox_keys"){let R=W(t.projectId);if(!R){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let v=Lr(t.projectId),O=Yp(j,R,v,r);for(let X of O)h.readyState===h.OPEN&&h.send(JSON.stringify(X));return}if(q!=="dispatch_action")return;let D=j;if(k===!1){let R=`refused: HUB protocol incompatible with CLI v${Ue} (protocol ${at})`;h.send(JSON.stringify({type:"action_result",actionId:D.actionId,status:"failed",error:R})),r.warn(`[exec] ${D.actionId} (${D.action.type}) \u2192 REFUSED: ${R}`),r.warn(`[exec] update the CLI to clear this: ${cc}`),n({kind:"action",actionId:D.actionId,actionType:D.action.type,ok:!1,error:R});return}if(D.action.type==="model_drift"){p.add(D.actionId);try{let R,v=o?.repos.find(O=>O.name===D.action.repoName);if(!o?.contextDir||!v)R={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:O}=await Promise.resolve().then(()=>(rh(),th)),X=v.mountAs==="."?o.root:wr(o.root,v.mountAs);R={status:"done",result:{report:await O(X,o.contextDir,v.name)}}}catch(O){R={status:"failed",error:O instanceof Error?O.message:String(O)}}h.send(JSON.stringify({type:"action_result",actionId:D.actionId,...R}))}finally{p.delete(D.actionId)}return}if(D.action.type==="local_apply"){p.add(D.actionId);try{let R;if(!o)R={status:"failed",error:"no local workspace on this CLI"};else{let O=await ym(o,D.action.repos,r);if(R=O.ok?{status:"done",result:{repos:O.repos}}:{status:"failed",error:O.error},O.ok&&o.contextDir){let X=D.action.taskId.split(":")[1]??"";for(let ve of X?O.repos:[]){let Ye=o.repos.find(Z=>Z.name===ve.repoName);if(!Ye)continue;let{recordPipelineEvent:J}=await Promise.resolve().then(()=>(Ha(),am));await J({contextDir:o.contextDir,repoDir:wr(o.root,Ye.mountAs),repoName:ve.repoName,taskKey:X,commitSha:ve.commit}).catch(Z=>r.warn(`[model] task event for ${X} failed: ${Z instanceof Error?Z.message:String(Z)}`))}B()}}h.send(JSON.stringify({type:"action_result",actionId:D.actionId,...R}));let v=R.status!=="failed";v?r.info(`[exec] ${D.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${D.actionId} (local_apply) \u2192 FAILED: ${R.status==="failed"?R.error:"?"}`),n({kind:"action",actionId:D.actionId,actionType:"local_apply",ok:v,...R.status==="failed"?{error:R.error}:{}})}finally{p.delete(D.actionId)}return}p.add(D.actionId);try{let R=await mm({action:D.action,repo:D.repo,trackerIssueId:D.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:E?()=>E.reportNow():void 0,refreshContextStatus:o?.contextDir?w:void 0,onRunActivity:G}).catch(X=>({status:"failed",error:X instanceof Error?X.message:String(X)}));D.action.type==="tracker_comment"&&R.status==="done"&&"result"in R&&typeof R.result?.commentId=="string"&&d.add(R.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:D.actionId,...R}));let v=R.status!=="failed",O=!v&&"error"in R?R.error:void 0;v?r.info(`[exec] ${D.actionId} (${D.action.type}) \u2192 done`):r.warn(`[exec] ${D.actionId} (${D.action.type}) \u2192 FAILED: ${O??"?"}`),n({kind:"action",actionId:D.actionId,actionType:D.action.type,ok:v,...O?{error:O}:{}}),v&&["apply_delivery","context_write","create_pr"].includes(D.action.type)&&B(),v&&["merge_pr","merge_branch"].includes(D.action.type)&&Le(!0)}finally{p.delete(D.actionId)}}),h.on("close",(P,L)=>{let j=L?.toString("utf-8")??"";if(r.info(`[ws] closed code=${P}${j?` reason=${j}`:""}`),y.stop(),g.stop(),E?.stop(),S(),clearInterval(Me),V&&clearTimeout(V),N&&clearTimeout(N),j==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:P}),!c&&setTimeout(()=>{m=f()},2e3)}),h.on("error",P=>r.warn(`[ws] error: ${P.message}`)),h}return{stop(){c=!0,m.close()}}}async function lc(t,e,r){try{let n=await oe(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=zn(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 kx(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?wr(e.root,o):Re(t.projectId,r.name);if(oh(wr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await yx().clone(Gn(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 wx(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?wr(e.root,o):Re(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!oh(wr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{gx(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 bx(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=wr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await ap(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 $x(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await Se(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function vx(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 xp(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 nh(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var cc,uc=x(()=>{"use strict";Ae();K();Ku();Ed();Pd();zo();oa();cp();mp();Sp();tt();vt();ga();Bp();$a();Kr();qp();Zp();hm();km();Sm();Nm();xe();Mm();Fr();ue();Um();Km();Ai();cc="npm i -g @code-partner/codepipe@latest"});import{execFileSync as xx}from"node:child_process";import{mkdtempSync as Sx,mkdirSync as Tx,readFileSync as ih,rmSync as Rx,writeFileSync as Ix}from"node:fs";import{tmpdir as Ex}from"node:os";import{dirname as Cx,join as sh}from"node:path";function ah(t="codepipe-context"){let e=Sx(sh(Ex(),"codepipe-ssh-")),r=sh(e,"id_ed25519");try{return xx("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:ih(r,"utf-8"),publicKey:ih(`${r}.pub`,"utf-8").trim()}}finally{Rx(e,{recursive:!0,force:!0})}}async function ch(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 lh(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 uh(t,e){Tx(Cx(t),{recursive:!0});let r=e.endsWith(`
645
+ `;return await Ee(this.contextDir,[{path:`tasks/${e}/comments.jsonl`,content:c}],`tracker(${e}): comment`),{id:i.id}}async createIssue(e){let r=new Date().toISOString(),n=await Fp(this.contextDir,this.config.prefix,o=>this.renderNewIssueFiles(o,e,r),o=>`tracker(${o}): create issue`);return{id:n,key:n}}async editIssue(e,r){await this.mutateRecord(e,n=>({...n,...r.title!==void 0?{title:r.title}:{}}),r.body)}async applyLink(e,r,n){let o=r==="subtask_of"?"subtask":"depends_on";await this.mutateRecord(e,i=>{let s=i.links.filter(a=>!(a.type===o&&a.targetKey===n));return s.push({type:o,targetKey:n}),{...i,links:s}})}async fetchStateFields(e){return[{name:"Status",values:Ds.statusColumns}]}async mutateRecord(e,r,n){let o=zn(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Jn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Ln(e),content:Sa(i)},...Ai(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Ee(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Oo,status:r.targetStatus,links:[],created:n,updated:n},i=Jn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Ln(e),content:Sa(o)},...Ai(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}}});import{existsSync as km,readFileSync as wm}from"node:fs";import{join as bm}from"node:path";import{parseDocument as $m}from"yaml";function Qa(t){if(!t)return"youtrack";try{let e=bm(t,"project.yaml");return km(e)&&$m(wm(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function kt(t){let e=Qa(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=Mp(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=Lv(n);return i?{ok:!0,kind:e,provider:new so(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=dd();return r?{ok:!0,kind:e,provider:new io(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function Lv(t){try{let e=bm(t,"project.yaml");if(!km(e))return null;let r=$m(wm(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var ji=v(()=>{"use strict";cr();Ja();Xa();mi();Ja();Xa()});async function tn(t,e){let n=(Ni.get(t)??Promise.resolve()).catch(()=>{}).then(e);Ni.set(t,n);try{return await n}finally{Ni.get(t)===n&&Ni.delete(t)}}async function vm(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;ur(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await pr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{commit:c,pushed:l}=await tp(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let u=e.taskId.split(":")[1]??"";u&&await Ya({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:u,commitSha:c}).catch(p=>{ur(`[model] task event for ${u} failed: ${p instanceof Error?p.message:String(p)}`)})}return ce({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await pr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir);return await rp(s,a,{branchName:e.branchName,force:e.force}),ce({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await pr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{commit:c,pushed:l}=await np(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ce({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return J("no repo spec");let i=Qe(r),s=await i.createPullRequest(r,e);if(t.contextDir){let a=e.taskId.split(":")[1]??"",c=e.taskId.split(":",2)[0]??"?";a&&await Va({contextDir:t.contextDir,repoDir:Ie(c,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:a,prUrl:s.url}).catch(l=>{ur(`[model] pr link for ${a} failed: ${l instanceof Error?l.message:String(l)}`)})}return ce({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return J("no repo spec");let i=Qe(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ce({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return J("no repo spec");let i=Qe(r);return await i.closePR(r,e.prNumber,e.comment),ce({prNumber:e.prNumber,host:i.name})}case"rewrite_cluster_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await pr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{commit:c,dropped:l}=await ip(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ce({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return J("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return tn(`${i}/${r.name}`,async()=>{let s=await pr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ie(i,r.name,t.baseDir),{mergedSha:c}=await sp(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ce({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return J("no repo spec");let i=t.cloneUrlOverride??Wn(r),a=(await ap(i)).filter(u=>cp(u,e.issueKey)),c=Qe(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 ce({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return J("no repo spec");let i=Qe(r);return await i.addPRComment(r,e.prNumber,e.body),ce({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=kt({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ce({issueId:t.trackerIssueId,newStatus:e.newStatus})):J("no tracker_issue_id provided"):J(i.error)}case"tracker_comment":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!t.trackerIssueId)return J("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ce({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!e.projectKey)return J("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 ce({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(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 J(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ce({applied:s})}case"set_project_setting":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await yf(t.contextDir,e.edits);return ce({files:i.files})}case"tracker_edit":{let i=kt({contextDir:t.contextDir});if(!i.ok)return J(i.error);if(!t.contextDir)return J("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 Pi(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ce({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await vf(t.contextDir,e);return ce({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=await bf(t.contextDir,e);return ce({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ce({reported:!0})):J("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return J("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ce({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return J("no project workspace on this CLI");if(!r)return J("no repo spec");if(!t.onRunActivity)return J("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=ai(t.contextDir),c=s.find(f=>f.id===e.actionId);if(!c){let f=a.find(m=>m.file===`actions/${e.actionId}.yml`);return J(f?`action "${e.actionId}" failed to parse: ${f.error}`:`unknown action "${e.actionId}"`)}let l=Kl(c,e.input);if(!l.ok)return J(l.error);let u=wp(t.contextDir),p=Y(e.projectId),d={};return p?.github?.token&&(d.GH_TOKEN=p.github.token),p?.gitlab?.token&&(d.GITLAB_TOKEN=p.gitlab.token),p?.bitbucket&&(d.BITBUCKET_EMAIL=p.bitbucket.email,d.BITBUCKET_API_TOKEN=p.bitbucket.apiToken),p?.youtrack&&(d.YOUTRACK_URL=p.youtrack.url,d.YOUTRACK_TOKEN=p.youtrack.token),tn(`${e.projectId}/${r.name}`,async()=>{await pr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let f=Ie(e.projectId,r.name,t.baseDir),m=await df({cwd:f,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return ce({runId:e.runId,status:m.status,exitCode:m.exitCode,...m.failedStep?{failedStep:m.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return J("no context repo clone on this CLI");let i=gf(t.contextDir,e.path);return ce({path:e.path,...i})}case"search_model":{if(!t.contextDir)return J("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(oo(),no)),s=await i(t.contextDir,e.q,e.limit);return ce({hits:s})}case"model_drift":return J("model_drift requires a local workspace (handled by the daemon)");case"local_apply":return J("local_apply requires a local workspace (handled by the daemon)");default:return J(`unsupported action type: ${e.type}`)}}catch(i){return J(i instanceof Error?i.message:String(i))}}function ce(t){return{status:"done",result:t}}function J(t){return{status:"failed",error:t}}var Ni,xm=v(()=>{"use strict";G();da();pf();hf();de();kf();$f();_a();Ot();ri();Kr();za();ji();_i();Ni=new Map});import{existsSync as Mv,mkdtempSync as Uv,rmSync as Bv}from"node:fs";import{tmpdir as Fv}from"node:os";import{join as Za}from"node:path";import{simpleGit as Sm}from"simple-git";async function Tm(t,e,r){let n=[];for(let a of e){let c=t.repos.find(u=>u.name===a.repoName);if(!c)return{ok:!1,error:`repo "${a.repoName}" not in project.yaml \u2014 run /sync`};let l=Za(t.root,c.mountAs);if(!Mv(Za(l,".git")))return{ok:!1,error:`${c.mountAs}/ not cloned \u2014 run /sync first`};n.push({payload:a,dir:l,mountAs:c.mountAs,defaultBranch:c.defaultBranch})}let o=[];for(let a of n){let c=Sm(a.dir),l=a.payload;try{await c.fetch()}catch(f){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${ao(f)}`}}let u=`origin/${l.baseRef}`;await Wv(c,u)||(u=`origin/${a.defaultBranch}`);let p;try{p=(await c.revparse([u])).trim()}catch(f){return{ok:!1,error:`base ${u} unavailable in ${a.mountAs}: ${ao(f)}`}}let d;try{d=await Hn(c,l.deliverySha,()=>fr(c,{contextRepoCloneUrl:l.contextRepoCloneUrl,deliveryRef:l.deliveryRef,deliverySha:l.deliverySha,baseSha:l.baseSha,commitMessage:l.commitMessage}))}catch(f){return{ok:!1,error:`fetch delivery failed in ${a.mountAs}: ${ao(f)}`}}o.push({repoName:l.repoName,mountAs:a.mountAs,git:c,branch:l.branchName,startPoint:p,deliveryCommit:d})}let i=[],s=[];for(let a of o){let c=await qv(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await Kv(a);await a.git.raw(["branch","-f",a.branch,u]),i.push({git:a.git,mountAs:a.mountAs,branch:a.branch,priorSha:c}),s.push({repoName:a.repoName,branch:a.branch,commit:u}),r.info(`[local-apply] ${a.mountAs}: branch ${a.branch} \u2192 ${u.slice(0,10)} (no checkout)`)}catch(l){return await Hv(i,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${ao(l)} (rolled back all repos)`}}}return{ok:!0,repos:s}}async function Kv(t){let e=Uv(Za(Fv(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=Sm(e);try{await r.raw([...Gv,"cherry-pick",t.deliveryCommit])}catch(n){throw await r.raw(["cherry-pick","--abort"]).catch(()=>{}),n}return(await r.revparse(["HEAD"])).trim()}finally{await t.git.raw(["worktree","remove","--force",e]).catch(()=>{}),Bv(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function Hv(t,e){for(let r of t)try{r.priorSha?await r.git.raw(["branch","-f",r.branch,r.priorSha]):await r.git.raw(["branch","-D",r.branch])}catch(n){e.warn(`[local-apply] rollback of ${r.mountAs}#${r.branch} failed: ${ao(n)} \u2014 check manually`)}}async function Wv(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function qv(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function ao(t){return t instanceof Error?t.message.trim():String(t)}var Gv,Em=v(()=>{"use strict";Kr();Gv=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as Yv}from"node:os";import{existsSync as Vv,mkdirSync as zv,readFileSync as Jv,writeFileSync as Xv}from"node:fs";import{dirname as Qv,join as Zv}from"node:path";function ec(){return z("FARM_PINS")??Zv(Yv(),".codepipe","farm-pins.json")}function Rm(){let t=ec();if(!Vv(t))return{};try{return JSON.parse(Jv(t,"utf-8"))}catch{return{}}}function ex(t){let e=ec();zv(Qv(e),{recursive:!0}),Xv(e,JSON.stringify(t,null,2)+`
646
+ `,{mode:384})}function tx(t){return Rm()[t]}function Oi(t,e){let r=Rm();r[t]=e,ex(r)}function Di(t,e){let r=je(e),n=tx(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 ${ec()}.`);return r}var tc=v(()=>{"use strict";_e();He()});import{existsSync as Im,readFileSync as Cm}from"node:fs";import{join as Am}from"node:path";async function Pm(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=je(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Di(e.farmId,e.farmPublicKey);let s=Y(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await ne(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Am(r,"project.yaml"),f=Am(r,"regimen.yaml");Im(d)&&Im(f)?c={projectYaml:Cm(d,"utf-8"),regimenYaml:Cm(f,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=St(e.farmPublicKey,JSON.stringify(l));Oi(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await ei(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return p.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...p.daemonStatus?{daemonStatus:p.daemonStatus}:{}}:o(p.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}var _m=v(()=>{"use strict";He();tc();Te();de()});import{homedir as rx}from"node:os";import{existsSync as nx,mkdirSync as ox,readFileSync as ix,writeFileSync as sx}from"node:fs";import{dirname as ax,join as cx}from"node:path";function rc(){return z("RUNNER_PINS")??cx(rx(),".codepipe","runner-pins.json")}function jm(){let t=rc();if(!nx(t))return{};try{return JSON.parse(ix(t,"utf-8"))}catch{return{}}}function lx(t){let e=rc();ox(ax(e),{recursive:!0}),sx(e,JSON.stringify(t,null,2)+`
647
+ `,{mode:384})}function ux(t){return jm()[t]}function nc(t,e){let r=jm();r[t]=e,lx(r)}function Nm(t,e){let r=je(e),n=ux(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 ${rc()}.`);return r}var Om=v(()=>{"use strict";_e();He()});async function Dm(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Lm(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}async function Um(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(je(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Nm(e.runnerId,e.runnerPublicKey);let i=Y(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).find(c=>c.host==="github"&&c.owner===e.owner&&c.repoName===e.repo);if(!a)throw new Error(`${e.owner}/${e.repo} is not a GitHub repository of this project`);return{githubToken:i,repo:a}}async function Bm(t,e,r,n=Mm){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 Um(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:[eu(e.runnerId)]},c=St(e.runnerPublicKey,JSON.stringify(a));nc(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 Fm(t,e,r,n=Mm){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 Um(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=St(e.runnerPublicKey,JSON.stringify(c));nc(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle for ${s.owner}/${s.repoName} sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l,owner:s.owner,repo:s.repoName});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var Lm,dx,Mm,Gm=v(()=>{"use strict";G();He();Om();Te();de();Lm=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});dx={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Lm(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)=>Dm(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Dm(t,e,r,"remove-token")},Mm={api:dx,fetchProject:ne,provisionOnRunner:Bd,teardownOnRunner:Fd}});function px(t){return Be.test(t)?At(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Be}`}function Hm(t,e,r,n){let o=px(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(zr(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>Km)return{ok:!1,detail:`secret value too large (max ${Km} chars)`};try{return Mu(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Wm(t,e){try{return Uu(t,e)?{ok:!0}:{ok:!0,detail:"no such secret (already absent)"}}catch(r){return{ok:!1,detail:r instanceof Error?r.message:String(r)}}}var Km,qm=v(()=>{"use strict";G();He();de();Km=16*1024});function fx(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Li,Ym=v(()=>{"use strict";Ot();Li=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=Qe(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof ar){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Qe(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=fx(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}}});function Vm(t){let{description:e,...r}=t;return r}function mx(t){let{body:e,...r}=t;return r}function gx(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 hx(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 zm(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Mi,Jm=v(()=>{"use strict";G();_i();ji();Mi=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??(()=>kt({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 $=e.stageField?{stageField:e.stageField}:{},x=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},S=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(S){let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[E,O]=await Promise.all([b.length>0?r.listIssues({projectKey:e.projectKey,columns:b,...$,...x}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...$})]),B=new Map;for(let A of[...E,...O])B.set(A.id,A);o=[...B.values()]}else{let b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:b,...$,...x})}}catch($){this.log.warn(`[yt-sync] listIssues failed: ${$ instanceof Error?$.message:String($)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let $ of o){if(s.add($.id),a.has($.status))continue;let x=await zm(r,$.id,e.sinceMs,this.log);x&&i.set($.id,x)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let x=await zm(r,$,e.sinceMs,this.log);if(x&&x.length>0&&i.set($,x),e.requireAssignee||x&&x.length>0){let R=await hx(r,$,e.stageField,this.log);if(R)c.push(R);else if(x&&x.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter($=>!a.has($.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($=>({issue:$,comments:i.get($.id)??[],attachments:u.get($.id)??[]}));try{await Pi(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let $ of p)this.shippedAttachments.add($)}catch($){let x=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${x}`);return}let f=this.options.isSelfComment??(()=>!1),m=[],g=[];for(let[$,x]of i){let R=x.filter(b=>!f(b.id));if(R.length===0)continue;m.push({issueId:$,comments:R.map(mx)});let S=R.flatMap(b=>{let E=Nr(b.body);return E?[{commentId:b.id,author:b.author,name:E.name,args:E.args,createdAt:b.createdAt}]:[]});S.length>0&&g.push({issueId:$,commands:S})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Vm),commentsBatch:m,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Vm)}:{},observedAtMs:n};this.send(y);let w=m.reduce(($,x)=>$+x.comments.length,0),h=g.reduce(($,x)=>$+x.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${h} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(m){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${m instanceof Error?m.message:String(m)}`);continue}let f=gx(u.name);l.has(f)&&(f=`${u.id}-${f}`),l.add(f),c.push({name:f,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}}});import{existsSync as Xm,readFileSync as yx,readdirSync as kx}from"node:fs";import{join as Qm}from"node:path";import{simpleGit as wx}from"simple-git";import{parse as bx}from"yaml";function oc(t){let e=new Map,r=Qm(t,Ss);if(!Xm(r))return e;let n;try{n=bx(yx(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 $x(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return jr({modelFormatVersion:2,repos:e})}function Zm(t,e){let r=Qm(t,e);if(!Xm(r))return[];let n=[];for(let o of kx(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Zm(t,i)):n.push(i)}return n}async function Ui(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let f=`model/derived/structure/${d.repo}`;for(let m of Zm(t,f))d.emittedShardPaths.has(m)||(n.push({path:m,content:"",deleted:!0}),o++)}let i=oc(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:Ss,content:$x(i)});let s=Si(t),a=am(s,r.halfLifeDays??ze.halfLifeDays);n.push({path:Cr,content:Ti(a)});for(let d of e){let f=[];for(let m of s)for(let g of m.files)Q(g.key)?.repo===d.repo&&f.push({kind:"touched_by",from:be(m.taskKey),to:g.key,...g.churn!==void 0?{weight:g.churn}:{}});n.push({path:wl(d.repo),content:Pr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:f})})}let c=wx(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Ee(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(oo(),no));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var eg=v(()=>{"use strict";G();Ha();tt()});var lc={};Rr(lc,{bootstrapWorkspaceModel:()=>ag,modelBootstrapCommand:()=>cc,modelBuildCommand:()=>ac,rebuildWorkspaceModelIfStale:()=>xx});import{existsSync as tg}from"node:fs";import{join as Bi}from"node:path";import{cancel as vx,intro as rg,log as sc,outro as ic}from"@clack/prompts";import{simpleGit as ng}from"simple-git";function co(t){vx(t),process.exit(1)}function og(t,e){let r=t.spec.repos.filter(o=>!e||o.name===e);r.length===0&&co(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let n=[];for(let o of r){let i=o.mountAs==="."?t.root:Bi(t.root,o.mountAs);if(!tg(Bi(i,".git"))){sc.warn(`${o.name}: no local clone at ${i} \u2014 skipped (run \`codepipe clone\` first)`);continue}n.push({name:o.name,dir:i,defaultBranch:o.defaultBranch||"main"})}return n.length===0&&co("nothing to do \u2014 no repo clones found"),n}async function ig(t){let e=ng(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function sg(t,e,r){let n=[];for(let o of e)try{let i=await Fa({repo:o.name,repoDir:o.dir,contextDir:t.contextDir,settings:r,ref:await ig(o)});n.push(i),sc.info(`${o.name}: ${i.counts.code} files, ${i.counts.component} components, ${i.counts.correlates} co-change edges @ ${i.headCommit.slice(0,10)}`)}catch(i){co(`${o.name}: ${i instanceof Error?i.message:String(i)}`)}return n}async function ac(t){rg("codepipe model build");let e=xe();e||co("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");let r=Qr(e.contextDir),n=await sg(e,og(e,t.repo),r),o=await Ui(e.contextDir,n,{halfLifeDays:r.cochange.halfLifeDays});o.committed?ic(`model updated: ${o.filesWritten} files written, ${o.filesDeleted} stale removed`):ic("model already up to date (no changes)")}async function cc(t){rg("codepipe model bootstrap");let e=xe();e||co("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)"),await ag(e,t.repo,{onLog:r=>sc.info(r)}),ic("bootstrap complete")}async function ag(t,e,r){let n=Qr(t.contextDir),o=og(t,e),i=await sg(t,o,n),s=Pf(t.contextDir),a=Af(n.issueKeyPattern,s),c=wr([...n.ignore,...Xr]),l=[];for(let d of i){let f=o.find(g=>g.name===d.repo),m=await jf({repo:d.repo,repoDir:f.dir,headCommit:d.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:a,pathToCurrent:$i(d.identityTable),entityByKey:d.entityByKey,ignored:c});l.push(m),r.onLog(`${d.repo}: ${m.size} task events mined from history`)}let{files:u,skippedPipeline:p}=Nf(t.contextDir,l);return p>0&&r.onLog(`${p} events already recorded by the live pipeline \u2014 left untouched`),u.length>0&&await Ee(t.contextDir,u,`model: bootstrap ${u.length} task events from history`),await Ui(t.contextDir,i,{halfLifeDays:n.cochange.halfLifeDays}),{events:u.length}}async function xx(t,e={}){let r=e.onLog??(()=>{}),n=Qr(t.contextDir);if(!n.enabled)return{rebuilt:[],skipped:[]};let o=[],i=[],s=oc(t.contextDir),a=[];for(let c of t.repos){let l=c.mountAs==="."?t.root:Bi(t.root,c.mountAs);if(!tg(Bi(l,".git")))continue;let u=ng(l),p=c.defaultBranch||"main";e.fetch&&await u.fetch(["origin",p]).catch(()=>{});let d=await ig({name:c.name,dir:l,defaultBranch:p}),f=(await u.revparse([d]).catch(()=>"")).trim();if(f){if(s.get(c.name)?.builtFromCommit===f){i.push(c.name);continue}try{a.push(await Fa({repo:c.name,repoDir:l,contextDir:t.contextDir,settings:n,ref:f})),o.push(c.name)}catch(m){r(`[model] rebuild of ${c.name} failed: ${m instanceof Error?m.message:String(m)}`)}}}return a.length>0&&(await Ui(t.contextDir,a,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${o.join(", ")} (skipped up-to-date: ${i.join(", ")||"\u2014"})`)),{rebuilt:o,skipped:i}}var Fi=v(()=>{"use strict";tt();eg();Ga();Ua();vi();ro();mt()});var lg={};Rr(lg,{computeDriftReport:()=>Ix,supersededAdrIds:()=>cg});import{existsSync as uc,readFileSync as dc,readdirSync as pc}from"node:fs";import{join as rn}from"node:path";import{parse as Sx}from"yaml";import{simpleGit as Tx}from"simple-git";function Rx(t,e){let r=rn(t,`model/derived/structure/${e}`),n=[],o="";if(!uc(r))return{nodes:n,builtFromCommit:o};for(let i of pc(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=It(Sx(dc(rn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=Q(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 cg(t){let e=new Set,r=rn(t,"adr");if(!uc(r))return e;for(let n of pc(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=dc(rn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function Ix(t,e,r){let{nodes:n,builtFromCommit:o}=Rx(e,r),i=(await Tx(t).revparse(["HEAD"])).trim(),s=await to(t,i),a=new Map(s.map(h=>[h.path,h.blobHash])),c=[],l=[],u=new Set,p=[];for(let h of n){if(h.level==="component"){p.push(h);continue}u.add(h.path);let $=a.get(h.path);$?h.contentHash&&$.slice(0,Ex)!==h.contentHash&&c.push(h.key):l.push(h.key)}let d=0,f=new Map,m=new Set;for(let h of s){let $=h.path.lastIndexOf("/"),x=$<0?"":h.path.slice(0,$);f.has(x)||f.set(x,new Set),f.get(x).add(h.path),u.has(h.path)||d++;let R=x;for(;R!==""&&!m.has(R);)m.add(R),R=R.includes("/")?R.slice(0,R.lastIndexOf("/")):""}let g=new Map;for(let h of u){let $=h.lastIndexOf("/"),x=$<0?"":h.slice(0,$);g.has(x)||g.set(x,new Set),g.get(x).add(h)}for(let h of p){if(!m.has(h.path)){l.push(h.key);continue}let $=g.get(h.path)??new Set,x=f.get(h.path)??new Set;($.size!==x.size||[...$].some(S=>!x.has(S)))&&c.push(h.key)}let y=[],w=cg(e);if(w.size>0){let h=rn(e,"model/facts/annotations"),$=new Map(n.filter(x=>x.entityId).map(x=>[x.entityId,x.key]));if(uc(h))for(let x of pc(h).sort()){if(!x.endsWith(".md"))continue;let R=x.replace(/\.md$/,""),S=$.get(R);if(S)try{(dc(rn(h,x),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(O=>`ADR-${O.slice(4).padStart(4,"0")}`).some(O=>w.has(O))&&y.push(S)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(y)].sort(),newFiles:d}}var Ex,ug=v(()=>{"use strict";G();ro();Ex=12});import{existsSync as pg,rmSync as Cx}from"node:fs";import{join as br}from"node:path";import{simpleGit as Ax}from"simple-git";import"ws";function Gi(t,e={}){let r=e.log??{info:g=>console.log(g),warn:g=>console.warn(g)};r.info(`codepipe-cli v${Ue} (protocol ${lt})`);let n=g=>e.onEvent?.(g),o=e.workspace;o?.contextDir&&xp(o.contextDir,r);let i=dg("CLI_TRACKING_POLL_INTERVAL_SEC"),s=dg("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let g=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(g)&&g>0?g*1e3:6e5})(),c=!1,l=!1,u=!1,p=new Set,d=new Set,f=m();function m(){let g=Zo(t.hubUrl,t.cliToken),y=null,w=new Li(i,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r),h=new Mi(s,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r,{contextDir:o?.contextDir??null,isSelfComment:_=>d.has(_)}),$=null,x=async()=>{try{let _={trackerProvider:Qa(o?.contextDir??null)};try{let M=await ne(t.hubUrl,t.cliToken,t.projectId);_={..._,repos:M.repos,contextRepo:M.contextRepo}}catch(M){r.warn(`[readiness] could not fetch project summary for push checks: ${M instanceof Error?M.message:String(M)}`)}let L=await Cd(t.projectId,_);if(g.readyState!==g.OPEN)return;let N={type:"cli_readiness",projectId:t.projectId,ready:L.ready,checks:L.checks,creds:L.creds,secretNames:Bu(t.projectId),checkedAt:L.checkedAt};if(g.send(JSON.stringify(N)),L.ready)r.info("[readiness] ready");else{let M=L.checks.filter(T=>!T.ok).map(T=>`${T.name}(${T.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${M.join(", ")}`)}let q=Dd(L.creds,u);if(q==="open"){u=!0;let M=Ld(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${M}`),lr(M)}else q==="rearm"&&(u=!1)}catch(_){r.warn(`[readiness] check failed: ${_ instanceof Error?_.message:String(_)}`)}},R=()=>{x(),$=setInterval(()=>void x(),a),typeof $.unref=="function"&&$.unref()},S=()=>{$&&(clearInterval($),$=null)},b=150,E=new Map,O=_=>{let L=E.get(_);if(!L||(L.timer&&clearTimeout(L.timer),E.delete(_),L.events.length===0||g.readyState!==g.OPEN))return;let N={type:"run_activity",projectId:t.projectId,runId:_,events:L.events};g.send(JSON.stringify(N))},B=(_,L)=>{let N=E.get(_);if(N||(N={events:[],timer:null},E.set(_,N)),N.events.push(L),L.kind==="result"){O(_);return}N.timer||(N.timer=setTimeout(()=>O(_),b),N.timer.unref?.())},A=o?.contextDir?new ci(o.contextDir,t.projectId,_=>{g.readyState===g.OPEN&&g.send(JSON.stringify(_))},r):null,k=async()=>{let _=o?.contextDir;if(!_)throw new Error("no context repo clone on this CLI");let L;try{L=(await ne(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let N=await Yp(_,t.projectId,L,r);return g.readyState===g.OPEN&&g.send(JSON.stringify(N)),N},D=null,j=async()=>{let _=o?.contextDir;if(_)try{let{readContextIndexHub:L,collectSearchRows:N}=await Promise.resolve().then(()=>(oo(),no));if(L(_)!=="metadata")return;let q=N(_);g.readyState===g.OPEN&&(g.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:q})),r.info(`[model] tier-2 index snapshot pushed (${q.length} rows)`))}catch(L){r.warn(`[model] tier-2 index push failed (non-fatal): ${L instanceof Error?L.message:String(L)}`)}},K=()=>{D&&clearTimeout(D),D=setTimeout(()=>void j(),5e3)},V=null,ee=async _=>{if(o?.contextDir)try{let{rebuildWorkspaceModelIfStale:L}=await Promise.resolve().then(()=>(Fi(),lc));(await L({root:o.root,contextDir:o.contextDir,repos:o.repos},{fetch:_,onLog:q=>r.info(q)})).rebuilt.length>0&&K()}catch(L){r.warn(`[model] release-path rebuild failed (non-fatal): ${L instanceof Error?L.message:String(L)}`)}},qe=_=>{V&&clearTimeout(V),V=setTimeout(()=>void ee(_),6e4)},st=setInterval(()=>void ee(!0),6*36e5);return g.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let _=Vu(t.projectId),L=z("ORIGIN")==="farm"?"farm":"local",N=z("FARM_ID"),q=t.accountEmail??_.email,M;try{let C=sf(t.projectId);C&&(M=C.publicKey,r.info(`[cred-channel] key fingerprint: ${C.fingerprint}`))}catch(C){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${C instanceof Error?C.message:String(C)}`)}let T={type:"register",projectId:t.projectId,platformVersion:Ue,protocolVersion:lt,accountId:_.accountId,accountLabel:_.label,origin:L,inFlightActionIds:[...p],...q?{accountEmail:q}:{},...L==="farm"&&N?{farmId:N}:{},...M?{sealPublicKey:M}:{}};g.send(JSON.stringify(T))}),g.on("message",async _=>{let L=_.toString("utf-8");if(L==="pong"||L==="ping")return;let N;try{N=JSON.parse(L)}catch{return}if(!N||typeof N!="object")return;let q=N.type;if(q==="registered"){let T=N;if(T.ok){if(r.info(`[ws] registered for project ${T.projectId}`),n({kind:"registered",projectId:T.projectId??t.projectId}),w.start(),A?.start(),R(),mc(t,o,r),o?.contextDir){try{let C=fi(o.contextDir,t.projectId);g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C.outdated&&(r.warn(`[ctx] context format outdated: v${C.templateVersion} \u2192 v${C.currentVersion}`+(C.missingPaths.length>0?` (missing: ${C.missingPaths.join(", ")})`:"")),l||(l=!0,k().catch(()=>{})))}catch(C){r.warn(`[ctx] context-format detect failed (non-fatal): ${C instanceof Error?C.message:String(C)}`)}j(),qe(!0)}}else r.warn(`[ws] register rejected: ${T.reason??"unknown"}`),n({kind:"register_rejected",reason:T.reason??"unknown"}),c=!0,g.close();return}if(q==="hello"){let T=N;y=Ro(T.protocolVersion);let C=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${T.platformVersion} (protocol ${T.protocolVersion}) \u2014 ${C}`),y||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ue}, protocol ${lt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${fc}`),n({kind:"incompatible",hubVersion:typeof T.platformVersion=="string"?T.platformVersion:null,hubProtocol:typeof T.protocolVersion=="number"?T.protocolVersion:null,updateCommand:fc}));return}if(q==="tracking_targets"){w.setTargets(N.targets);return}if(q==="youtrack_sync_request"){h.setRequest(N);return}if(q==="youtrack_force_sync"){h.forceSync();return}if(q==="sync_local"){await jx(N,o,g,r);return}if(q==="provision_repo"){let T=N;r.info(`[repo] provision_repo: ${T.repo.name} (${T.repo.host}:${T.repo.owner}/${T.repo.repoName})`),await Px(t,o,T.repo,r),await mc(t,o,r);return}if(q==="remove_repo"){let T=N;r.info(`[repo] remove_repo: ${T.repoName}${T.purge?" (purge)":""}`),await mc(t,o,r),T.purge&&_x(t,o,T.repoName,r);return}if(q==="context_write"){await Nx(N,o,g,r);return}if(q==="adr_promote"){await Ox(N,o,g,r);return}if(q==="cred_update"){let T=N,C=Y(t.projectId),I=C?.sealKey?await af(t.projectId,T.kind,T.sealed,C.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},W={type:"cred_update_result",updateId:T.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(W)),I.ok?(r.info(`[cred] ${T.kind} replaced${I.detail?` \u2014 ${I.detail}`:""}`),x()):r.warn(`[cred] ${T.kind} replacement rejected: ${I.detail??"unknown"}`);return}if(q==="readiness_check"){r.info("[readiness] on-demand check requested"),x();return}if(q==="agent_login_start"){Nd(t,g,N,r,x);return}if(q==="move_to_farm"){let T=N;r.info(`[farm-move] request to move ${t.projectId} onto farm ${T.farmName} (${T.farmId})`);let C=await Pm(t,T,o?.contextDir,r);g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C.ok?r.info(`[farm-move] done \u2014 farm daemon ${C.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${C.error??"unknown error"}`);return}if(q==="gh_runner_setup"){let T=N;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${T.runnerName} (${T.runnerId})`);let C=await Bm(t,T,r);g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C.ok?r.info(`[ghr] runners connected on ${T.runnerName}`):r.warn(`[ghr] setup failed: ${C.error??"see per-repo statuses"}`);return}if(q==="gh_runner_teardown"){let T=N;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${T.runnerName} (${T.runnerId})`);let C=await Fm(t,T,r);g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C.ok?r.info(`[ghr] runners disconnected from ${T.runnerName}`):r.warn(`[ghr] teardown failed: ${C.error??"unknown error"}`);return}if(q==="tracker_fields_request"){let T=N,C={type:"tracker_fields_result",requestId:T.requestId,projectId:t.projectId,ok:!1},I=kt({contextDir:o?.contextDir??null});if(!I.ok)C.error=I.error;else try{C.fields=await I.provider.fetchStateFields(T.projectKey),C.ok=!0}catch(W){C.error=W instanceof Error?W.message:String(W)}g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C.ok||r.warn(`[yt-fields] listing failed: ${C.error??"unknown"}`);return}if(q==="project_secret_update"||q==="project_secret_delete"){let T=N,C;if(T.type==="project_secret_update"){let W=Y(t.projectId);C=W?.sealKey?Hm(t.projectId,T.name,T.sealed,W.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else C=Wm(t.projectId,T.name);let I={type:"project_secret_update_result",updateId:T.updateId,projectId:t.projectId,ok:C.ok,...C.detail?{detail:C.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(I)),C.ok?(r.info(`[secret] ${T.name} ${T.type==="project_secret_update"?"saved":"deleted"}`+(C.detail?` \u2014 ${C.detail}`:"")),x()):r.warn(`[secret] ${T.name} rejected: ${C.detail??"unknown"}`);return}if(q==="auto_apply_local"){let T=N;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${T.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let C=await pp({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},T.claim,r).catch(I=>({ok:!1,message:I instanceof Error?I.message:String(I)}));C.ok?r.info(`[apply] ${T.claim.taskKey}: ${C.message}`):r.warn(`[apply] ${T.claim.taskKey}: ${C.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:T.claim.taskKey,ok:C.ok,...C.ok?{branches:C.branches??[]}:{error:C.message}});return}if(q==="sandbox_keys"){let T=Y(t.projectId);if(!T){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let C=Mr(t.projectId),I=ef(N,T,C,r);for(let W of I)g.readyState===g.OPEN&&g.send(JSON.stringify(W));return}if(q!=="dispatch_action")return;let M=N;if(y===!1){let T=`refused: HUB protocol incompatible with CLI v${Ue} (protocol ${lt})`;g.send(JSON.stringify({type:"action_result",actionId:M.actionId,status:"failed",error:T})),r.warn(`[exec] ${M.actionId} (${M.action.type}) \u2192 REFUSED: ${T}`),r.warn(`[exec] update the CLI to clear this: ${fc}`),n({kind:"action",actionId:M.actionId,actionType:M.action.type,ok:!1,error:T});return}if(M.action.type==="model_drift"){p.add(M.actionId);try{let T,C=o?.repos.find(I=>I.name===M.action.repoName);if(!o?.contextDir||!C)T={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:I}=await Promise.resolve().then(()=>(ug(),lg)),W=C.mountAs==="."?o.root:br(o.root,C.mountAs);T={status:"done",result:{report:await I(W,o.contextDir,C.name)}}}catch(I){T={status:"failed",error:I instanceof Error?I.message:String(I)}}g.send(JSON.stringify({type:"action_result",actionId:M.actionId,...T}))}finally{p.delete(M.actionId)}return}if(M.action.type==="local_apply"){p.add(M.actionId);try{let T;if(!o)T={status:"failed",error:"no local workspace on this CLI"};else{let I=await Tm(o,M.action.repos,r);if(T=I.ok?{status:"done",result:{repos:I.repos}}:{status:"failed",error:I.error},I.ok&&o.contextDir){let W=M.action.taskId.split(":")[1]??"";for(let ye of W?I.repos:[]){let Pe=o.repos.find(ue=>ue.name===ye.repoName);if(!Pe)continue;let{recordPipelineEvent:X}=await Promise.resolve().then(()=>(za(),gm));await X({contextDir:o.contextDir,repoDir:br(o.root,Pe.mountAs),repoName:ye.repoName,taskKey:W,commitSha:ye.commit}).catch(ue=>r.warn(`[model] task event for ${W} failed: ${ue instanceof Error?ue.message:String(ue)}`))}K()}}g.send(JSON.stringify({type:"action_result",actionId:M.actionId,...T}));let C=T.status!=="failed";C?r.info(`[exec] ${M.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${M.actionId} (local_apply) \u2192 FAILED: ${T.status==="failed"?T.error:"?"}`),n({kind:"action",actionId:M.actionId,actionType:"local_apply",ok:C,...T.status==="failed"?{error:T.error}:{}})}finally{p.delete(M.actionId)}return}p.add(M.actionId);try{let T=await vm({action:M.action,repo:M.repo,trackerIssueId:M.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:A?()=>A.reportNow():void 0,refreshContextStatus:o?.contextDir?k:void 0,onRunActivity:B}).catch(W=>({status:"failed",error:W instanceof Error?W.message:String(W)}));M.action.type==="tracker_comment"&&T.status==="done"&&"result"in T&&typeof T.result?.commentId=="string"&&d.add(T.result.commentId),g.send(JSON.stringify({type:"action_result",actionId:M.actionId,...T}));let C=T.status!=="failed",I=!C&&"error"in T?T.error:void 0;C?r.info(`[exec] ${M.actionId} (${M.action.type}) \u2192 done`):r.warn(`[exec] ${M.actionId} (${M.action.type}) \u2192 FAILED: ${I??"?"}`),n({kind:"action",actionId:M.actionId,actionType:M.action.type,ok:C,...I?{error:I}:{}}),C&&["apply_delivery","context_write","create_pr"].includes(M.action.type)&&K(),C&&["merge_pr","merge_branch"].includes(M.action.type)&&qe(!0)}finally{p.delete(M.actionId)}}),g.on("close",(_,L)=>{let N=L?.toString("utf-8")??"";if(r.info(`[ws] closed code=${_}${N?` reason=${N}`:""}`),w.stop(),h.stop(),A?.stop(),S(),clearInterval(st),V&&clearTimeout(V),D&&clearTimeout(D),N==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:_}),!c&&setTimeout(()=>{f=m()},2e3)}),g.on("error",_=>r.warn(`[ws] error: ${_.message}`)),g}return{stop(){c=!0,f.close()}}}async function mc(t,e,r){try{let n=await ne(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Xn(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 Px(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?br(e.root,o):Ie(t.projectId,r.name);if(pg(br(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await Ax().clone(Wn(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 _x(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?br(e.root,o):Ie(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!pg(br(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Cx(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 jx(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=br(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await mp(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 Nx(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 Ee(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 Ox(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 Ap(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 dg(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var fc,gc=v(()=>{"use strict";_e();G();zu();Od();Md();Qo();la();gp();$p();Pp();tt();xt();$a();Vp();Ea();Kr();tf();cf();xm();Em();_m();Gm();Te();qm();Gr();de();Ym();Jm();ji();fc="npm i -g @code-partner/codepipe@latest"});import{execFileSync as Dx}from"node:child_process";import{mkdtempSync as Lx,mkdirSync as Mx,readFileSync as fg,rmSync as Ux,writeFileSync as Bx}from"node:fs";import{tmpdir as Fx}from"node:os";import{dirname as Gx,join as mg}from"node:path";function gg(t="codepipe-context"){let e=Lx(mg(Fx(),"codepipe-ssh-")),r=mg(e,"id_ed25519");try{return Dx("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:fg(r,"utf-8"),publicKey:fg(`${r}.pub`,"utf-8").trim()}}finally{Ux(e,{recursive:!0,force:!0})}}async function hg(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 yg(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 kg(t,e){Mx(Gx(t),{recursive:!0});let r=e.endsWith(`
641
648
  `)?e:e+`
642
- `;return Ix(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var dc=x(()=>{"use strict"});import{existsSync as dh,mkdirSync as ph}from"node:fs";import{dirname as fh}from"node:path";import{simpleGit as rn}from"simple-git";function Ax(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 Px(t,e){return e?.contextWrite?.token?{user:No(t),secret:e.contextWrite.token}:t===Dn.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Dn.bitbucket?e?.bitbucket?.apiToken?{user:or,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function mh(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 Bi))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 Fi(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await oe(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new Bi(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=Px(Or(s.cloneUrl),r);if(a){let c=await _x({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 jx({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 _x(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Ax(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(dh(`${r}/.git`)){let l=rn(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=la(r);await l.reset(["--hard",`origin/${s}`]),ua(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else ph(fh(r),{recursive:!0}),await rn().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await hh(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 jx(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=uh(i,n),a=lh(e.cloneUrl),c=e.branch;try{if(dh(`${r}/.git`)){let l=rn(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=la(r);await l.reset(["--hard",`origin/${c}`]),ua(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ph(fh(r),{recursive:!0}),await rn().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await rn(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await hh(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 hh(t){let e=rn(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 Bi,pc=x(()=>{"use strict";K();xe();vt();dc();Bi=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as Nx}from"node:child_process";function Ox(){try{return Nx("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function yh(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Ox(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var kh=x(()=>{"use strict"});import{homedir as nn}from"node:os";import{mkdirSync as Dx,readFileSync as wh,writeFileSync as Lx,existsSync as mc}from"node:fs";import{dirname as Mx,join as Kt}from"node:path";function Ux(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function nt(t){let e=Y("SANDBOX_CONFIG");if(e)return e;let r=Kt(nn(),".codepipe","worker");return t?Kt(r,"profiles",t,"config.json"):Kt(r,"config.json")}function bh(){return Kt(nn(),".devpipe-sandbox","config.json")}function Ki(){ir(Kt(nn(),".devpipe"),Kt(nn(),".codepipe")),Y("SANDBOX_CONFIG")||ir(Kt(nn(),".devpipe-sandbox"),Kt(nn(),".codepipe-sandbox"))}function $h(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Ie(t){let e=nt(t),r=null;return mc(e)?r=JSON.parse(wh(e,"utf-8")):!t&&!Y("SANDBOX_CONFIG")&&mc(bh())&&(r=JSON.parse(wh(bh(),"utf-8"))),r?(r.planningLane=Ux(),r):null}function vh(t,e){let r=nt(e);Dx(Mx(r),{recursive:!0}),Lx(r,JSON.stringify(t,null,2)+`
643
- `,{mode:384})}var Gi=x(()=>{"use strict";Ae();Oo();mc(".env")&&process.loadEnvFile(".env")});import Bx from"ws";var on,hc=x(()=>{"use strict";on=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 Bx(e)}}});import{hostname as Fx}from"node:os";async function br(t){Ki();let e=Ie(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${nt(t.profile)}.`),process.exit(1));let r=t.name??Fx(),n=yh({projects:t.projects??[],llm:t.llm??null}),o=new on(t.hub.replace(/\/$/,"")),i=fi(),s=Pe(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});vh({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 ${nt(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 xh=x(()=>{"use strict";He();kh();Gi();hc()});import{spawn as Kx}from"node:child_process";function gc(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Hx(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 Wx(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function $r(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function yc(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
644
- `}async function Ih(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new St;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let n=e.onActivity,o=c=>{if(n)try{n(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),u=c.type;if(u==="assistant"){let p=c.message;for(let d of p?.content??[]){let m=d.type;if(m==="text"){let f=String(d.text??"").trim();f&&o({ts:l,kind:"text",author:"agent",text:gc(f,Sh)})}else if(m==="tool_use"){let f=String(d.name??""),h=d.input?.file_path??d.input?.path,k=Hx(h,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:f,...k?{file:k}:{}})}}return}if(u==="user"){let p=c.message;for(let d of p?.content??[])if(d.type==="tool_result"){let m=d.is_error===!0,f=m?gc(Wx(d.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:m,...f?{text:f}:{}})}return}if(u==="result"){s=c;let p=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...p?{text:p}:{}});return}if(u==="system"){let p=String(c.subtype??"").trim();p&&o({ts:l,kind:"system",author:"agent",text:p})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let u=Kx(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let p=!1,d=!1,m=null,f=()=>{p=!0,u.kill("SIGTERM"),m=setTimeout(()=>u.kill("SIGKILL"),Th)};e.signal?.addEventListener("abort",f,{once:!0});let h=null,k=()=>{h&&clearTimeout(h),h=setTimeout(()=>{d=!0,console.warn(`[claude:chat] idle for ${Rh}ms \u2014 ending session`),u.kill("SIGTERM"),m=setTimeout(()=>u.kill("SIGKILL"),Th)},Rh)},y=()=>{m&&clearTimeout(m),h&&clearTimeout(h),e.signal?.removeEventListener("abort",f)},g=!0,$=S=>{if(!(!g||u.stdin.destroyed))try{u.stdin.write(S)}catch{}};$(yc(e.prompt)),k(),(async()=>{try{for await(let S of e.interactive.inbox){if(p||!g)break;if(k(),S.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:gc(S.text,Sh)}),$(yc(S.text));else{$(yc(Gx)),g=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let T="",C=S=>{let b;try{b=JSON.parse(S)}catch{return}a(b)};u.stdout.on("data",S=>{i.push(S),k(),T+=S;let b;for(;(b=T.indexOf(`
645
- `))!==-1;){let I=T.slice(0,b).trim();T=T.slice(b+1),I&&C(I)}}),u.stderr.on("data",S=>{i.push(S);for(let b of S.split(`
646
- `)){let I=b.trim();I&&console.warn(`[claude:chat:stderr] ${I}`)}}),u.on("error",S=>{y(),l(S)}),u.on("close",S=>{if(y(),p){l(new St);return}if(d){l(new Error("chat session ended: idle for too long without a reply"));return}T.trim()&&C(T.trim()),console.log(`[claude:chat] exit code=${S}`),c({artifactPaths:[],log:i.join(""),usage:Yx(s)})})})}function Yx(t){let e=tr();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=$r(r.input_tokens),e.outputTokens=$r(r.output_tokens),e.cacheReadInputTokens=$r(r.cache_read_input_tokens),e.cacheCreationInputTokens=$r(r.cache_creation_input_tokens)),e.totalCostUsd=$r(t.total_cost_usd),e.numTurns=$r(t.num_turns),e.durationMs=$r(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Sh,Th,Rh,Gx,Eh=x(()=>{"use strict";K();sn();Sh=16e3,Th=5e3,Rh=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Gx="\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B \u0434\u0438\u0430\u043B\u043E\u0433. \u0422\u0435\u043F\u0435\u0440\u044C, \u043E\u043F\u0438\u0440\u0430\u044F\u0441\u044C \u043D\u0430 \u0432\u0441\u0451, \u0447\u0442\u043E \u043C\u044B \u043E\u0431\u0441\u0443\u0434\u0438\u043B\u0438, \u043D\u0430\u043F\u0438\u0448\u0438 \u0444\u0430\u0439\u043B DRAFT.md \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u043F\u043E \u043E\u043F\u0438\u0441\u0430\u043D\u043D\u043E\u043C\u0443 \u043A\u043E\u043D\u0442\u0440\u0430\u043A\u0442\u0443 (\u0441\u0442\u0440\u043E\u043A\u0430 1 \u2014 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u226480 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C, \u0441\u0442\u0440\u043E\u043A\u0430 2 \u043F\u0443\u0441\u0442\u0430\u044F, \u0434\u0430\u043B\u044C\u0448\u0435 \u0442\u0435\u043B\u043E \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C \u0432 Markdown) \u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0438 \u0440\u0430\u0431\u043E\u0442\u0443. \u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043F\u0438\u0448\u0438."});import{spawn as qx}from"node:child_process";import{existsSync as Vx}from"node:fs";function Jx(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Ch(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: ${Gt(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=Zx(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=Ph(o.content);console.log(`[claude] tool_result (error)${i?`: ${Gt(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)} ${Gt(JSON.stringify(e),200)}`),e}function Xx(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(Gt(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(Gt(r.trim().split(`
649
+ `;return Bx(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var hc=v(()=>{"use strict"});import{existsSync as wg,mkdirSync as bg}from"node:fs";import{dirname as $g}from"node:path";import{simpleGit as nn}from"simple-git";function Kx(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 Hx(t,e){return e?.contextWrite?.token?{user:Lo(t),secret:e.contextWrite.token}:t===Mn.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Mn.bitbucket?e?.bitbucket?.apiToken?{user:ir,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function vg(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 Ki))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 Hi(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await ne(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new Ki(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=Hx(Dr(s.cloneUrl),r);if(a){let c=await Wx({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 qx({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 Wx(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Kx(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(wg(`${r}/.git`)){let l=nn(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=ma(r);await l.reset(["--hard",`origin/${s}`]),ga(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else bg($g(r),{recursive:!0}),await nn().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await xg(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 qx(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=kg(i,n),a=yg(e.cloneUrl),c=e.branch;try{if(wg(`${r}/.git`)){let l=nn(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=ma(r);await l.reset(["--hard",`origin/${c}`]),ga(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else bg($g(r),{recursive:!0}),await nn().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await nn(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await xg(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 xg(t){let e=nn(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 Ki,yc=v(()=>{"use strict";G();Te();xt();hc();Ki=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as Yx}from"node:child_process";function Vx(){try{return Yx("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Tg(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Vx(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Eg=v(()=>{"use strict"});import{homedir as on}from"node:os";import{mkdirSync as zx,readFileSync as Rg,writeFileSync as Jx,existsSync as wc}from"node:fs";import{dirname as Xx,join as Gt}from"node:path";function Qx(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function nt(t){let e=z("SANDBOX_CONFIG");if(e)return e;let r=Gt(on(),".codepipe","worker");return t?Gt(r,"profiles",t,"config.json"):Gt(r,"config.json")}function Ig(){return Gt(on(),".devpipe-sandbox","config.json")}function Wi(){sr(Gt(on(),".devpipe"),Gt(on(),".codepipe")),z("SANDBOX_CONFIG")||sr(Gt(on(),".devpipe-sandbox"),Gt(on(),".codepipe-sandbox"))}function Cg(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Ce(t){let e=nt(t),r=null;return wc(e)?r=JSON.parse(Rg(e,"utf-8")):!t&&!z("SANDBOX_CONFIG")&&wc(Ig())&&(r=JSON.parse(Rg(Ig(),"utf-8"))),r?(r.planningLane=Qx(),r):null}function Ag(t,e){let r=nt(e);zx(Xx(r),{recursive:!0}),Jx(r,JSON.stringify(t,null,2)+`
650
+ `,{mode:384})}var qi=v(()=>{"use strict";_e();Mo();wc(".env")&&process.loadEnvFile(".env")});import Zx from"ws";var sn,bc=v(()=>{"use strict";sn=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 Zx(e)}}});import{hostname as eS}from"node:os";async function $r(t){Wi();let e=Ce(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${nt(t.profile)}.`),process.exit(1));let r=t.name??eS(),n=Tg({projects:t.projects??[],llm:t.llm??null}),o=new sn(t.hub.replace(/\/$/,"")),i=hi(),s=je(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Ag({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 ${nt(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 Pg=v(()=>{"use strict";He();Eg();qi();bc()});function _g(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 jg(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 Ng(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 Yi(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 $c=v(()=>{"use strict"});import{spawn as tS}from"node:child_process";function vc(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function nS(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 oS(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function vr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function xc(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}})+`
651
+ `}async function Mg(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Tt;let r=Yi(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",_g(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim());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 f of d?.content??[]){let m=f.type;if(m==="text"){let g=String(f.text??"").trim();g&&i({ts:u,kind:"text",author:"agent",text:vc(g,Og)})}else if(m==="tool_use"){let g=String(f.name??""),y=f.input?.file_path??f.input?.path,w=nS(y,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:g,...w?{file:w}:{}})}}return}if(p==="user"){let d=l.message;for(let f of d?.content??[])if(f.type==="tool_result"){let m=f.is_error===!0,g=m?vc(oS(f.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:m,...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=tS(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,f=!1,m=null,g=()=>{d=!0,p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Dg)};e.signal?.addEventListener("abort",g,{once:!0});let y=null,w=()=>{y&&clearTimeout(y),y=setTimeout(()=>{f=!0,console.warn(`[claude:chat] idle for ${Lg}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),Dg)},Lg)},h=()=>{m&&clearTimeout(m),y&&clearTimeout(y),e.signal?.removeEventListener("abort",g)},$=!0,x=b=>{if(!(!$||p.stdin.destroyed))try{p.stdin.write(b)}catch{}};x(xc(e.prompt)),w(),(async()=>{try{for await(let b of e.interactive.inbox){if(d||!$)break;if(w(),b.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:vc(b.text,Og)}),x(xc(b.text,Ng(r)));else{x(xc(rS)),$=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let R="",S=b=>{let E;try{E=JSON.parse(b)}catch{return}c(E)};p.stdout.on("data",b=>{s.push(b),w(),R+=b;let E;for(;(E=R.indexOf(`
652
+ `))!==-1;){let O=R.slice(0,E).trim();R=R.slice(E+1),O&&S(O)}}),p.stderr.on("data",b=>{s.push(b);for(let E of b.split(`
653
+ `)){let O=E.trim();O&&console.warn(`[claude:chat:stderr] ${O}`)}}),p.on("error",b=>{h(),u(b)}),p.on("close",b=>{if(h(),d){u(new Tt);return}if(f){u(new Error("chat session ended: idle for too long without a reply"));return}R.trim()&&S(R.trim()),console.log(`[claude:chat] exit code=${b}`),l({artifactPaths:[],log:s.join(""),usage:iS(a)})})})}function iS(t){let e=tr();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=vr(r.input_tokens),e.outputTokens=vr(r.output_tokens),e.cacheReadInputTokens=vr(r.cache_read_input_tokens),e.cacheCreationInputTokens=vr(r.cache_creation_input_tokens)),e.totalCostUsd=vr(t.total_cost_usd),e.numTurns=vr(t.num_turns),e.durationMs=vr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Og,Dg,Lg,rS,Ug=v(()=>{"use strict";G();an();$c();Og=16e3,Dg=5e3,Lg=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),rS="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{spawn as sS}from"node:child_process";import{existsSync as aS}from"node:fs";function lS(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Bg(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: ${Kt(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=pS(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=Gg(o.content);console.log(`[claude] tool_result (error)${i?`: ${Kt(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)} ${Kt(JSON.stringify(e),200)}`),e}function uS(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(Kt(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(Kt(r.trim().split(`
647
654
  `).slice(-5).join(`
648
- `),500)),n.join(" \u2014 ")}function Qx(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 Ph(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Zx(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=${Gt(r,80)}`}return""}function Gt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function je(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function eS(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=je(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:je(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 tS(t,e,r,n){let o=tr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=je(i.input_tokens),o.outputTokens=je(i.output_tokens),o.cacheReadInputTokens=je(i.cache_read_input_tokens),o.cacheCreationInputTokens=je(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=je(t?.total_cost_usd),o.numTurns=t&&je(t.num_turns)>0?je(t.num_turns):r,o.durationMs=je(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function rS(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:Gt(c,Ah)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=nS(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?Gt(Ph(s.content),Ah):"";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 nS(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 an,St,zx,co,Ah,sn=x(()=>{"use strict";K();Eh();an=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},St=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},zx=5e3;co=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Ih(this.binary,e);if(e.signal?.aborted)throw new St;let r=["-p",Jx(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let f of e.addDirs??[])r.push("--add-dir",f);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=f=>{if(f){if(f.type==="result"){i=f;return}if(f.type==="rate_limit_event"){let h=eS(f.rate_limit_info);h&&(!l||h.utilization>l.utilization)&&(l=h);return}if(f.type==="assistant"){let h=f.message;typeof h?.model=="string"&&(c=h.model);let k=h?.usage;k&&(a+=1,s.input+=je(k.input_tokens),s.output+=je(k.output_tokens),s.cacheRead+=je(k.cache_read_input_tokens),s.cacheCreate+=je(k.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let h of rS(f,e.workspaceDir))try{d(h)}catch{}};return d?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((f,h)=>{let k=qx(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let y=!1,g=null,$=()=>{y=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),k.kill("SIGTERM"),g=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},zx)};e.signal?.addEventListener("abort",$,{once:!0});let T=()=>{g&&clearTimeout(g),e.signal?.removeEventListener("abort",$)},C="";k.stdout.on("data",S=>{n.push(S),C+=S;let b;for(;(b=C.indexOf(`
649
- `))!==-1;){let I=C.slice(0,b).trim();if(C=C.slice(b+1),I){let M=Ch(I);u(M),M&&m(M)}}}),k.stderr.on("data",S=>{n.push(S),o.push(S);for(let b of S.split(`
650
- `)){let I=b.trim();I&&console.warn(`[claude:stderr] ${I}`)}}),k.on("error",S=>{T(),h(S)}),k.on("close",S=>{if(T(),y){h(new St);return}if(C.trim()){let I=Ch(C.trim());u(I),I&&m(I)}let b=i?.is_error===!0;if(S!==0||b){let I=typeof i?.api_error_status=="number"?i.api_error_status:void 0,M=typeof i?.subtype=="string"?i.subtype:void 0,G=typeof i?.result=="string"?i.result:void 0;h(new an(Xx(S,i,o.join("")),{code:S,apiErrorStatus:I,subtype:M,resultText:G,retryAfterMs:Qx(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:tS(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&Vx(n))}};Ah=200});import{mkdirSync as oS,writeFileSync as cn}from"node:fs";import{dirname as iS,join as ln}from"node:path";function _h(t,e,r){let n=ln(t,e);oS(iS(n),{recursive:!0}),cn(n,r)}function sS(t,e,r){return`# ${t} \u2014 Estimate
655
+ `),500)),n.join(" \u2014 ")}function dS(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 Gg(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function pS(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=${Kt(r,80)}`}return""}function Kt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Oe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function fS(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Oe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Oe(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 mS(t,e,r,n){let o=tr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=Oe(i.input_tokens),o.outputTokens=Oe(i.output_tokens),o.cacheReadInputTokens=Oe(i.cache_read_input_tokens),o.cacheCreationInputTokens=Oe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Oe(t?.total_cost_usd),o.numTurns=t&&Oe(t.num_turns)>0?Oe(t.num_turns):r,o.durationMs=Oe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function gS(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:Kt(c,Fg)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=hS(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?Kt(Gg(s.content),Fg):"";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 hS(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 cn,Tt,cS,uo,Fg,an=v(()=>{"use strict";G();Ug();$c();cn=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Tt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},cS=5e3;uo=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Mg(this.binary,e);if(e.signal?.aborted)throw new Tt;let r=["-p",lS(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",jg(Yi(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let m of e.addDirs??[])r.push("--add-dir",m);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=m=>{if(m){if(m.type==="result"){i=m;return}if(m.type==="rate_limit_event"){let g=fS(m.rate_limit_info);g&&(!l||g.utilization>l.utilization)&&(l=g);return}if(m.type==="assistant"){let g=m.message;typeof g?.model=="string"&&(c=g.model);let y=g?.usage;y&&(a+=1,s.input+=Oe(y.input_tokens),s.output+=Oe(y.output_tokens),s.cacheRead+=Oe(y.cache_read_input_tokens),s.cacheCreate+=Oe(y.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,f=m=>{if(d)for(let g of gS(m,e.workspaceDir))try{d(g)}catch{}};return d?.({ts:Date.now(),kind:"start",text:`${p} job started`}),console.log(`[claude] spawn ${this.binary} role=${p}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((m,g)=>{let y=sS(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});y.stdout.setEncoding("utf-8"),y.stderr.setEncoding("utf-8");let w=!1,h=null,$=()=>{w=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${p}`),y.kill("SIGTERM"),h=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),y.kill("SIGKILL")},cS)};e.signal?.addEventListener("abort",$,{once:!0});let x=()=>{h&&clearTimeout(h),e.signal?.removeEventListener("abort",$)},R="";y.stdout.on("data",S=>{n.push(S),R+=S;let b;for(;(b=R.indexOf(`
656
+ `))!==-1;){let E=R.slice(0,b).trim();if(R=R.slice(b+1),E){let O=Bg(E);u(O),O&&f(O)}}}),y.stderr.on("data",S=>{n.push(S),o.push(S);for(let b of S.split(`
657
+ `)){let E=b.trim();E&&console.warn(`[claude:stderr] ${E}`)}}),y.on("error",S=>{x(),g(S)}),y.on("close",S=>{if(x(),w){g(new Tt);return}if(R.trim()){let E=Bg(R.trim());u(E),E&&f(E)}let b=i?.is_error===!0;if(S!==0||b){let E=typeof i?.api_error_status=="number"?i.api_error_status:void 0,O=typeof i?.subtype=="string"?i.subtype:void 0,B=typeof i?.result=="string"?i.result:void 0;g(new cn(uS(S,i,o.join("")),{code:S,apiErrorStatus:E,subtype:O,resultText:B,retryAfterMs:dS(i)}));return}console.log("[claude] exit code=0"),m({artifactPaths:[],log:n.join(""),usage:mS(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&aS(n))}};Fg=200});import{mkdirSync as yS,writeFileSync as ln}from"node:fs";import{dirname as kS,join as un}from"node:path";function Kg(t,e,r){let n=un(t,e);yS(kS(n),{recursive:!0}),ln(n,r)}function wS(t,e,r){return`# ${t} \u2014 Estimate
651
658
 
652
659
  **Title:** ${e}
653
660
 
@@ -668,7 +675,7 @@ production-grade estimates.)
668
675
  ${r.split(`
669
676
  `).slice(0,8).join(`
670
677
  `).trim()||"(empty)"}
671
- `}function aS(t,e,r,n){let o=n?`
678
+ `}function bS(t,e,r,n){let o=n?`
672
679
  ## Reviewer rework instruction
673
680
 
674
681
  > ${n.split(`
@@ -697,10 +704,10 @@ TBD (mock runner does not yet inspect project code).
697
704
  ${r.split(`
698
705
  `).slice(0,8).join(`
699
706
  `).trim()||"(empty)"}
700
- `}function cS(t){return`# ${t} \u2014 Open questions
707
+ `}function $S(t){return`# ${t} \u2014 Open questions
701
708
 
702
709
  (none \u2014 mock runner did not surface ambiguities.)
703
- `}function lS(t,e,r){let n=r?` (rework: ${r.split(`
710
+ `}function vS(t,e,r){let n=r?` (rework: ${r.split(`
704
711
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
705
712
  index 0000000..1111111 100644
706
713
  --- a/CHANGELOG.md
@@ -711,7 +718,7 @@ index 0000000..1111111 100644
711
718
  +- mock-runner placeholder change for slice 5 testing.
712
719
  +
713
720
  # Changelog
714
- `}function uS(t,e,r){return`# ${t} \u2014 Diff summary
721
+ `}function xS(t,e,r){return`# ${t} \u2014 Diff summary
715
722
 
716
723
  **Title:** ${e}
717
724
  ${r?`
@@ -722,143 +729,143 @@ ${r?`
722
729
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
723
730
 
724
731
  (Mock-runner output. Replace with claude-headless for production patches.)
725
- `}var lo,kc=x(()=>{"use strict";K();sn();lo=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=sS(n,o,i);cn(ln(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;cn(ln(e.workspaceDir,"SOLUTION.md"),aS(n,o,i,a)),s.push("SOLUTION.md"),cn(ln(e.workspaceDir,"QUESTIONS.md"),cS(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;_h(e.workspaceDir,"changes/sample.patch",lS(n,o,a)),s.push("changes/sample.patch"),_h(e.workspaceDir,"diff-summary.md",uS(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(cn(ln(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
726
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:tr()}}async runInteractive(e){let r=e.onActivity,n=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("\u041F\u0440\u0438\u0432\u0435\u0442! \u041E\u043F\u0438\u0448\u0438\u0442\u0435 \u0437\u0430\u0434\u0430\u0447\u0443, \u043A\u043E\u0442\u043E\u0440\u0443\u044E \u0445\u043E\u0442\u0438\u0442\u0435 \u0441\u0444\u043E\u0440\u043C\u0443\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C.");let o="\u0427\u0435\u0440\u043D\u043E\u0432\u0438\u043A \u0438\u0437 \u0447\u0430\u0442\u0430";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new St;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`\u041F\u043E\u043D\u044F\u043B: **${i.text.trim()}**. \u0427\u0442\u043E-\u043D\u0438\u0431\u0443\u0434\u044C \u0435\u0449\u0451 \u0443\u0442\u043E\u0447\u043D\u0438\u0442\u044C?`);else break}return cn(ln(e.workspaceDir,"DRAFT.md"),`${o}
732
+ `}var po,Sc=v(()=>{"use strict";G();an();po=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=wS(n,o,i);ln(un(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;ln(un(e.workspaceDir,"SOLUTION.md"),bS(n,o,i,a)),s.push("SOLUTION.md"),ln(un(e.workspaceDir,"QUESTIONS.md"),$S(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Kg(e.workspaceDir,"changes/sample.patch",vS(n,o,a)),s.push("changes/sample.patch"),Kg(e.workspaceDir,"diff-summary.md",xS(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(ln(un(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
733
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:tr()}}async runInteractive(e){let r=e.onActivity,n=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),n("Hi! Describe the task you'd like to formulate.");let o="Draft from chat";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Tt;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(o=i.text.trim().slice(0,80)),n(`Got it: **${i.text.trim()}**. Anything else to clarify?`);else break}return ln(un(e.workspaceDir,"DRAFT.md"),`${o}
727
734
 
728
- \u0421\u0444\u043E\u0440\u043C\u0438\u0440\u043E\u0432\u0430\u043D\u043E \u0432 \u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u043E\u043C \u0447\u0430\u0442\u0435 (mock runner).
729
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:tr()}}}});function jh(t){switch(t){case"mock":return new lo;case"claude-headless":return new co;default:return null}}function Nh(t,e){let r=e&&e.trim().length>0?e.trim():ut;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var Oh=x(()=>{"use strict";K();sn();kc();sn();kc()});function Mh(t=process.env){return{maxAttempts:Hi(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Hi(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Hi(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Hi(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function mS(t){if(t instanceof an){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return pS.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&fS.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:dS.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Dh.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 Dh.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Uh(t){if(t instanceof an){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Lh.test(n)}let e=t instanceof Error?t.message:String(t);return Lh.test(e)}function hS(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 Bh(t,e,r){let n=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),o=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=mS(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let u=hS(s,r.policy,c.retryAfterMs);if(Date.now()+u>o)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await n(u)}}function Hi(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var dS,Dh,pS,fS,Lh,Fh=x(()=>{"use strict";sn();dS=new Set([429,500,502,503,529]),Dh=/(\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,pS=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,fS=new Set(["error_max_turns"]);Lh=/(not logged in|invalid api key|invalid x-api-key|authentication[ _]error|unauthorized|oauth token (?:expired|revoked|invalid)|token (?:expired|revoked)|please run .{0,20}login|run `?claude\b.{0,20}(?:login|setup-token))/i});import{mkdtempSync as gS,rmSync as yS,writeFileSync as Kh}from"node:fs";import{tmpdir as kS}from"node:os";import{join as wc}from"node:path";function Wi(t){return`[url "https://${t}/"]
735
+ Produced by the interactive chat (mock runner).
736
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:tr()}}}});function Hg(t){switch(t){case"mock":return new po;case"claude-headless":return new uo;default:return null}}function Wg(t,e){let r=e&&e.trim().length>0?e.trim():pt;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var qg=v(()=>{"use strict";G();an();Sc();an();Sc()});function zg(t=process.env){return{maxAttempts:Vi(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Vi(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Vi(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Vi(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function RS(t){if(t instanceof cn){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return TS.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&ES.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:SS.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Yg.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 Yg.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Jg(t){if(t instanceof cn){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Vg.test(n)}let e=t instanceof Error?t.message:String(t);return Vg.test(e)}function IS(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 Xg(t,e,r){let n=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),o=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=RS(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let u=IS(s,r.policy,c.retryAfterMs);if(Date.now()+u>o)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${u}ms`),await r.onBeforeRetry(),await n(u)}}function Vi(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var SS,Yg,TS,ES,Vg,Qg=v(()=>{"use strict";an();SS=new Set([429,500,502,503,529]),Yg=/(\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,TS=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,ES=new Set(["error_max_turns"]);Vg=/(not logged in|invalid api key|invalid x-api-key|authentication[ _]error|unauthorized|oauth token (?:expired|revoked|invalid)|token (?:expired|revoked)|please run .{0,20}login|run `?claude\b.{0,20}(?:login|setup-token))/i});import{mkdtempSync as CS,rmSync as AS,writeFileSync as Zg}from"node:fs";import{tmpdir as PS}from"node:os";import{join as Tc}from"node:path";function zi(t){return`[url "https://${t}/"]
730
737
  insteadOf = git@${t}:
731
738
  insteadOf = ssh://git@${t}/
732
- `}function Gh(t,e){if(t.length===0)return null;let r=gS(wc(kS(),"devpipe-gitcreds-")),n=wc(r,"credentials"),o=wc(r,"gitconfig");return Kh(n,t.join(`
739
+ `}function eh(t,e){if(t.length===0)return null;let r=CS(Tc(PS(),"devpipe-gitcreds-")),n=Tc(r,"credentials"),o=Tc(r,"gitconfig");return Zg(n,t.join(`
733
740
  `)+`
734
- `,{mode:384}),Kh(o,`[credential]
741
+ `,{mode:384}),Zg(o,`[credential]
735
742
  helper = store --file=${n}
736
- `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{yS(r,{recursive:!0,force:!0})}catch{}}}}function bc(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(wS)),t.bitbucket?.apiToken&&(e.push(`https://${or}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(bS)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push($S)),Gh(e,r)}function Hh(t,e){if(t.contextWrite?.token){let r=Or(e)??"github.com",n=No(r);return Gh([`https://${n}:${t.contextWrite.token}@${r}`],[Wi(r)])}return bc(t)}var wS,bS,$S,Wh=x(()=>{"use strict";K();wS=Wi("github.com"),bS=Wi("bitbucket.org"),$S=Wi("gitlab.com")});import{spawn as qh}from"node:child_process";import{existsSync as Yi,mkdirSync as uo,readFileSync as vS,rmSync as $c,symlinkSync as xS}from"node:fs";import{homedir as SS}from"node:os";import{dirname as dn,join as Ht}from"node:path";function Vh(t){let e=Ht(SS(),".codepipe-sandbox","repos");return t?Ht(e,t):e}function zh(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 Yh(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 TS(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 Jh(t,e,r,n,o){let i=async c=>{await ie(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ie(t,["reset","--hard",`origin/${c}`],o),await ie(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!Yh(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Yi(t)&&$c(t,{recursive:!0,force:!0}),uo(dn(t),{recursive:!0});try{return await ie(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Yh(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Yi(t)&&$c(t,{recursive:!0,force:!0}),uo(dn(t),{recursive:!0}),await ie(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Yi(Ht(t,".git")))try{return await s()}catch(c){if(!TS(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 Xh(t){await ie(t.workspacePath,["reset","--hard",t.baseSha]),await ie(t.workspacePath,["clean","-fdx"])}async function Qh(t,e){let r=t.workspacePath;await ie(r,["add","-A"]);let n=(await Te(r,["write-tree"])).trim(),o=(await Te(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:pn,GIT_AUTHOR_EMAIL:fn,GIT_COMMITTER_NAME:pn,GIT_COMMITTER_EMAIL:fn};return(await Te(r,["commit-tree",n,"-m",e],i)).trim()}async function Zh(t,e,r,n,o){try{await ie(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Or(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 eg(t,e){return Te(t.workspacePath,["diff","--binary",t.baseSha,e])}async function tg(t,e,r,n,o){await ie(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ie(t.workspacePath,["checkout","--force",r])}async function rg(t,e,r,n,o,i){let s=t.workspacePath;await ie(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await Te(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=f=>Te(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Te(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ie(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(h=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(h)}`)}),await c(n)||await ie(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:pn,GIT_AUTHOR_EMAIL:fn,GIT_COMMITTER_NAME:pn,GIT_COMMITTER_EMAIL:fn},u=(await Te(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Te(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ie(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ie(s,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await Te(s,["diff","--name-only","--diff-filter=U"])).split(`
737
- `).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await ie(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 vc(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:pn,GIT_AUTHOR_EMAIL:fn,GIT_COMMITTER_NAME:pn,GIT_COMMITTER_EMAIL:fn};(await Te(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ie(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 ie(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ie(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Te(n,["diff","--name-only","--diff-filter=U"])).split(`
738
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await Te(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function ie(t,e,r){return new Promise((n,o)=>{let i=qh("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
739
- ${s.join("").trim()||"(no stderr)"}`))})})}function Te(t,e,r){return new Promise((n,o)=>{let i=qh("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
740
- ${a.join("").trim()||"(no stderr)"}`))})})}function ng(t,e){Yi(t)&&$c(t,{recursive:!0,force:!0}),uo(dn(t),{recursive:!0}),xS(e,t,"dir")}async function og(t,e,r){await ie(t,["worktree","prune"]).catch(()=>{}),uo(dn(r),{recursive:!0}),await ie(t,["worktree","add","--detach",r,`origin/${e}`])}async function RS(t,e,r){uo(dn(r),{recursive:!0}),await ie(dn(r),["clone","--quiet","--no-checkout",t,r]),await ie(r,["checkout","--force","--detach",e])}async function ig(t,e,r,n="worktree",o,i){return r.length===0?[]:zh(e,async()=>{let s=[];for(let a of r){let c=Ht(Vh(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await Jh(c,a.cloneUrl,a.ref,a.defaultBranch,o)}catch(d){throw new Error(`failed to materialize project repo "${a.name}" (${a.cloneUrl}): `+(d instanceof Error?d.message:String(d)))}let u=(await Te(c,["rev-parse","HEAD"])).trim(),p=Ht(t,"code",a.name);n==="direct"?(ng(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await RS(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await og(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 sg(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return zh(e,async()=>{let a=Ht(Vh(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await Jh(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=Ht(t,"context");n==="direct"?(ng(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await og(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Te(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function ag(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ie(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Te(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
741
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=vS(Ht(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var un,pn,fn,cg=x(()=>{"use strict";K();un=new Map;pn="CodePipe Agent",fn="codepipe@codepartner.ee"});import{readFileSync as IS}from"node:fs";import{join as ES}from"node:path";function lg(t){let e=ES(t,po),r;try{r=IS(e,"utf-8")}catch{throw new Wt(`BUILD produced no ${po} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Wt(`${po} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Wt(`${po} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Wt(`${po}: "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"?CS(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 CS(t){let e=Buffer.from(t,"utf-8");return e.length<=xc?t:`\u2026 [${e.length-xc} bytes elided] \u2026
742
- `+e.subarray(e.length-xc).toString("utf-8")}var xc,Wt,po,ug=x(()=>{"use strict";xc=8*1024,Wt=class extends Error{},po="meta/build-result.json"});import{readFileSync as AS}from"node:fs";import{join as PS}from"node:path";function pg(t){let e=PS(t,mn),r;try{r=AS(e,"utf-8")}catch{throw new Tt(`code review produced no ${mn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new Tt(`${mn} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new Tt(`${mn} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Tt(`${mn}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?dg(o.remarks,_S):"";if(!i&&s.trim().length===0)throw new Tt(`${mn}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?dg(o.summary,jS):"";return{approved:i,remarks:s,summary:a}}function dg(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
743
- \u2026 [${r.length-e} bytes elided]`}var _S,jS,Tt,mn,fg=x(()=>{"use strict";_S=16*1024,jS=4*1024,Tt=class extends Error{},mn="meta/review-result.json"});import{readFileSync as NS,statSync as OS}from"node:fs";import{join as mg}from"node:path";function KS(t){return t.startsWith("meta/")||FS.has(t)}function GS(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 HS(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function hg(t,e,r){let n=r?.maxBytes??DS,o=r?.totalBytes??LS,i=r?.maxCount??MS,s=e.map((f,h)=>{let k=null;try{k=OS(mg(t,f)).size}catch{}return{path:f,index:h,size:k}}),a=[...s].sort((f,h)=>{let k=y=>KS(y.path)?0:1;return k(f)!==k(h)?k(f)-k(h):(f.size??0)-(h.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((f,h)=>f.index-h.index).map(f=>f.path),u=new Array(s.length),p=[],d=0;for(let f of c){let h=null;if(f.size!==null&&f.size<=n&&d+f.size<=o)try{h=NS(mg(t,f.path))}catch{}if(h!==null){d+=h.length,u[f.index]={path:f.path,contentBase64:h.toString("base64")};continue}let k=f.size===null?HS(f.path):GS(f.path,f.size,n,o),y=Buffer.from(k,"utf-8");d+=y.length,u[f.index]={path:f.path,contentBase64:y.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,BS),h=`# Artifacts omitted from upload
743
+ `+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{AS(r,{recursive:!0,force:!0})}catch{}}}}function Ec(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(_S)),t.bitbucket?.apiToken&&(e.push(`https://${ir}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(jS)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(NS)),eh(e,r)}function th(t,e){if(t.contextWrite?.token){let r=Dr(e)??"github.com",n=Lo(r);return eh([`https://${n}:${t.contextWrite.token}@${r}`],[zi(r)])}return Ec(t)}var _S,jS,NS,rh=v(()=>{"use strict";G();_S=zi("github.com"),jS=zi("bitbucket.org"),NS=zi("gitlab.com")});import{spawn as oh}from"node:child_process";import{existsSync as Ji,mkdirSync as fo,readFileSync as OS,rmSync as Rc,symlinkSync as DS}from"node:fs";import{homedir as LS}from"node:os";import{dirname as pn,join as Ht}from"node:path";function ih(t){let e=Ht(LS(),".codepipe-sandbox","repos");return t?Ht(e,t):e}function sh(t,e){let n=(dn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{dn.get(t)===o&&dn.delete(t)},()=>{dn.get(t)===o&&dn.delete(t)});return dn.set(t,o),n}function nh(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 MS(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 ah(t,e,r,n,o){let i=async c=>{await oe(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await oe(t,["reset","--hard",`origin/${c}`],o),await oe(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!nh(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Ji(t)&&Rc(t,{recursive:!0,force:!0}),fo(pn(t),{recursive:!0});try{return await oe(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!nh(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Ji(t)&&Rc(t,{recursive:!0,force:!0}),fo(pn(t),{recursive:!0}),await oe(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Ji(Ht(t,".git")))try{return await s()}catch(c){if(!MS(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 ch(t){await oe(t.workspacePath,["reset","--hard",t.baseSha]),await oe(t.workspacePath,["clean","-fdx"])}async function lh(t,e){let r=t.workspacePath;await oe(r,["add","-A"]);let n=(await Re(r,["write-tree"])).trim(),o=(await Re(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:fn,GIT_AUTHOR_EMAIL:mn,GIT_COMMITTER_NAME:fn,GIT_COMMITTER_EMAIL:mn};return(await Re(r,["commit-tree",n,"-m",e],i)).trim()}async function uh(t,e,r,n,o){try{await oe(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Dr(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 dh(t,e){return Re(t.workspacePath,["diff","--binary",t.baseSha,e])}async function ph(t,e,r,n,o){await oe(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await oe(t.workspacePath,["checkout","--force",r])}async function fh(t,e,r,n,o,i){let s=t.workspacePath;await oe(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await Re(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=m=>Re(s,["rev-parse","-q","--verify",`${m}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Re(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await oe(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 oe(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:mn,GIT_COMMITTER_NAME:fn,GIT_COMMITTER_EMAIL:mn},u=(await Re(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Re(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await oe(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await oe(s,["cherry-pick","--no-commit",p],l)}catch(m){d=m instanceof Error?m.message:String(m)}let f=(await Re(s,["diff","--name-only","--diff-filter=U"])).split(`
744
+ `).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await oe(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return f}async function Ic(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:fn,GIT_AUTHOR_EMAIL:mn,GIT_COMMITTER_NAME:fn,GIT_COMMITTER_EMAIL:mn};(await Re(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await oe(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 oe(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await oe(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Re(n,["diff","--name-only","--diff-filter=U"])).split(`
745
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await Re(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function oe(t,e,r){return new Promise((n,o)=>{let i=oh("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}):
746
+ ${s.join("").trim()||"(no stderr)"}`))})})}function Re(t,e,r){return new Promise((n,o)=>{let i=oh("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}):
747
+ ${a.join("").trim()||"(no stderr)"}`))})})}function mh(t,e){Ji(t)&&Rc(t,{recursive:!0,force:!0}),fo(pn(t),{recursive:!0}),DS(e,t,"dir")}async function gh(t,e,r){await oe(t,["worktree","prune"]).catch(()=>{}),fo(pn(r),{recursive:!0}),await oe(t,["worktree","add","--detach",r,`origin/${e}`])}async function US(t,e,r){fo(pn(r),{recursive:!0}),await oe(pn(r),["clone","--quiet","--no-checkout",t,r]),await oe(r,["checkout","--force","--detach",e])}async function hh(t,e,r,n="worktree",o,i){return r.length===0?[]:sh(e,async()=>{let s=[];for(let a of r){let c=Ht(ih(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await ah(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 Re(c,["rev-parse","HEAD"])).trim(),p=Ht(t,"code",a.name);n==="direct"?(mh(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await US(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await gh(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 yh(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return sh(e,async()=>{let a=Ht(ih(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await ah(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=Ht(t,"context");n==="direct"?(mh(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await gh(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Re(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function kh(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await oe(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Re(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
748
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=OS(Ht(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var dn,fn,mn,wh=v(()=>{"use strict";G();dn=new Map;fn="CodePipe Agent",mn="codepipe@codepartner.ee"});import{readFileSync as BS}from"node:fs";import{join as FS}from"node:path";function bh(t){let e=FS(t,mo),r;try{r=BS(e,"utf-8")}catch{throw new Wt(`BUILD produced no ${mo} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Wt(`${mo} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Wt(`${mo} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Wt(`${mo}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,f=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||f===null)return[];let m={name:d,exitCode:f};return typeof p.durationMs=="number"&&(m.durationMs=p.durationMs),[m]}),c=typeof o.logTail=="string"?GS(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 GS(t){let e=Buffer.from(t,"utf-8");return e.length<=Cc?t:`\u2026 [${e.length-Cc} bytes elided] \u2026
749
+ `+e.subarray(e.length-Cc).toString("utf-8")}var Cc,Wt,mo,$h=v(()=>{"use strict";Cc=8*1024,Wt=class extends Error{},mo="meta/build-result.json"});import{readFileSync as KS}from"node:fs";import{join as HS}from"node:path";function xh(t){let e=HS(t,gn),r;try{r=KS(e,"utf-8")}catch{throw new Et(`code review produced no ${gn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new Et(`${gn} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new Et(`${gn} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Et(`${gn}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?vh(o.remarks,WS):"";if(!i&&s.trim().length===0)throw new Et(`${gn}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?vh(o.summary,qS):"";return{approved:i,remarks:s,summary:a}}function vh(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
750
+ \u2026 [${r.length-e} bytes elided]`}var WS,qS,Et,gn,Sh=v(()=>{"use strict";WS=16*1024,qS=4*1024,Et=class extends Error{},gn="meta/review-result.json"});import{readFileSync as YS,statSync as VS}from"node:fs";import{join as Th}from"node:path";function tT(t){return t.startsWith("meta/")||eT.has(t)}function rT(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 nT(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Eh(t,e,r){let n=r?.maxBytes??zS,o=r?.totalBytes??JS,i=r?.maxCount??XS,s=e.map((m,g)=>{let y=null;try{y=VS(Th(t,m)).size}catch{}return{path:m,index:g,size:y}}),a=[...s].sort((m,g)=>{let y=w=>tT(w.path)?0:1;return y(m)!==y(g)?y(m)-y(g):(m.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((m,g)=>m.index-g.index).map(m=>m.path),u=new Array(s.length),p=[],d=0;for(let m of c){let g=null;if(m.size!==null&&m.size<=n&&d+m.size<=o)try{g=YS(Th(t,m.path))}catch{}if(g!==null){d+=g.length,u[m.index]={path:m.path,contentBase64:g.toString("base64")};continue}let y=m.size===null?nT(m.path):rT(m.path,m.size,n,o),w=Buffer.from(y,"utf-8");d+=w.length,u[m.index]={path:m.path,contentBase64:w.toString("base64")},p.push({path:m.path,bytes:m.size??0})}let f=u.filter(m=>m!==void 0);if(l.length>0){let m=l.slice(0,ZS),g=`# Artifacts omitted from upload
744
751
 
745
752
  ${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.
746
753
 
747
- `+f.map(k=>`- ${k}
748
- `).join("")+(l.length>f.length?`
749
- \u2026and ${l.length-f.length} more.
750
- `:"");m.push({path:US,contentBase64:Buffer.from(h,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var DS,LS,MS,US,BS,FS,gg=x(()=>{"use strict";DS=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),LS=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),MS=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),US="artifacts-omitted.md",BS=500,FS=new Set(["QUESTIONS.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as WS,mkdtempSync as YS,readFileSync as qS,readdirSync as kg,rmSync as yg}from"node:fs";import{tmpdir as VS}from"node:os";import{join as qi,relative as zS}from"node:path";function wg(t){let e=YS(qi(VS(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>yg(e,{recursive:!0,force:!0}),listFiles:()=>bg(e,e),readFile:r=>qS(qi(e,r),"utf-8"),clean:()=>{for(let r of kg(e))XS.has(r)||yg(qi(e,r),{recursive:!0,force:!0})}}}function bg(t,e){let r=[];for(let n of kg(e)){let o=qi(e,n),i=WS(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&JS.has(n))continue;r.push(...bg(t,o))}else r.push(zS(t,o))}return r}var JS,XS,$g=x(()=>{"use strict";JS=new Set(["code","context","scratch"]),XS=new Set(["code","context"])});import{existsSync as zi,readFileSync as vg,readdirSync as Sc}from"node:fs";import{join as Rt}from"node:path";import{parse as QS}from"yaml";function Ji(t){if(!zi(t))return[];let e=[];for(let r of Sc(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Rt(t,r.name);r.isDirectory()?e.push(...Ji(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Vi(t){try{return QS(vg(t,"utf-8"))}catch{return null}}function xg(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 Ji(Rt(t,"model/derived/structure"))){let s=Et(Vi(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[...Ji(Rt(t,"model/derived/correlates")),Rt(t,"model/derived/relates.yaml")]){if(!zi(i))continue;let s=Eo(Vi(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Rt(t,"model/facts/events");if(zi(n))for(let i of Sc(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Ct(Vi(Rt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=ke(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,ke(l),"references",1)}for(let i of Ji(Rt(t,"model/facts/identity"))){let s=Ao(Vi(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=Rt(t,"model/facts/annotations");if(zi(o)){for(let i of Sc(o).sort())if(i.endsWith(".md"))try{let s=vg(Rt(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 Sg=x(()=>{"use strict";K()});function Rg(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function iT(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 Ig(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(ke(e)))&&s(ke(e),Tg);for(let m of`${r}
751
- ${n}`.match(oT)??[]){if(m===e)continue;let f=ke(m);(o.events.has(m)||o.adjacency.has(f))&&s(f,Tg)}let a=new Map;for(let m of o.nodes.keys()){let f=Q(m);if(f?.level!=="code")continue;let h=f.path.slice(f.path.lastIndexOf("/")+1);for(let k of[f.path,h])a.has(k)||a.set(k,[]),a.get(k).push(m)}let c=`${r}
752
- ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let m of c){let f=m.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!f||!f.includes("/")&&!f.includes("."))continue;let h=a.get(f)??[];h.length===1&&s(h[0],ZS)}let l=new Map,u=(m,f)=>{let h=m.toLowerCase();!h||h.length<4||l.set(h,l.has(h)&&l.get(h)!==f?null:f)};for(let m of o.nodes.keys()){let f=Q(m);if(!f)continue;let h=f.path.slice(f.path.lastIndexOf("/")+1);f.level==="code"&&u(h.replace(/\.[a-z0-9]+$/i,""),m),f.level==="component"&&u(h,m)}for(let m of`${r}
753
- ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let f=l.get(m.toLowerCase());f&&s(f,eT)}let p=Rg(`${r}
754
- ${n}`),d=[];for(let[m,f]of o.events){if(m===e||!f.title)continue;let h=iT(p,Rg(f.title));h>=rT&&d.push({key:ke(m),score:h})}return d.sort((m,f)=>f.score-m.score||(m.key<f.key?-1:1)).slice(0,nT).forEach(m=>s(m.key,tT)),i}var Tg,ZS,eT,tT,rT,nT,oT,Eg=x(()=>{"use strict";K();Tg=1,ZS=.9,eT=.7,tT=.5,rT=.15,nT=3,oT=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function Cg(t,e,r={}){let n=r.cutoff??Pr.activationCutoff,o=r.topK??Pr.topKPerNode,i=r.nodeCap??Pr.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=wl[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 Ag=x(()=>{"use strict";K()});import{existsSync as Pg,readFileSync as _g,readdirSync as sT}from"node:fs";import{join as Rc}from"node:path";function Tc(t){return Math.ceil(t.length/4)}function Xi(t,e){return[...t.entries()].filter(([r])=>e(r)).map(([r,n])=>({key:r,activation:n.activation,via:n.via})).sort((r,n)=>n.activation-r.activation||(r.key<n.key?-1:1))}function Yt(t){let e=Q(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function Qi(t){if(!t.via)return"matched from the task text";let e=Yt(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 uT(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=Rc(t,"adr");if(!Pg(n))return null;let o=r.padStart(4,"0");for(let i of sT(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:_g(Rc(n,i),"utf-8").trim()}}catch{return null}return null}function jg(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??Pr.budgetTokens,a=[],c=0,l=S=>{let b=Tc(S);return c+b>s?!1:(a.push(S),c+=b,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
755
- `));let u=Xi(i,S=>S.startsWith("adr::")),p=!1;for(let S of u){let b=uT(n,Yt(S.key));if(!b)continue;let I=`${p?"":`
754
+ `+m.map(y=>`- ${y}
755
+ `).join("")+(l.length>m.length?`
756
+ \u2026and ${l.length-m.length} more.
757
+ `:"");f.push({path:QS,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:f,omitted:p,dropped:l}}var zS,JS,XS,QS,ZS,eT,Rh=v(()=>{"use strict";zS=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),JS=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),XS=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),QS="artifacts-omitted.md",ZS=500,eT=new Set(["QUESTIONS.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as oT,mkdtempSync as iT,readFileSync as sT,readdirSync as Ch,rmSync as Ih}from"node:fs";import{tmpdir as aT}from"node:os";import{join as Xi,relative as cT}from"node:path";function Ah(t){let e=iT(Xi(aT(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Ih(e,{recursive:!0,force:!0}),listFiles:()=>Ph(e,e),readFile:r=>sT(Xi(e,r),"utf-8"),clean:()=>{for(let r of Ch(e))uT.has(r)||Ih(Xi(e,r),{recursive:!0,force:!0})}}}function Ph(t,e){let r=[];for(let n of Ch(e)){let o=Xi(e,n),i=oT(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&lT.has(n))continue;r.push(...Ph(t,o))}else r.push(cT(t,o))}return r}var lT,uT,_h=v(()=>{"use strict";lT=new Set(["code","context","scratch"]),uT=new Set(["code","context"])});import{existsSync as Zi,readFileSync as jh,readdirSync as Ac}from"node:fs";import{join as Rt}from"node:path";import{parse as dT}from"yaml";function es(t){if(!Zi(t))return[];let e=[];for(let r of Ac(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Rt(t,r.name);r.isDirectory()?e.push(...es(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Qi(t){try{return dT(jh(t,"utf-8"))}catch{return null}}function Nh(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 es(Rt(t,"model/derived/structure"))){let s=It(Qi(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[...es(Rt(t,"model/derived/correlates")),Rt(t,"model/derived/relates.yaml")]){if(!Zi(i))continue;let s=Ao(Qi(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Rt(t,"model/facts/events");if(Zi(n))for(let i of Ac(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Ct(Qi(Rt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=be(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,be(l),"references",1)}for(let i of es(Rt(t,"model/facts/identity"))){let s=_o(Qi(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=Rt(t,"model/facts/annotations");if(Zi(o)){for(let i of Ac(o).sort())if(i.endsWith(".md"))try{let s=jh(Rt(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 Oh=v(()=>{"use strict";G()});function Lh(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function kT(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 Mh(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(f,m)=>{(i.get(f)??0)<m&&i.set(f,m)};(o.events.has(e)||o.adjacency.has(be(e)))&&s(be(e),Dh);for(let f of`${r}
758
+ ${n}`.match(yT)??[]){if(f===e)continue;let m=be(f);(o.events.has(f)||o.adjacency.has(m))&&s(m,Dh)}let a=new Map;for(let f of o.nodes.keys()){let m=Q(f);if(m?.level!=="code")continue;let g=m.path.slice(m.path.lastIndexOf("/")+1);for(let y of[m.path,g])a.has(y)||a.set(y,[]),a.get(y).push(f)}let c=`${r}
759
+ ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let f of c){let m=f.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!m||!m.includes("/")&&!m.includes("."))continue;let g=a.get(m)??[];g.length===1&&s(g[0],pT)}let l=new Map,u=(f,m)=>{let g=f.toLowerCase();!g||g.length<4||l.set(g,l.has(g)&&l.get(g)!==m?null:m)};for(let f of o.nodes.keys()){let m=Q(f);if(!m)continue;let g=m.path.slice(m.path.lastIndexOf("/")+1);m.level==="code"&&u(g.replace(/\.[a-z0-9]+$/i,""),f),m.level==="component"&&u(g,f)}for(let f of`${r}
760
+ ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let m=l.get(f.toLowerCase());m&&s(m,fT)}let p=Lh(`${r}
761
+ ${n}`),d=[];for(let[f,m]of o.events){if(f===e||!m.title)continue;let g=kT(p,Lh(m.title));g>=gT&&d.push({key:be(f),score:g})}return d.sort((f,m)=>m.score-f.score||(f.key<m.key?-1:1)).slice(0,hT).forEach(f=>s(f.key,mT)),i}var Dh,pT,fT,mT,gT,hT,yT,Uh=v(()=>{"use strict";G();Dh=1,pT=.9,fT=.7,mT=.5,gT=.15,hT=3,yT=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function Bh(t,e,r={}){let n=r.cutoff??_r.activationCutoff,o=r.topK??_r.topKPerNode,i=r.nodeCap??_r.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=Tl[p.kind]??.3,f=l.activation*d*Math.min(p.weight,1);if(f<n)continue;let m=s.get(p.to);(!m||m.activation<f)&&(s.set(p.to,{activation:f,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:f}))}}return s}var Fh=v(()=>{"use strict";G()});import{existsSync as Gh,readFileSync as Kh,readdirSync as wT}from"node:fs";import{join as _c}from"node:path";function Pc(t){return Math.ceil(t.length/4)}function ts(t,e){return[...t.entries()].filter(([r])=>e(r)).map(([r,n])=>({key:r,activation:n.activation,via:n.via})).sort((r,n)=>n.activation-r.activation||(r.key<n.key?-1:1))}function qt(t){let e=Q(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function rs(t){if(!t.via)return"matched from the task text";let e=qt(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 xT(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=_c(t,"adr");if(!Gh(n))return null;let o=r.padStart(4,"0");for(let i of wT(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:Kh(_c(n,i),"utf-8").trim()}}catch{return null}return null}function Hh(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??_r.budgetTokens,a=[],c=0,l=S=>{let b=Pc(S);return c+b>s?!1:(a.push(S),c+=b,!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(`
762
+ `));let u=ts(i,S=>S.startsWith("adr::")),p=!1;for(let S of u){let b=xT(n,qt(S.key));if(!b)continue;let E=`${p?"":`
756
763
  ## Governing decisions
757
764
  `}
758
- ### ${Yt(S.key)} (\`${b.file}\`, ${Qi(S)})
765
+ ### ${qt(S.key)} (\`${b.file}\`, ${rs(S)})
759
766
 
760
767
  ${b.content}
761
- `;if(!l(I))break;p=!0}let d=Xi(i,S=>o.nodes.get(S)?.entityId!==void 0).filter(S=>o.annotations.has(o.nodes.get(S.key).entityId)),m=t.staleKeys??new Set,f=!1;for(let S of d){let b=o.nodes.get(S.key).entityId,I=o.annotations.get(b),M=m.has(S.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(b)?" \u2014 \u26A0 the file no longer exists":"",G=`${f?"":`
768
+ `;if(!l(E))break;p=!0}let d=ts(i,S=>o.nodes.get(S)?.entityId!==void 0).filter(S=>o.annotations.has(o.nodes.get(S.key).entityId)),f=t.staleKeys??new Set,m=!1;for(let S of d){let b=o.nodes.get(S.key).entityId,E=o.annotations.get(b),O=f.has(S.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(b)?" \u2014 \u26A0 the file no longer exists":"",B=`${m?"":`
762
769
  ## Why the code is shaped this way (intent notes)
763
770
  `}
764
- ### \`${Yt(S.key)}\`${M}
771
+ ### \`${qt(S.key)}\`${O}
765
772
 
766
- ${I}
767
- `;if(!l(G))break;f=!0}let h=ke(e),k=Xi(i,S=>S.startsWith("task::")&&S!==h).slice(0,aT),y=!1;for(let S of k){let b=o.events.get(Yt(S.key));if(!b)continue;let I=[...b.files].filter(N=>!m.has(N.key)&&(!N.entityId||!o.orphanedEntities.has(N.entityId))).sort((N,_)=>(_.churn??0)-(N.churn??0)||(N.key<_.key?-1:1)).slice(0,3).map(N=>`\`${Yt(N.key)}\``).join(", "),M="",G=b.links?.solution??`tasks/${b.taskKey}/SOLUTION.md`,E=Rc(n,G);if(Pg(E))try{M=`
768
- > ${_g(E,"utf-8").trim().slice(0,lT).replace(/\n+/g," ").trim()}\u2026
769
- > _(full text: \`${G}\`)_`}catch{}let w=`${y?"":`
773
+ ${E}
774
+ `;if(!l(B))break;m=!0}let g=be(e),y=ts(i,S=>S.startsWith("task::")&&S!==g).slice(0,bT),w=!1;for(let S of y){let b=o.events.get(qt(S.key));if(!b)continue;let E=[...b.files].filter(D=>!f.has(D.key)&&(!D.entityId||!o.orphanedEntities.has(D.entityId))).sort((D,j)=>(j.churn??0)-(D.churn??0)||(D.key<j.key?-1:1)).slice(0,3).map(D=>`\`${qt(D.key)}\``).join(", "),O="",B=b.links?.solution??`tasks/${b.taskKey}/SOLUTION.md`,A=_c(n,B);if(Gh(A))try{O=`
775
+ > ${Kh(A,"utf-8").trim().slice(0,vT).replace(/\n+/g," ").trim()}\u2026
776
+ > _(full text: \`${B}\`)_`}catch{}let k=`${w?"":`
770
777
  ## Related past tasks
771
778
  `}
772
- - **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${Qi(S)}. Files: ${I||"\u2014"}.${M}`;if(!l(w))break;y=!0}let g=S=>{if(m.has(S.key))return!1;let b=o.nodes.get(S.key)?.entityId;return!b||!o.orphanedEntities.has(b)},$=Xi(i,S=>S.startsWith("code:")),T=$.filter(g).slice(0,cT);if(T.length>0){let S=["","## Files likely involved",""];for(let b of T){let I=`- \`${Yt(b.key)}\` \u2014 ${Qi(b)}`;if(c+Tc(S.join(`
773
- `))+Tc(I)>s)break;S.push(I)}S.length>3&&l(S.join(`
774
- `))}let C=$.filter(S=>!g(S)).slice(0,10);if(C.length>0){let S=["","## 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(b=>`- \`${Yt(b.key)}\` \u2014 ${Qi(b)}${m.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l(S.join(`
779
+ - **${b.taskKey}**${b.title?` \u2014 ${b.title}`:""}${b.date?` (${b.date})`:""}, ${rs(S)}. Files: ${E||"\u2014"}.${O}`;if(!l(k))break;w=!0}let h=S=>{if(f.has(S.key))return!1;let b=o.nodes.get(S.key)?.entityId;return!b||!o.orphanedEntities.has(b)},$=ts(i,S=>S.startsWith("code:")),x=$.filter(h).slice(0,$T);if(x.length>0){let S=["","## Files likely involved",""];for(let b of x){let E=`- \`${qt(b.key)}\` \u2014 ${rs(b)}`;if(c+Pc(S.join(`
780
+ `))+Pc(E)>s)break;S.push(E)}S.length>3&&l(S.join(`
781
+ `))}let R=$.filter(S=>!h(S)).slice(0,10);if(R.length>0){let S=["","## 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.","",...R.map(b=>`- \`${qt(b.key)}\` \u2014 ${rs(b)}${f.has(b.key)?" (changed since the map was built)":" (file gone)"}`)];l(S.join(`
775
782
  `))}return a.length<=1?null:a.join(`
776
783
  `)+`
777
- `}var aT,cT,lT,Ng=x(()=>{"use strict";K();aT=5,cT=300,lT=400});var Mg={};Rr(Mg,{assembleContextPack:()=>mT});import{createHash as dT}from"node:crypto";import{existsSync as Og,readFileSync as Dg}from"node:fs";import{join as Lg}from"node:path";function pT(t){return dT("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function fT(t,e,r){let n=new Set;for(let o of e.keys()){let i=Q(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=Lg(a,i.path);try{if(!Og(c)){n.add(o);continue}pT(Dg(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function mT(t){let e=xg(t.contextDir);if(e.empty)return null;let r="",n=Lg(t.contextDir,`tasks/${t.taskKey}/task.md`);if(Og(n))try{r=Dg(n,"utf-8")}catch{r=""}let o=Ig({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=Cg(e,o),s=t.repoDirs?fT(e,i,t.repoDirs):new Set;return jg({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var Ug=x(()=>{"use strict";K();Sg();Eg();Ag();Ng()});import{mkdirSync as Bg,readFileSync as Fg,readdirSync as hT,writeFileSync as Kg}from"node:fs";import{homedir as gT}from"node:os";import{dirname as yT,join as qt}from"node:path";function wT(t){let e=Buffer.from(t,"utf-8");if(e.length<=Zi)return t;let r=Math.floor(Zi/4),n=Zi-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}
784
+ `}var bT,$T,vT,Wh=v(()=>{"use strict";G();bT=5,$T=300,vT=400});var zh={};Rr(zh,{assembleContextPack:()=>RT});import{createHash as ST}from"node:crypto";import{existsSync as qh,readFileSync as Yh}from"node:fs";import{join as Vh}from"node:path";function TT(t){return ST("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function ET(t,e,r){let n=new Set;for(let o of e.keys()){let i=Q(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=Vh(a,i.path);try{if(!qh(c)){n.add(o);continue}TT(Yh(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function RT(t){let e=Nh(t.contextDir);if(e.empty)return null;let r="",n=Vh(t.contextDir,`tasks/${t.taskKey}/task.md`);if(qh(n))try{r=Yh(n,"utf-8")}catch{r=""}let o=Mh({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=Bh(e,o),s=t.repoDirs?ET(e,i,t.repoDirs):new Set;return Hh({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}})}var Jh=v(()=>{"use strict";G();Oh();Uh();Fh();Wh()});import{mkdirSync as Xh,readFileSync as Qh,readdirSync as IT,writeFileSync as Zh}from"node:fs";import{homedir as CT}from"node:os";import{dirname as AT,join as Yt}from"node:path";function _T(t){let e=Buffer.from(t,"utf-8");if(e.length<=ns)return t;let r=Math.floor(ns/4),n=ns-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}
778
785
 
779
- \u2026 [${s} bytes elided \u2014 log capped at ${Zi} bytes for upload] \u2026
786
+ \u2026 [${s} bytes elided \u2014 log capped at ${ns} bytes for upload] \u2026
780
787
 
781
- ${i}`}function bT(){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 fo(t={}){Ki();let e=Ie(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=$h(t.profile,e.sandboxId,!!Y("SANDBOX_CONFIG")),s=qt(gT(),".codepipe","logs"),a=Ko("SANDBOX_LOG",i,s);if(a.enabled){let E=new Ur(a);Go(E),console.log(`[log] file logging \u2192 ${E.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ue} (protocol ${at})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=jh(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=Mh();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new on(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,h=null,k=!1,y=()=>{let E=u.openControlSocket();return f=E,E.on("open",()=>{console.log("[ws] connected");let w={type:"sandbox_hello",platformVersion:Ue,protocolVersion:at};E.send(JSON.stringify(w))}),E.on("message",w=>{let N=w.toString("utf-8"),_=null;try{let B=JSON.parse(N);B&&typeof B=="object"&&(_=B)}catch{}if(_&&_.type==="hello"){let B=_;h=To(B.protocolVersion);let V=h?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${B.platformVersion} (protocol ${B.protocolVersion}) \u2014 ${V}`),h&&(k=!1);return}if(_&&_.type==="pause_job"){let B=typeof _.jobId=="string"?_.jobId:"",V=B?m.get(B):void 0;V?(console.warn(`[ws] pause_job ${B} \u2014 aborting agent`),V.paused=!0,V.abort.abort()):console.log(`[ws] pause_job ${B} \u2014 not a running job, ignoring`),B&&E.send(JSON.stringify({type:"job_paused",jobId:B}));return}if(_&&(_.type==="chat_user_message"||_.type==="chat_finalize")){let B=typeof _.jobId=="string"?_.jobId:"",V=B?m.get(B):void 0;if(V?.chatInbox)if(_.type==="chat_user_message"){let ee=typeof _.text=="string"?_.text:"";ee.trim()&&V.chatInbox.push({kind:"user",text:ee})}else V.chatInbox.finalize();else console.log(`[ws] ${String(_.type)} ${B} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${N}`)}),E.on("close",(w,N)=>{console.log(`[ws] closed code=${w} reason=${N?.toString()||""}`),f===E&&(f=null),!p&&setTimeout(y,2e3)}),E.on("error",w=>console.warn(`[ws] error: ${w.message}`)),E},g=y(),$=async E=>{for(;!p;){if(h===!1){k||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ue}, protocol ${at}) \u2014 not claiming jobs until versions align.`),k=!0),await new Promise(w=>setTimeout(w,5e3));continue}try{let w=await u.claim(d.signal,E);if(w.status===204)continue;if(w.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(!w.ok){console.warn(`[claim:${E}] ${w.status} \u2014 backoff 5s`),await new Promise(_=>setTimeout(_,5e3));continue}let N=await w.json();await T(u,N)}catch(w){if(d.signal.aborted)break;let N=w instanceof Error?w.message:String(w);console.warn(`[claim:${E}] error: ${N} \u2014 backoff 5s`),await new Promise(_=>setTimeout(_,5e3))}}};async function T(E,w){let N={abort:new AbortController,paused:!1};w.role==="chat"&&(N.chatInbox=bT()),m.set(w.jobId,N);let _=!1,B=null,V=null,ee=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),Le=async()=>{try{await E.heartbeat(w.jobId)==="claim_lost"&&(_=!0,console.warn(`[job] ${w.jobId} claim lost \u2014 HUB sweeper took it`))}catch(J){let Z=J instanceof Error?J.message:String(J);console.warn(`[job] ${w.jobId} heartbeat error: ${Z}`)}};Le();let Me=setInterval(()=>{Le()},ee),P=new Date().toISOString();console.log(`[job] ${w.jobId} claimed \u2014 role=${w.role} task=${w.taskId} phase=${w.phase}`),console.log(`[job] ${w.jobId} prompt (${w.prompt.length} chars):`),console.log(S(w.prompt," \u2502 "));let L=[],j=null,q=400,D=25,R=500,v=()=>{if(j&&(clearTimeout(j),j=null),L.length===0)return;let J=L.splice(0,L.length),Z=f;if(!Z||Z.readyState!==Z.OPEN)return;let kt={type:"agent_activity",jobId:w.jobId,taskId:w.taskId,projectId:w.projectId,role:w.role,phase:w.phase,events:J};try{Z.send(JSON.stringify(kt))}catch{}},O=J=>{L.push(J),L.length>R&&L.shift(),L.length>=D?v():j||(j=setTimeout(v,q))},X=w.role==="analysis"&&w.taskId.startsWith("draft::")?w.taskId.slice(7):null,ve=new Set,Ye=null;try{if(!c){_||await E.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:P,finishedAt:new Date().toISOString()});return}if(!Nh(o,w.provider??null)){_||await E.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${w.provider??"claude"}"`},startedAt:P,finishedAt:new Date().toISOString()});return}let J=wg(w.jobId);console.log(`[job] ${w.jobId} workspace=${J.dir}`);let Z=C(w,r);B=Z.gitCreds,V=Z.contextGitCreds;let kt=B?.env,Xc=Z.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Z.claudeOauthToken}:void 0,it=[],er=null,ds=null;try{let U=w.role==="build"?"clone":"worktree";it=await ig(J.dir,w.projectId,w.projectRepos,U,kt,n);let F=await sg(J.dir,w.projectId,w.contextRepo,"worktree",kt,n);ds=F,er=F?.workspacePath??null}catch(U){let F=U instanceof Error?U.message:String(U);console.warn(`[job] ${w.jobId} materialize failed: ${F}`),_||await E.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${F}`},startedAt:P,finishedAt:new Date().toISOString()}),J.dispose();return}let Qc=async()=>{if(!w.deliveries||w.deliveries.length===0)return[];let U=w.contextRepo?.cloneUrl;if(!U||!kt)throw new Error(U?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let F=[];for(let te of w.deliveries){let re=it.find(ge=>ge.name===te.name);if(re){if(w.role==="implement"&&te.baseSha&&te.baseSha!==re.baseSha){let ge=await rg(re,te.deliveryRef,te.deliverySha,te.baseSha,U,kt);console.log(`[job] ${w.jobId} ${re.name}: base moved ${te.baseSha.slice(0,10)} \u2192 ${re.baseSha.slice(0,10)} \u2014 re-applied delivery ${te.deliverySha.slice(0,10)} (${ge.length} conflicted file(s))`),ge.length>0&&F.push(`- **${re.name}**:`,...ge.map(In=>` - \`${In}\``));continue}await tg(re,te.deliveryRef,te.deliverySha,U,kt),console.log(`[job] ${w.jobId} ${re.name}: checked out delivery ${te.deliverySha.slice(0,10)} for ${w.role}`)}}return F},ps=[];if(w.role==="build"||w.role==="implement"||w.role==="code-review")try{ps=await Qc()}catch(U){let F=U instanceof Error?U.message:String(U);console.warn(`[job] ${w.jobId} delivery checkout failed: ${F}`),_||await E.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${F}`},startedAt:P,finishedAt:new Date().toISOString()}),J.dispose();return}let fs=w.role==="resolve-conflict"?w.metadata?.taskBranchByRepo??{}:{},Zc="";if(w.role==="resolve-conflict"){if(!it.some(U=>fs[U.name])){let U="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${w.jobId} ${U}`),_||await E.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:U},startedAt:P,finishedAt:new Date().toISOString()}),J.dispose();return}try{let U=[];for(let F of it){let te=fs[F.name];if(!te)continue;let re=await vc(F,te,kt);console.log(`[job] ${w.jobId} ${F.name}: merged ${te} into ${F.ref} \u2014 ${re.length} conflicted file(s)`),re.length>0?U.push(`- **${F.name}**:`,...re.map(ge=>` - \`${ge}\``)):U.push(`- **${F.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Zc=`
788
+ ${i}`}function jT(){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 go(t={}){Wi();let e=Ce(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=Cg(t.profile,e.sandboxId,!!z("SANDBOX_CONFIG")),s=Yt(CT(),".codepipe","logs"),a=Wo("SANDBOX_LOG",i,s);if(a.enabled){let A=new Br(a);qo(A),console.log(`[log] file logging \u2192 ${A.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ue} (protocol ${lt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Hg(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=zg();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new sn(e.hubUrl,e.token),p=!1,d=new AbortController,f=new Map,m=null,g=null,y=!1,w=()=>{let A=u.openControlSocket();return m=A,A.on("open",()=>{console.log("[ws] connected");let k={type:"sandbox_hello",platformVersion:Ue,protocolVersion:lt};A.send(JSON.stringify(k))}),A.on("message",k=>{let D=k.toString("utf-8"),j=null;try{let K=JSON.parse(D);K&&typeof K=="object"&&(j=K)}catch{}if(j&&j.type==="hello"){let K=j;g=Ro(K.protocolVersion);let V=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${K.platformVersion} (protocol ${K.protocolVersion}) \u2014 ${V}`),g&&(y=!1);return}if(j&&j.type==="pause_job"){let K=typeof j.jobId=="string"?j.jobId:"",V=K?f.get(K):void 0;V?(console.warn(`[ws] pause_job ${K} \u2014 aborting agent`),V.paused=!0,V.abort.abort()):console.log(`[ws] pause_job ${K} \u2014 not a running job, ignoring`),K&&A.send(JSON.stringify({type:"job_paused",jobId:K}));return}if(j&&(j.type==="chat_user_message"||j.type==="chat_finalize")){let K=typeof j.jobId=="string"?j.jobId:"",V=K?f.get(K):void 0;if(V?.chatInbox)if(j.type==="chat_user_message"){let ee=typeof j.text=="string"?j.text:"";ee.trim()&&V.chatInbox.push({kind:"user",text:ee})}else V.chatInbox.finalize();else console.log(`[ws] ${String(j.type)} ${K} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${D}`)}),A.on("close",(k,D)=>{console.log(`[ws] closed code=${k} reason=${D?.toString()||""}`),m===A&&(m=null),!p&&setTimeout(w,2e3)}),A.on("error",k=>console.warn(`[ws] error: ${k.message}`)),A},h=w(),$=async A=>{for(;!p;){if(g===!1){y||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ue}, protocol ${lt}) \u2014 not claiming jobs until versions align.`),y=!0),await new Promise(k=>setTimeout(k,5e3));continue}try{let k=await u.claim(d.signal,A);if(k.status===204)continue;if(k.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(!k.ok){console.warn(`[claim:${A}] ${k.status} \u2014 backoff 5s`),await new Promise(j=>setTimeout(j,5e3));continue}let D=await k.json();await x(u,D)}catch(k){if(d.signal.aborted)break;let D=k instanceof Error?k.message:String(k);console.warn(`[claim:${A}] error: ${D} \u2014 backoff 5s`),await new Promise(j=>setTimeout(j,5e3))}}};async function x(A,k){let D={abort:new AbortController,paused:!1};k.role==="chat"&&(D.chatInbox=jT()),f.set(k.jobId,D);let j=!1,K=null,V=null,ee=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),qe=async()=>{try{await A.heartbeat(k.jobId)==="claim_lost"&&(j=!0,console.warn(`[job] ${k.jobId} claim lost \u2014 HUB sweeper took it`))}catch(X){let ue=X instanceof Error?X.message:String(X);console.warn(`[job] ${k.jobId} heartbeat error: ${ue}`)}};qe();let st=setInterval(()=>{qe()},ee),_=new Date().toISOString();console.log(`[job] ${k.jobId} claimed \u2014 role=${k.role} task=${k.taskId} phase=${k.phase}`),console.log(`[job] ${k.jobId} prompt (${k.prompt.length} chars):`),console.log(S(k.prompt," \u2502 "));let L=[],N=null,q=400,M=25,T=500,C=()=>{if(N&&(clearTimeout(N),N=null),L.length===0)return;let X=L.splice(0,L.length),ue=m;if(!ue||ue.readyState!==ue.OPEN)return;let se={type:"agent_activity",jobId:k.jobId,taskId:k.taskId,projectId:k.projectId,role:k.role,phase:k.phase,events:X};try{ue.send(JSON.stringify(se))}catch{}},I=X=>{L.push(X),L.length>T&&L.shift(),L.length>=M?C():N||(N=setTimeout(C,q))},W=k.role==="analysis"&&k.taskId.startsWith("draft::")?k.taskId.slice(7):null,ye=new Set,Pe=null;try{if(!c){j||await A.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:_,finishedAt:new Date().toISOString()});return}if(!Wg(o,k.provider??null)){j||await A.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${k.provider??"claude"}"`},startedAt:_,finishedAt:new Date().toISOString()});return}let X=Ah(k.jobId);console.log(`[job] ${k.jobId} workspace=${X.dir}`);let ue=R(k,r);K=ue.gitCreds,V=ue.contextGitCreds;let se=K?.env,nl=ue.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ue.claudeOauthToken}:void 0,at=[],er=null,gs=null;try{let U=k.role==="build"?"clone":"worktree";at=await hh(X.dir,k.projectId,k.projectRepos,U,se,n);let F=await yh(X.dir,k.projectId,k.contextRepo,"worktree",se,n);gs=F,er=F?.workspacePath??null}catch(U){let F=U instanceof Error?U.message:String(U);console.warn(`[job] ${k.jobId} materialize failed: ${F}`),j||await A.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${F}`},startedAt:_,finishedAt:new Date().toISOString()}),X.dispose();return}let ol=async()=>{if(!k.deliveries||k.deliveries.length===0)return[];let U=k.contextRepo?.cloneUrl;if(!U||!se)throw new Error(U?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let F=[];for(let Z of k.deliveries){let te=at.find(ke=>ke.name===Z.name);if(te){if(k.role==="implement"&&Z.baseSha&&Z.baseSha!==te.baseSha){let ke=await fh(te,Z.deliveryRef,Z.deliverySha,Z.baseSha,U,se);console.log(`[job] ${k.jobId} ${te.name}: base moved ${Z.baseSha.slice(0,10)} \u2192 ${te.baseSha.slice(0,10)} \u2014 re-applied delivery ${Z.deliverySha.slice(0,10)} (${ke.length} conflicted file(s))`),ke.length>0&&F.push(`- **${te.name}**:`,...ke.map(In=>` - \`${In}\``));continue}await ph(te,Z.deliveryRef,Z.deliverySha,U,se),console.log(`[job] ${k.jobId} ${te.name}: checked out delivery ${Z.deliverySha.slice(0,10)} for ${k.role}`)}}return F},hs=[];if(k.role==="build"||k.role==="implement"||k.role==="code-review")try{hs=await ol()}catch(U){let F=U instanceof Error?U.message:String(U);console.warn(`[job] ${k.jobId} delivery checkout failed: ${F}`),j||await A.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${F}`},startedAt:_,finishedAt:new Date().toISOString()}),X.dispose();return}let ys=k.role==="resolve-conflict"?k.metadata?.taskBranchByRepo??{}:{},il="";if(k.role==="resolve-conflict"){if(!at.some(U=>ys[U.name])){let U="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${k.jobId} ${U}`),j||await A.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:U},startedAt:_,finishedAt:new Date().toISOString()}),X.dispose();return}try{let U=[];for(let F of at){let Z=ys[F.name];if(!Z)continue;let te=await Ic(F,Z,se);console.log(`[job] ${k.jobId} ${F.name}: merged ${Z} into ${F.ref} \u2014 ${te.length} conflicted file(s)`),te.length>0?U.push(`- **${F.name}**:`,...te.map(ke=>` - \`${ke}\``)):U.push(`- **${F.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}il=`
782
789
 
783
790
  ## Conflicts to resolve
784
791
 
785
792
  `+(U.length>0?U.join(`
786
793
  `):"(no task branches to merge)")+`
787
- `}catch(U){let F=U instanceof Error?U.message:String(U);console.warn(`[job] ${w.jobId} conflict merge failed: ${F}`),_||await E.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${F}`},startedAt:P,finishedAt:new Date().toISOString()}),J.dispose();return}}if(w.contextPack&&er)try{let{assembleContextPack:U}=await Promise.resolve().then(()=>(Ug(),Mg)),F=U({contextDir:er,taskKey:String(w.metadata?.trackerIssueKey??w.taskId.split(":")[1]??""),title:String(w.metadata?.taskTitle??""),repoDirs:new Map(it.map(te=>[te.name,te.workspacePath]))});F?(Bg(qt(J.dir,"meta"),{recursive:!0}),Kg(qt(J.dir,"meta","context-pack.md"),F),console.log(`[job] ${w.jobId} context pack: ${F.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${w.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(U){let F=U instanceof Error?U.message:String(U);console.warn(`[job] ${w.jobId} context pack failed (non-fatal): ${F}`)}let kk=ps.length>0?`
794
+ `}catch(U){let F=U instanceof Error?U.message:String(U);console.warn(`[job] ${k.jobId} conflict merge failed: ${F}`),j||await A.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${F}`},startedAt:_,finishedAt:new Date().toISOString()}),X.dispose();return}}if(k.contextPack&&er)try{let{assembleContextPack:U}=await Promise.resolve().then(()=>(Jh(),zh)),F=U({contextDir:er,taskKey:String(k.metadata?.trackerIssueKey??k.taskId.split(":")[1]??""),title:String(k.metadata?.taskTitle??""),repoDirs:new Map(at.map(Z=>[Z.name,Z.workspacePath]))});F?(Xh(Yt(X.dir,"meta"),{recursive:!0}),Zh(Yt(X.dir,"meta","context-pack.md"),F),console.log(`[job] ${k.jobId} context pack: ${F.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${k.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(U){let F=U instanceof Error?U.message:String(U);console.warn(`[job] ${k.jobId} context pack failed (non-fatal): ${F}`)}let Ck=hs.length>0?`
788
795
 
789
796
  ## Base branch moved \u2014 conflicts to resolve
790
797
 
791
798
  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:
792
799
 
793
- `+ps.join(`
800
+ `+hs.join(`
794
801
  `)+`
795
- `:"",wk=I(b(w.prompt,it,er),er,w.taskId)+Zc+kk,ms=[...it.map(U=>U.workspacePath),...er?[er]:[]];ms.length>0&&console.log(`[job] ${w.jobId} --add-dir: ${ms.join(", ")}`),X&&(Ye=setInterval(()=>{let F=f;if(!F||F.readyState!==F.OPEN)return;let te;try{te=hT(qt(J.dir,"drafts")).filter(re=>re.endsWith(".json")).sort()}catch{return}for(let re of te){if(ve.has(re))continue;if(ve.size>=pu)break;let ge;try{let qe=JSON.parse(Fg(qt(J.dir,"drafts",re),"utf-8")),Tr=typeof qe.localRef=="string"?qe.localRef:"",xo=typeof qe.title=="string"?qe.title:"",hs=typeof qe.body=="string"?qe.body:"";if(!Tr||!xo)continue;ge={localRef:Tr,title:xo,body:hs,...qe.isEpic===!0?{isEpic:!0}:{},...Array.isArray(qe.links)?{links:qe.links}:{}}}catch{continue}ve.add(re);let In={type:"child_draft",jobId:w.jobId,projectId:w.projectId,draftId:X,child:ge};try{F.send(JSON.stringify(In))}catch{}}},1500));try{let U={workspaceDir:J.dir,role:w.role,prompt:wk,addDirs:ms,metadata:w.metadata??{},...w.model?{model:w.model}:{},...Xc?{env:Xc}:{},signal:N.abort.signal,onActivity:O},F=N.chatInbox?await c.run({...U,interactive:{inbox:N.chatInbox.iterable}}):await Bh(c,U,{jobId:w.jobId,policy:l,onBeforeRetry:async()=>{J.clean();for(let ae of it)try{await Xh(ae);let ye=fs[ae.name];w.role==="resolve-conflict"&&ye&&await vc(ae,ye,kt)}catch(ye){let En=ye instanceof Error?ye.message:String(ye);console.warn(`[job] ${w.jobId} worktree reset failed (${ae.name}): ${En}`)}try{await Qc()}catch(ae){let ye=ae instanceof Error?ae.message:String(ae);console.warn(`[job] ${w.jobId} delivery re-checkout failed: ${ye}`)}},aborted:()=>_||N.paused}),te=[];if(kT.has(w.role)&&it.length>0){let ae=w.metadata??{},ye=typeof ae.commitMessage=="string"?ae.commitMessage:`${w.taskId}: changes`,En=w.contextRepo?.cloneUrl,tl=V?.env;if(!En||!tl)throw new Error("delivery requested but "+(En?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let bk=w.taskId.includes(":")?w.taskId.slice(w.taskId.indexOf(":")+1):w.taskId;for(let wt of it){let Cn=await Qh(wt,ye);if(!Cn){console.log(`[job] ${w.jobId} ${wt.name}: no changes \u2014 no delivery`);continue}let gs=`codepipe/deliveries/${bk}/${w.jobId}/${wt.name}`;await Zh(wt,Cn,gs,En,tl),te.push({name:wt.name,deliveryRef:gs,deliverySha:Cn,baseSha:wt.baseSha}),console.log(`[job] ${w.jobId} ${wt.name}: delivered ${Cn.slice(0,10)} \u2192 ${gs}`);let rl=await eg(wt,Cn);if(rl.trim().length>0){let $k=qt("display",`${wt.name}.diff`),nl=qt(J.dir,$k);Bg(yT(nl),{recursive:!0}),Kg(nl,rl)}}}if(w.role==="resolve-conflict"&&te.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let re;w.role==="build"&&(re=lg(J.dir),console.log(`[job] ${w.jobId} build verdict: ok=${re.ok}`+(re.failedStep?` failedStep=${re.failedStep}`:"")));let ge;w.role==="code-review"&&(ge=pg(J.dir),console.log(`[job] ${w.jobId} review verdict: approved=${ge.approved}`));let In=F.artifactPaths.length>0?F.artifactPaths:J.listFiles(),qe=Array.from(new Set(In)),Tr;if(ds)try{let ae=w.role==="index"?["adr/SOURCES.md"]:w.role==="backfill"?["adr"]:[],ye=await ag(ds,ae);ye.length>0&&(Tr=ye,console.log(`[job] ${w.jobId} captured ${ye.length} knowledge file(s) for Context Repo`))}catch(ae){let ye=ae instanceof Error?ae.message:String(ae);console.warn(`[job] ${w.jobId} knowledge capture failed (non-fatal): ${ye}`)}let{artifacts:xo,omitted:hs,dropped:el}=hg(J.dir,qe);for(let ae of hs)console.warn(`[job] ${w.jobId} artifact ${ae.path} (${ae.bytes} bytes) exceeded upload budget \u2014 content omitted`);el.length>0&&console.warn(`[job] ${w.jobId} artifact listing truncated: ${el.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let So={jobId:w.jobId,status:"succeeded",artifacts:xo,...Tr?{contextWrites:Tr}:{},...te.length>0?{deliveries:te}:{},log:wT(F.log),startedAt:P,finishedAt:new Date().toISOString(),usage:F.usage,...F.rateLimit?{rateLimit:F.rateLimit}:{},...re?{build:re}:{},...ge?{review:ge}:{}};if(_||N.paused)console.warn(`[job] ${w.jobId} skipping result upload \u2014 ${N.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await E.submitResult(So),console.log(`[job] ${w.jobId} done \u2014 uploaded ${So.artifacts.length} artifact(s):`);for(let ae of So.artifacts){let ye=Buffer.from(ae.contentBase64,"base64").length;console.log(` \xB7 ${ae.path} (${ye} bytes)`)}So.artifacts.length===0&&console.warn(`[job] ${w.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(U){let F=U instanceof Error?U.message:String(U);if(N.paused)console.log(`[job] ${w.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(_)console.warn(`[job] ${w.jobId} failed after claim lost (${F}) \u2014 skipping result upload`);else{let te=Uh(U),re=U instanceof Wt,ge=U instanceof Tt;console.warn(te?`[job] ${w.jobId} failed: ${F} (Claude auth \u2014 token invalid/expired)`:re?`[job] ${w.jobId} failed: ${F} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:ge?`[job] ${w.jobId} failed: ${F} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${w.jobId} failed: ${F}`),await E.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:F},startedAt:P,finishedAt:new Date().toISOString(),...te?{authError:!0}:{},...re?{buildInconclusive:!0}:{},...ge?{reviewInconclusive:!0}:{}})}}finally{J.dispose()}}finally{clearInterval(Me),Ye&&clearInterval(Ye),v(),N.chatInbox?.close(),m.delete(w.jobId),B?.cleanup(),V?.cleanup()}}function C(E,w){if(!E.credBundle)return{gitCreds:null,contextGitCreds:null};if(!w)return console.warn(`[job] ${E.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let N;try{N=JSON.parse(Vr(w,E.credBundle).toString("utf-8"))}catch(ee){return console.warn(`[job] ${E.jobId} failed to open credBundle: ${ee instanceof Error?ee.message:String(ee)}`),{gitCreds:null,contextGitCreds:null}}let _=bc(N);_&&console.log(`[job] ${E.jobId} cred bundle opened \u2014 git creds configured`);let B=Hh(N,E.contextRepo.cloneUrl),V={gitCreds:_,contextGitCreds:B};return N.claudeOauthToken&&(V.claudeOauthToken=N.claudeOauthToken),V}function S(E,w){return E.split(`
796
- `).map(N=>w+N).join(`
797
- `)}function b(E,w,N){let _=w[0]?.workspacePath??"";return E.replace(/\{\{codeDir\}\}/g,_).replace(/\{\{codeRoot\}\}/g,_?_.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,N??"")}function I(E,w,N){let _=E,B=N.includes("::")?"":N.split(":",2)[1]??"",V=ee=>{if(!w||!B)return"";try{return Fg(qt(w,"tasks",B,ee),"utf-8").trim()}catch{return""}};if(_.includes("{{solutionMd}}")){let ee=V("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";_=_.replace(/\{\{solutionMd\}\}/g,()=>ee)}if(_.includes("{{taskDescription}}")){let ee=V("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";_=_.replace(/\{\{taskDescription\}\}/g,()=>ee)}return _}let M=E=>{if(p)return;p=!0,console.log(`
798
- [${E}] shutting down`),d.abort();let w=[...m.keys()];for(let B of m.values())B.abort.abort();let N=new AbortController,_=setTimeout(()=>N.abort(),3e3);(async()=>(await Promise.all(w.map(async B=>{try{await u.releaseJob(B,`sandbox ${E}`,N.signal),console.log(`[${E}] released job ${B}`)}catch(V){let ee=V instanceof Error?V.message:String(V);console.warn(`[${E}] release failed: ${ee} (sweeper will reclaim)`)}})),clearTimeout(_),g.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>M("SIGINT")),process.on("SIGTERM",()=>M("SIGTERM"));let G=[$("implementation")];e.planningLane!==!1?G.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(G)}var Zi,kT,Gg=x(()=>{"use strict";K();He();Ds();Oh();Fh();Ae();Gi();Wh();hc();cg();ug();fg();gg();$g();Zi=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),kT=new Set(["implement","resolve-conflict"])});var hn=x(()=>{"use strict";xh();Gg();Gi()});import{cancel as $T,isCancel as Wg,log as ot,password as vT,text as xT}from"@clack/prompts";function ST(t){return Wg(t)&&($T("aborted"),process.exit(1)),typeof t=="string"?t:""}function TT(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function RT(t){let e=Vs({redirectUri:qs,challenge:t.challenge,state:t.state});ot.message(`Open this URL, approve the access, and paste the code shown:
799
- ${e}`);let r=await xT({message:"Authorization code \u2014 blank to skip"});if(Wg(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=Td(r,t.state);return await zs({code:n,verifier:t.verifier,state:t.state,redirectUri:qs})}catch(n){return ot.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function IT(t){if(Ns()?.claude?.oauthToken&&!t.farm)return ot.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN==="0"||!process.stdout.isTTY)return null;ot.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=Vo(),n;try{n=await Rd({...r,openUrl:cr,log:i=>ot.message(i)})}catch(i){ot.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await RT(r);if(s===null)return null;n=s}let o=await Mt(n.oauthToken);return o==="invalid"?(ot.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(ot.success(`Claude: logged in \u2014 ${TT(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function ET(t){ot.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t.farm?`
800
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=ST(await vT({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||ot.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),e):(ot.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}var Yg,qg=x(()=>{"use strict";zo();Fr();ue();Xs();Yg={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:IT,promptManual:ET,validate:Mt}});function Vg(t){return Yg}async function zg(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Jg=x(()=>{"use strict";qg()});async function yn(t,e,r){return e.host==="github"?AT(t,e,r):e.host==="gitlab"?LT(t,e,r):UT(t,e,r)}async function Xg(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 zt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Qg(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 Vt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Zg(e.gitlabToken,t):o}}return e.bitbucket?(await gn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await ey(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 Qg(t,e){let r=!1;try{r=(await zt(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 Zg(t,e){let r=!1;try{r=(await Vt(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 ey(t,e){let r=!1;try{r=(await gn(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 zt(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(CT+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 AT(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 PT(n,e,r),i=await jT(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=qr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await NT(n,o.owner,o.name,a.path,i)||await OT(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 PT(t,e,r){let n=await zt(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 Qg(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await _T(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 zt(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 _T(t,e){let{status:r,data:n}=await zt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function jT(t,e,r){let{data:n}=await zt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function NT(t,e,r,n,o){let{status:i,data:s}=await zt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function OT(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 zt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Vt(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(DT+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 LT(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 Vt(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 Zg(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Vt(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 Vt(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 Vt(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=qr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await Vt(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 Vt(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 gn(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(MT+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 UT(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 gn(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 ey(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 gn(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=qr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await gn(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 gn(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 CT,DT,MT,es=x(()=>{"use strict";yr();CT="https://api.github.com";DT="https://gitlab.com/api/v4";MT="https://api.bitbucket.org/2.0"});function We(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=BT[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 BT,ts=x(()=>{"use strict";BT={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as FT}from"node:crypto";import{existsSync as ty,mkdirSync as KT,readFileSync as ry,readdirSync as GT,rmSync as rs,writeFileSync as HT}from"node:fs";import{homedir as WT}from"node:os";import{dirname as YT,join as Ic}from"node:path";function ny(){return Ic(WT(),".codepipe","init-drafts")}function Ec(t){let e=FT("sha256").update(t).digest("hex").slice(0,16);return Ic(ny(),`${e}.json`)}function oy(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=qT)}function iy(t){let e=Ec(t);if(!ty(e))return null;try{let r=JSON.parse(ry(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:oy(r.savedAt)?(rs(e,{force:!0}),null):r}catch{return null}}function Cc(t){rs(Ec(t),{force:!0})}function sy(){let t=ny();if(ty(t))for(let e of GT(t)){let r=Ic(t,e);try{let n=JSON.parse(ry(r,"utf-8"));oy(n.savedAt)&&rs(r,{force:!0})}catch{rs(r,{force:!0})}}}var qT,kn,ay=x(()=>{"use strict";qT=24*60*60*1e3;kn=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(){Cc(this.cwd)}persist(){let e=Ec(this.cwd);KT(YT(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};HT(e,JSON.stringify(r,null,2)+`
801
- `,{mode:384})}}});function cy(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 ly(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 uy=x(()=>{"use strict"});import{existsSync as VT}from"node:fs";import{join as zT}from"node:path";import{simpleGit as JT}from"simple-git";function eR(t){let e=t.split("/");return e[e.length-1]??t}function dy(t){if(t.filter(r=>!QT.test(eR(r))).length>XT)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(ZT.has(n))return!0}return!1}async function tR(t){try{let r=(await JT(t).raw(["ls-files"])).split(`
802
- `).map(n=>n.trim()).filter(Boolean);return dy(r)}catch{return!1}}async function rR(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)?dy(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function py(t,e){for(let r of t)try{let n=e.localRoot!=null?zT(e.localRoot,r.mountAs??r.name):null;if(n&&VT(n)?await tR(n):await rR(r,e.tokens))return!0}catch{}return!1}var XT,QT,ZT,fy=x(()=>{"use strict";XT=3,QT=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,ZT=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as my}from"node:fs";import{join as hy}from"node:path";import{simpleGit as gy}from"simple-git";async function ho(t,e,r={}){let n=r.log??nR,o=[];for(let i of e){let s=hy(t,i.mountAs),a=gu(i);if(!my(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 gy().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=mo(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(!my(hy(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=gy(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!oR(l,a)){n.warn(`${i.mountAs}/ origin (${mo(l)||"none"}) != expected (${mo(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:mo(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=mo(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 oR(t,e){return yy(t)===yy(e)}function yy(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function mo(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function ky(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 ho(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 nR,ns=x(()=>{"use strict";pt();nR={info:t=>console.log(t),warn:t=>console.warn(t)}});import{spawn as by}from"node:child_process";import{existsSync as wy}from"node:fs";import{homedir as iR,hostname as sR}from"node:os";import{join as os}from"node:path";async function aR(t,e,r){let n=Ie(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${nt(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 Od(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 ${nt(e)} still holds its token.
803
- Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${n.sandboxId} \u2014 replacing the registration`),Nu(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function cR(t,e,r){let n=Ie(e)!==null;if(!await aR(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 Qo(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof H&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof H&&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 H?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 br({hub:t.hubUrl,token:o,name:r.name??`${sR()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function lR(t,e){let r=Ie(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=Pe(r.sealPublicKey);if(!W(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Bo(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 Ac(t,e,r){await cR(t,e,r),lR(t.projectId,e)}function uR(t){return[...t?["--profile",t]:[],"worker","start"]}function dR(t){let e={...t};for(let r of Os)delete e[r];return e}function Pc(t){let e=by(process.execPath,[t.entry,...uR(t.profile)],{stdio:["ignore","pipe","pipe"],env:dR(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
804
- `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function pR(t,e){let r=process.cwd(),n=os(r,dt);if(Lo(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(wy(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 oe(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 Nc(r);if(!hu(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=W(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Fi({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=os(iR(),".codepipe",e?os("profiles",e,"context-config"):"context-config");if(si(c.contextDir,l,a),!wy(os(c.contextDir,"project.yaml"))){Wr(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Wn(c.contextDir,ht(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 _c(t){let{cfg:e,profile:r}=Uo(t.profile);await pR(e,r),await Ac(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 h=k=>y=>{for(let g of y.toString("utf-8").split(`
805
- `))g.length>0&&k.write(`${f} ${g}
806
- `)};m.stdout?.on("data",h(process.stdout)),m.stderr?.on("data",h(process.stderr))},i=(m,f)=>{let h=by(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(h,m),h};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Pc({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
807
- `)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=m=>{if(!l){l=!0,console.log(`
808
- [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:h}of c)h.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),h.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(h=>{f.on("exit",(k,y)=>h({name:m,code:k??(y?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 jc=x(()=>{"use strict";He();hn();Oe();vt();pc();yr();xe();ue();pt();go()});var Cy={};Rr(Cy,{replCommand:()=>Mc});import{existsSync as Ry,mkdirSync as fR,readFileSync as mR,writeFileSync as hR}from"node:fs";import{homedir as gR}from"node:os";import{dirname as yR,join as Iy}from"node:path";import*as wn from"node:readline";async function Mc(t={}){let e=$e();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=W(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)),Ln(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let n=hr(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
802
+ `:"",Ak=E(b(k.prompt,at,er),er,k.taskId)+il+Ck,ks=[...at.map(U=>U.workspacePath),...er?[er]:[]];ks.length>0&&console.log(`[job] ${k.jobId} --add-dir: ${ks.join(", ")}`),W&&(Pe=setInterval(()=>{let F=m;if(!F||F.readyState!==F.OPEN)return;let Z;try{Z=IT(Yt(X.dir,"drafts")).filter(te=>te.endsWith(".json")).sort()}catch{return}for(let te of Z){if(ye.has(te))continue;if(ye.size>=wu)break;let ke;try{let Ye=JSON.parse(Qh(Yt(X.dir,"drafts",te),"utf-8")),Er=typeof Ye.localRef=="string"?Ye.localRef:"",To=typeof Ye.title=="string"?Ye.title:"",ws=typeof Ye.body=="string"?Ye.body:"";if(!Er||!To)continue;ke={localRef:Er,title:To,body:ws,...Ye.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Ye.links)?{links:Ye.links}:{}}}catch{continue}ye.add(te);let In={type:"child_draft",jobId:k.jobId,projectId:k.projectId,draftId:W,child:ke};try{F.send(JSON.stringify(In))}catch{}}},1500));try{let U={workspaceDir:X.dir,role:k.role,prompt:Ak,addDirs:ks,metadata:k.metadata??{},...k.model?{model:k.model}:{},...nl?{env:nl}:{},signal:D.abort.signal,onActivity:I},F=D.chatInbox?await c.run({...U,interactive:{inbox:D.chatInbox.iterable}}):await Xg(c,U,{jobId:k.jobId,policy:l,onBeforeRetry:async()=>{X.clean();for(let ae of at)try{await ch(ae);let we=ys[ae.name];k.role==="resolve-conflict"&&we&&await Ic(ae,we,se)}catch(we){let Cn=we instanceof Error?we.message:String(we);console.warn(`[job] ${k.jobId} worktree reset failed (${ae.name}): ${Cn}`)}try{await ol()}catch(ae){let we=ae instanceof Error?ae.message:String(ae);console.warn(`[job] ${k.jobId} delivery re-checkout failed: ${we}`)}},aborted:()=>j||D.paused}),Z=[];if(PT.has(k.role)&&at.length>0){let ae=k.metadata??{},we=typeof ae.commitMessage=="string"?ae.commitMessage:`${k.taskId}: changes`,Cn=k.contextRepo?.cloneUrl,al=V?.env;if(!Cn||!al)throw new Error("delivery requested but "+(Cn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Pk=k.taskId.includes(":")?k.taskId.slice(k.taskId.indexOf(":")+1):k.taskId;for(let bt of at){let An=await lh(bt,we);if(!An){console.log(`[job] ${k.jobId} ${bt.name}: no changes \u2014 no delivery`);continue}let bs=`codepipe/deliveries/${Pk}/${k.jobId}/${bt.name}`;await uh(bt,An,bs,Cn,al),Z.push({name:bt.name,deliveryRef:bs,deliverySha:An,baseSha:bt.baseSha}),console.log(`[job] ${k.jobId} ${bt.name}: delivered ${An.slice(0,10)} \u2192 ${bs}`);let cl=await dh(bt,An);if(cl.trim().length>0){let _k=Yt("display",`${bt.name}.diff`),ll=Yt(X.dir,_k);Xh(AT(ll),{recursive:!0}),Zh(ll,cl)}}}if(k.role==="resolve-conflict"&&Z.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let te;k.role==="build"&&(te=bh(X.dir),console.log(`[job] ${k.jobId} build verdict: ok=${te.ok}`+(te.failedStep?` failedStep=${te.failedStep}`:"")));let ke;k.role==="code-review"&&(ke=xh(X.dir),console.log(`[job] ${k.jobId} review verdict: approved=${ke.approved}`));let In=F.artifactPaths.length>0?F.artifactPaths:X.listFiles(),Ye=Array.from(new Set(In)),Er;if(gs)try{let ae=k.role==="index"?["adr/SOURCES.md"]:k.role==="backfill"?["adr"]:[],we=await kh(gs,ae);we.length>0&&(Er=we,console.log(`[job] ${k.jobId} captured ${we.length} knowledge file(s) for Context Repo`))}catch(ae){let we=ae instanceof Error?ae.message:String(ae);console.warn(`[job] ${k.jobId} knowledge capture failed (non-fatal): ${we}`)}let{artifacts:To,omitted:ws,dropped:sl}=Eh(X.dir,Ye);for(let ae of ws)console.warn(`[job] ${k.jobId} artifact ${ae.path} (${ae.bytes} bytes) exceeded upload budget \u2014 content omitted`);sl.length>0&&console.warn(`[job] ${k.jobId} artifact listing truncated: ${sl.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let Eo={jobId:k.jobId,status:"succeeded",artifacts:To,...Er?{contextWrites:Er}:{},...Z.length>0?{deliveries:Z}:{},log:_T(F.log),startedAt:_,finishedAt:new Date().toISOString(),usage:F.usage,...F.rateLimit?{rateLimit:F.rateLimit}:{},...te?{build:te}:{},...ke?{review:ke}:{}};if(j||D.paused)console.warn(`[job] ${k.jobId} skipping result upload \u2014 ${D.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await A.submitResult(Eo),console.log(`[job] ${k.jobId} done \u2014 uploaded ${Eo.artifacts.length} artifact(s):`);for(let ae of Eo.artifacts){let we=Buffer.from(ae.contentBase64,"base64").length;console.log(` \xB7 ${ae.path} (${we} bytes)`)}Eo.artifacts.length===0&&console.warn(`[job] ${k.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(U){let F=U instanceof Error?U.message:String(U);if(D.paused)console.log(`[job] ${k.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(j)console.warn(`[job] ${k.jobId} failed after claim lost (${F}) \u2014 skipping result upload`);else{let Z=Jg(U),te=U instanceof Wt,ke=U instanceof Et;console.warn(Z?`[job] ${k.jobId} failed: ${F} (Claude auth \u2014 token invalid/expired)`:te?`[job] ${k.jobId} failed: ${F} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:ke?`[job] ${k.jobId} failed: ${F} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${k.jobId} failed: ${F}`),await A.submitResult({jobId:k.jobId,status:"failed",artifacts:[],error:{message:F},startedAt:_,finishedAt:new Date().toISOString(),...Z?{authError:!0}:{},...te?{buildInconclusive:!0}:{},...ke?{reviewInconclusive:!0}:{}})}}finally{X.dispose()}}finally{clearInterval(st),Pe&&clearInterval(Pe),C(),D.chatInbox?.close(),f.delete(k.jobId),K?.cleanup(),V?.cleanup()}}function R(A,k){if(!A.credBundle)return{gitCreds:null,contextGitCreds:null};if(!k)return console.warn(`[job] ${A.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let D;try{D=JSON.parse(zr(k,A.credBundle).toString("utf-8"))}catch(ee){return console.warn(`[job] ${A.jobId} failed to open credBundle: ${ee instanceof Error?ee.message:String(ee)}`),{gitCreds:null,contextGitCreds:null}}let j=Ec(D);j&&console.log(`[job] ${A.jobId} cred bundle opened \u2014 git creds configured`);let K=th(D,A.contextRepo.cloneUrl),V={gitCreds:j,contextGitCreds:K};return D.claudeOauthToken&&(V.claudeOauthToken=D.claudeOauthToken),V}function S(A,k){return A.split(`
803
+ `).map(D=>k+D).join(`
804
+ `)}function b(A,k,D){let j=k[0]?.workspacePath??"";return A.replace(/\{\{codeDir\}\}/g,j).replace(/\{\{codeRoot\}\}/g,j?j.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,D??"")}function E(A,k,D){let j=A,K=D.includes("::")?"":D.split(":",2)[1]??"",V=ee=>{if(!k||!K)return"";try{return Qh(Yt(k,"tasks",K,ee),"utf-8").trim()}catch{return""}};if(j.includes("{{solutionMd}}")){let ee=V("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";j=j.replace(/\{\{solutionMd\}\}/g,()=>ee)}if(j.includes("{{taskDescription}}")){let ee=V("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";j=j.replace(/\{\{taskDescription\}\}/g,()=>ee)}return j}let O=A=>{if(p)return;p=!0,console.log(`
805
+ [${A}] shutting down`),d.abort();let k=[...f.keys()];for(let K of f.values())K.abort.abort();let D=new AbortController,j=setTimeout(()=>D.abort(),3e3);(async()=>(await Promise.all(k.map(async K=>{try{await u.releaseJob(K,`sandbox ${A}`,D.signal),console.log(`[${A}] released job ${K}`)}catch(V){let ee=V instanceof Error?V.message:String(V);console.warn(`[${A}] release failed: ${ee} (sweeper will reclaim)`)}})),clearTimeout(j),h.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM"));let B=[$("implementation")];e.planningLane!==!1?B.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(B)}var ns,PT,ey=v(()=>{"use strict";G();He();Fs();qg();Qg();_e();qi();rh();bc();wh();$h();Sh();Rh();_h();ns=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),PT=new Set(["implement","resolve-conflict"])});var hn=v(()=>{"use strict";Pg();ey();qi()});import{cancel as NT,isCancel as ry,log as ot,password as OT,text as DT}from"@clack/prompts";function LT(t){return ry(t)&&(NT("aborted"),process.exit(1)),typeof t=="string"?t:""}function MT(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function UT(t){let e=Zs({redirectUri:Qs,challenge:t.challenge,state:t.state});ot.message(`Open this URL, approve the access, and paste the code shown:
806
+ ${e}`);let r=await DT({message:"Authorization code \u2014 blank to skip"});if(ry(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=_d(r,t.state);return await ea({code:n,verifier:t.verifier,state:t.state,redirectUri:Qs})}catch(n){return ot.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function BT(t){if(Us()?.claude?.oauthToken&&!t.farm)return ot.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN==="0"||!process.stdout.isTTY)return null;ot.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=Xo(),n;try{n=await jd({...r,openUrl:lr,log:i=>ot.message(i)})}catch(i){ot.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await UT(r);if(s===null)return null;n=s}let o=await Mt(n.oauthToken);return o==="invalid"?(ot.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(ot.success(`Claude: logged in \u2014 ${MT(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function FT(t){ot.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t.farm?`
807
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=LT(await OT({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||ot.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),e):(ot.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}var ny,oy=v(()=>{"use strict";Qo();Gr();de();ra();ny={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:BT,promptManual:FT,validate:Mt}});function iy(t){return ny}async function sy(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var ay=v(()=>{"use strict";oy()});async function kn(t,e,r){return e.host==="github"?KT(t,e,r):e.host==="gitlab"?JT(t,e,r):QT(t,e,r)}async function cy(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 zt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await ly(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 Vt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await uy(e.gitlabToken,t):o}}return e.bitbucket?(await yn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await dy(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 ly(t,e){let r=!1;try{r=(await zt(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 uy(t,e){let r=!1;try{r=(await Vt(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 dy(t,e){let r=!1;try{r=(await yn(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 zt(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(GT+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 KT(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 HT(n,e,r),i=await qT(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Vr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await YT(n,o.owner,o.name,a.path,i)||await VT(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 HT(t,e,r){let n=await zt(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 ly(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await WT(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 zt(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 WT(t,e){let{status:r,data:n}=await zt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function qT(t,e,r){let{data:n}=await zt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function YT(t,e,r,n,o){let{status:i,data:s}=await zt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function VT(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 zt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Vt(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(zT+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 JT(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 Vt(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 uy(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Vt(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let m=await Vt(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(m.status===404||!m.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=m.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let f=await Vt(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Vr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await Vt(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let m of f)l.add(m.path);if(f.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Vt(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 yn(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(XT+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 QT(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 yn(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 dy(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 yn(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=Vr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await yn(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let f of l)p.set(f.path,f.content);if((await yn(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 GT,zT,XT,os=v(()=>{"use strict";kr();GT="https://api.github.com";zT="https://gitlab.com/api/v4";XT="https://api.bitbucket.org/2.0"});function We(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=ZT[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 ZT,is=v(()=>{"use strict";ZT={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as eE}from"node:crypto";import{existsSync as py,mkdirSync as tE,readFileSync as fy,readdirSync as rE,rmSync as ss,writeFileSync as nE}from"node:fs";import{homedir as oE}from"node:os";import{dirname as iE,join as jc}from"node:path";function my(){return jc(oE(),".codepipe","init-drafts")}function Nc(t){let e=eE("sha256").update(t).digest("hex").slice(0,16);return jc(my(),`${e}.json`)}function gy(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=sE)}function hy(t){let e=Nc(t);if(!py(e))return null;try{let r=JSON.parse(fy(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:gy(r.savedAt)?(ss(e,{force:!0}),null):r}catch{return null}}function Oc(t){ss(Nc(t),{force:!0})}function yy(){let t=my();if(py(t))for(let e of rE(t)){let r=jc(t,e);try{let n=JSON.parse(fy(r,"utf-8"));gy(n.savedAt)&&ss(r,{force:!0})}catch{ss(r,{force:!0})}}}var sE,wn,ky=v(()=>{"use strict";sE=24*60*60*1e3;wn=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){Oc(this.cwd)}persist(){let e=Nc(this.cwd);tE(iE(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};nE(e,JSON.stringify(r,null,2)+`
808
+ `,{mode:384})}}});function wy(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 by(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 $y=v(()=>{"use strict"});import{existsSync as aE}from"node:fs";import{join as cE}from"node:path";import{simpleGit as lE}from"simple-git";function fE(t){let e=t.split("/");return e[e.length-1]??t}function vy(t){if(t.filter(r=>!dE.test(fE(r))).length>uE)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(pE.has(n))return!0}return!1}async function mE(t){try{let r=(await lE(t).raw(["ls-files"])).split(`
809
+ `).map(n=>n.trim()).filter(Boolean);return vy(r)}catch{return!1}}async function gE(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)?vy(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function xy(t,e){for(let r of t)try{let n=e.localRoot!=null?cE(e.localRoot,r.mountAs??r.name):null;if(n&&aE(n)?await mE(n):await gE(r,e.tokens))return!0}catch{}return!1}var uE,dE,pE,Sy=v(()=>{"use strict";uE=3,dE=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,pE=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Ty}from"node:fs";import{join as Ey}from"node:path";import{simpleGit as Ry}from"simple-git";async function yo(t,e,r={}){let n=r.log??hE,o=[];for(let i of e){let s=Ey(t,i.mountAs),a=xu(i);if(!Ty(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 Ry().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=ho(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(!Ty(Ey(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=Ry(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!yE(l,a)){n.warn(`${i.mountAs}/ origin (${ho(l)||"none"}) != expected (${ho(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:ho(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=ho(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 yE(t,e){return Iy(t)===Iy(e)}function Iy(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function ho(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Cy(t={}){let e=xe();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 yo(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 hE,as=v(()=>{"use strict";mt();hE={info:t=>console.log(t),warn:t=>console.warn(t)}});import{spawn as Py}from"node:child_process";import{existsSync as Ay}from"node:fs";import{homedir as kE,hostname as wE}from"node:os";import{join as cs}from"node:path";async function bE(t,e,r){let n=Ce(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${nt(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 Gd(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 ${nt(e)} still holds its token.
810
+ Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${n.sandboxId} \u2014 replacing the registration`),Fu(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function $E(t,e,r){let n=Ce(e)!==null;if(!await bE(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 ti(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof H&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof H&&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 H?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 $r({hub:t.hubUrl,token:o,name:r.name??`${wE()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function vE(t,e){let r=Ce(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=je(r.sealPublicKey);if(!Y(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Ko(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 Dc(t,e,r){await $E(t,e,r),vE(t.projectId,e)}function xE(t){return[...t?["--profile",t]:[],"worker","start"]}function SE(t){let e={...t};for(let r of Bs)delete e[r];return e}function Lc(t){let e=Py(process.execPath,[t.entry,...xE(t.profile)],{stdio:["ignore","pipe","pipe"],env:SE(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
811
+ `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function TE(t,e){let r=process.cwd(),n=cs(r,ft);if(Bo(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Ay(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 ne(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Bc(r);if(!vu(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=Y(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Hi({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=cs(kE(),".codepipe",e?cs("profiles",e,"context-config"):"context-config");if(li(c.contextDir,l,a),!Ay(cs(c.contextDir,"project.yaml"))){qr(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Yn(c.contextDir,yt(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 Mc(t){let{cfg:e,profile:r}=Go(t.profile);await TE(e,r),await Dc(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(f,m)=>{let g=y=>w=>{for(let h of w.toString("utf-8").split(`
812
+ `))h.length>0&&y.write(`${m} ${h}
813
+ `)};f.stdout?.on("data",g(process.stdout)),f.stderr?.on("data",g(process.stderr))},i=(f,m)=>{let g=Py(process.execPath,[n,...m],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,f),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Lc({entry:n,profile:r,onLine:f=>process.stdout.write(`[worker] ${f}
814
+ `)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=f=>{if(!l){l=!0,console.log(`
815
+ [up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${m} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:f,child:m})=>new Promise(g=>{m.on("exit",(y,w)=>g({name:f,code:y??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var Uc=v(()=>{"use strict";He();hn();Le();xt();yc();kr();Te();de();mt();ko()});var By={};Rr(By,{replCommand:()=>Hc});import{existsSync as Ly,mkdirSync as EE,readFileSync as RE,writeFileSync as IE}from"node:fs";import{homedir as CE}from"node:os";import{dirname as AE,join as My}from"node:path";import*as bn from"node:readline";async function Hc(t={}){let e=xe();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=Y(e.spec.projectId);r||(console.error(`no secrets for project ${e.spec.projectId} at ~/.codepipe/secrets/${e.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),Un(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let n=hr(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
809
816
  \u26A0 unfinished local apply: ${o.map(a=>`${a} (${n[a].repos.map(c=>c.mountAs).join(", ")})`).join("; ")}
810
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=wn.createInterface({input:process.stdin,output:process.stdout,completer:kR,history:MR(),removeHistoryDuplicates:!0}),s={ws:e,secrets:r,connection:"connecting",rl:i,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};qd(a=>Xt(s,a)),s.daemon=Ui({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>Xt(s,a),warn:a=>Xt(s,a)},onEvent:a=>_R(s,a),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos.map(a=>({name:a.name,mountAs:a.mountAs,defaultBranch:a.defaultBranch}))}});try{let a={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await Ac(a,t.profile,{profile:t.profile});let c=process.argv[1];if(!c)throw new Error("cannot resolve the codepipe entry script for the worker process");let l=Pc({entry:c,profile:t.profile,onLine:u=>Xt(s,`[worker] ${u}`)});l.on("exit",(u,p)=>{s.workerExited=!0,!Lc&&Jt(s,`[worker] exited (code ${u??(p?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),s.workerChild=l,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(a){console.warn(`[worker] could not start the embedded worker (${a instanceof Error?a.message:String(a)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}Dc(s),i.prompt(),i.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await wR(s,c)){Ty(s);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}s.unread=0,Dc(s),i.prompt()}),i.on("close",()=>{Ty(s)})}function kR(t){let e=$y.filter(r=>r.startsWith(t));return[e.length?e:$y,t]}async function wR(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return bR(),!1;case"/status":return await $R(t),!1;case"/tasks":return await vR(t,n),!1;case"/task":return await xR(t,n),!1;case"/sync":return await SR(t),!1;case"/logs":return jR(t,n),!1;case"/monitor":return NR(t),!1;case"/apply":return await xy(t,n,"apply"),!1;case"/unstash":return await xy(t,n,"unstash"),!1;case"/applied":return await TR(t,n),!1;case"/abort":return await RR(t,n),!1;case"/approve":return await Sy(t,n,"approve"),!1;case"/merge":return await Sy(t,n,"merge"),!1;case"/login":return ER(t,n),!1;case"/secret":return CR(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function bR(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
811
- `))}async function $R(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=Ry(Iy(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function vR(t,e){let r=OR(e,"--phase");try{let n=await Ud(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){yo(n)}}async function xR(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Bd(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){yo(n)}}async function SR(t){let e=await ho(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 xy(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await op(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function TR(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=hr(t.ws.contextDir)[r],i=DR(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,p;if(l>0?(u=c.slice(0,l),p=c.slice(l+1)):(p=c,u=o?.repos.length===1?IR(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${p}`);return}let d=p.match(/(?:pull|pull-requests)\/(\d+)/);if(!d){console.log(` cannot parse PR number from ${p}`);return}a.push({repoName:u,url:p,number:Number(d[1])})}try{let c=await Fd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);na(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){yo(c)}}async function Sy(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Gd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){yo(o)}}async function RR(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=LR(e,"--reason")||"local apply aborted";await sp(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await Kd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){yo(o)}}function IR(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function ER(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},ne(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 CR(t,e){let[r,n,...o]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
812
- `)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}AR(t.secrets,n,i),ne(t.secrets),Ln(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}PR(t.secrets,n),ne(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function AR(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 PR(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 _R(t,e){switch(e.kind){case"connected":t.connection="connecting",Xt(t,"[hub] connected");break;case"registered":t.connection="registered",Xt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Jt(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Xt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Jt(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Jt(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?Xt(t,`[hub] action ${e.actionType} done`):Jt(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?Jt(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):Jt(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function Xt(t,e){t.logBuffer.push(e),t.logBuffer.length>Ey&&t.logBuffer.shift(),t.follow&&Jt(t,e)}function jR(t,e){let r=e[0];if(r==="follow"||r==="on"){Oc(t,!0);return}if(r==="off"){Oc(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Ey,Number(r)||vy)):vy,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 NR(t){Oc(t,!t.follow)}function Oc(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Jt(t,e){wn.cursorTo(process.stdout,0),wn.clearLine(process.stdout,0),process.stdout.write(e+`
813
- `),t.unread+=1,Dc(t),t.rl.prompt(!0)}function Dc(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function Ty(t){if(Lc)return;Lc=!0,UR(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
817
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=bn.createInterface({input:process.stdin,output:process.stdout,completer:PE,history:XE(),removeHistoryDuplicates:!0}),s={ws:e,secrets:r,connection:"connecting",rl:i,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};ep(a=>Xt(s,a)),s.daemon=Gi({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>Xt(s,a),warn:a=>Xt(s,a)},onEvent:a=>WE(s,a),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos.map(a=>({name:a.name,mountAs:a.mountAs,defaultBranch:a.defaultBranch}))}});try{let a={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await Dc(a,t.profile,{profile:t.profile});let c=process.argv[1];if(!c)throw new Error("cannot resolve the codepipe entry script for the worker process");let l=Lc({entry:c,profile:t.profile,onLine:u=>Xt(s,`[worker] ${u}`)});l.on("exit",(u,p)=>{s.workerExited=!0,!Kc&&Jt(s,`[worker] exited (code ${u??(p?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),s.workerChild=l,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(a){console.warn(`[worker] could not start the embedded worker (${a instanceof Error?a.message:String(a)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}Gc(s),i.prompt(),i.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await _E(s,c)){Dy(s);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}s.unread=0,Gc(s),i.prompt()}),i.on("close",()=>{Dy(s)})}function PE(t){let e=_y.filter(r=>r.startsWith(t));return[e.length?e:_y,t]}async function _E(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return jE(),!1;case"/status":return await NE(t),!1;case"/tasks":return await OE(t,n),!1;case"/task":return await DE(t,n),!1;case"/sync":return await LE(t),!1;case"/logs":return qE(t,n),!1;case"/monitor":return YE(t),!1;case"/apply":return await Ny(t,n,"apply"),!1;case"/unstash":return await Ny(t,n,"unstash"),!1;case"/applied":return await ME(t,n),!1;case"/abort":return await UE(t,n),!1;case"/approve":return await Oy(t,n,"approve"),!1;case"/merge":return await Oy(t,n,"merge"),!1;case"/login":return FE(t,n),!1;case"/secret":return GE(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function jE(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
818
+ `))}async function NE(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=Ly(My(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function OE(t,e){let r=VE(e,"--phase");try{let n=await qd(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){wo(n)}}async function DE(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Yd(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){wo(n)}}async function LE(t){let e=await yo(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 Ny(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await dp(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function ME(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=hr(t.ws.contextDir)[r],i=zE(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,p;if(l>0?(u=c.slice(0,l),p=c.slice(l+1)):(p=c,u=o?.repos.length===1?BE(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${p}`);return}let d=p.match(/(?:pull|pull-requests)\/(\d+)/);if(!d){console.log(` cannot parse PR number from ${p}`);return}a.push({repoName:u,url:p,number:Number(d[1])})}try{let c=await Vd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);ca(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){wo(c)}}async function Oy(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Jd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){wo(o)}}async function UE(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=JE(e,"--reason")||"local apply aborted";await fp(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await zd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){wo(o)}}function BE(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function FE(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},re(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 GE(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(`
819
+ `)}`:" (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}KE(t.secrets,n,i),re(t.secrets),Un(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}HE(t.secrets,n),re(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function KE(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 HE(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 WE(t,e){switch(e.kind){case"connected":t.connection="connecting",Xt(t,"[hub] connected");break;case"registered":t.connection="registered",Xt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Jt(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Xt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Jt(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Jt(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?Xt(t,`[hub] action ${e.actionType} done`):Jt(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?Jt(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):Jt(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function Xt(t,e){t.logBuffer.push(e),t.logBuffer.length>Uy&&t.logBuffer.shift(),t.follow&&Jt(t,e)}function qE(t,e){let r=e[0];if(r==="follow"||r==="on"){Fc(t,!0);return}if(r==="off"){Fc(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Uy,Number(r)||jy)):jy,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 YE(t){Fc(t,!t.follow)}function Fc(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Jt(t,e){bn.cursorTo(process.stdout,0),bn.clearLine(process.stdout,0),process.stdout.write(e+`
820
+ `),t.unread+=1,Gc(t),t.rl.prompt(!0)}function Gc(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function Dy(t){if(Kc)return;Kc=!0,QE(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
814
821
  bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
815
- stopping the embedded worker\u2026`),e.kill("SIGTERM"),e.on("exit",()=>{console.log("bye."),setTimeout(()=>process.exit(0),150)}),setTimeout(()=>{t.workerExited||e.kill("SIGKILL")},8e3).unref(),setTimeout(()=>process.exit(0),1e4).unref()}function OR(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function DR(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function LR(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function yo(t){t instanceof H?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function MR(){if(!Ry(is))return[];try{return mR(is,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function UR(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{fR(yR(is),{recursive:!0}),hR(is,r.slice().reverse().join(`
822
+ 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 VE(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function zE(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function JE(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function wo(t){t instanceof H?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function XE(){if(!Ly(ls))return[];try{return RE(ls,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function QE(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{EE(AE(ls),{recursive:!0}),IE(ls,r.slice().reverse().join(`
816
823
  `)+`
817
- `)}catch{}}var is,$y,Ey,vy,Lc,Uc=x(()=>{"use strict";uc();xe();Zo();ue();pt();ns();jc();oa();is=Iy(gR(),".codepipe","history"),$y=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Ey=500,vy=40;Lc=!1});import{existsSync as bn,mkdirSync as Py,readFileSync as _y,readdirSync as BR,writeFileSync as jy}from"node:fs";import{join as vr,resolve as Ny}from"node:path";import{setTimeout as Bc}from"node:timers/promises";import{cancel as FR,confirm as $n,intro as Oy,isCancel as Gc,log as A,multiselect as KR,outro as Fc,password as ko,select as It,spinner as Hc,text as me}from"@clack/prompts";import{simpleGit as as}from"simple-git";function le(t){FR(t),process.exit(1)}function Ee(t){return Gc(t)&&le("aborted"),t}function se(t){return Gc(t)&&le("aborted"),typeof t=="string"?t:""}async function Dy(t={}){Oy("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();sy();let r=iy(e),n,o=!1;r&&Object.keys(r.answers).length>0?Ee(await $n({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(A.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new kn(e,r),o=!0):(Cc(e),n=new kn(e)):n=new kn(e);let i=t.force===!0?null:await Nc(e),s=await n.ask("target",async()=>Ee(await It({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?A.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||My(e,t.force===!0));let c=await n.ask("hubUrl",async()=>se(await me({message:"HUB URL",placeholder:st,initialValue:Y("HUB_URL")??st,validate:v=>v.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>vn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>xn(c,l)),d=null;s==="farm"&&(d=await GR(c,u));let m=a?WR(a.parsed.repoName):"",f=await n.ask("projectId",async()=>se(await me({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:v=>nr.test(v.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await n.ask("projectName",async()=>se(await me({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:v=>v.trim().length>0?void 0:"required"})).trim()),k=await n.ask("automationLevel",async()=>Ee(await It({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"?"auto":await n.ask("applyMode",async()=>Ee(await It({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),g=await n.ask("trackerProvider",async()=>Ee(await It({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"}))),$=g==="internal",T=null,C,S=!0;if($){let v,O=Hc();O.start("checking task-key prefixes on your account\u2026");try{v=await Dd(c,u,{excludeProjectId:f}),O.stop("prefixes checked")}catch{O.stop("could not reach the HUB",1),le("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=su(iu(h),v);C=await n.ask("trackerPrefix",async()=>se(await me({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:X,initialValue:X,validate:ve=>{let Ye=ve.trim();if(!Nr.test(Ye))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(v.has(Ye.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else T=await n.ask("youtrack",()=>Wy()),C=await n.ask("youtrackProjectKey",async()=>se(await me({message:"YouTrack project key",placeholder:"DEV",validate:v=>v.trim().length>0?void 0:"required"})).trim()),S=await n.ask("youtrackWrites",async()=>Ee(await $n({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let b=n.get("tokens")??{},I=()=>n.set("tokens",b),M=await n.ask("repos",()=>VR(b,l,a,{onCred:I,initial:n.get("reposPartial")??[],onProgress:v=>n.set("reposPartial",v)}));n.delete("reposPartial");let G=await zR(await n.ask("contextRepo",()=>Ky(f,M,b,l)),f,M,b,l,I,v=>n.set("contextRepo",v)),{spec:E,mode:w}=G,N;$||(A.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),N=await n.ask("assigneeLogin",async()=>se(await me({message:"your YouTrack login (the assignee value)",...T?.login?{initialValue:T.login}:{},validate:v=>v.trim().length>0?void 0:"required"})).trim()));let _=await n.ask("llmProvider",async()=>{for(;;){if(Ee(await It({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";A.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),B=_==="claude"?await n.ask("claudeToken",()=>zg(Vg("claude"),{farm:s==="farm"})):"",V;if(B){let v=await xd(B);if(v){let O=Pl(v);O&&(V=O,A.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${O} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let ee={projectId:f,name:h,automationLevel:k,repos:M,trackerProvider:g,youtrackProjectKey:C};A.step(`${w==="attach"?"attaching to":"provisioning"} Context Repo ${E.owner}/${E.name} (${E.host})\u2026`);let Le;try{Le=await yn(ee,E,{...Gy(b),youtrackWrites:S,...T?{trackerUrl:T.url}:{},mode:w,log:{info:v=>A.message(v),warn:v=>A.warn(v)}})}catch(v){le(`Context Repo provisioning failed: ${v instanceof Error?v.message:String(v)}`)}ee.contextRepo=Le,A.success(`Context Repo ready: ${Le.owner}/${Le.name}@${Le.branch}`),A.step(`registering project on ${c}\u2026`);let Me;try{Me=await Ut(c,u,ee)}catch(v){if(v instanceof H&&v.status===409){A.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{Me=await oe(c,u,f)}catch(O){throw O instanceof H&&le(`HUB \u2192 ${O.status} ${O.message}`),O}}else if(v instanceof H&&v.status===401)n.delete("cliToken"),le("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(v instanceof H)le(`HUB \u2192 ${v.status} ${v.message}`);else throw v}let P=Me.contextRepo??Le;A.success(`project ${Me.projectId} ready (${Me.provisioningStatus})`);let L=await eI(P),j=T?{url:T.url,token:T.token}:void 0;if(s==="farm"){let v=d,O={...b,...L?{contextWrite:L}:{},...B?{claude:{oauthToken:B}}:{},...j?{youtrack:j}:{}},X=b.github?.token;if(P.host==="github"&&X)try{let Z=ah(`devpipe-${f}`);await ch(P,X,Z.publicKey,`devpipe-${f}`),O.contextSsh={privateKey:Z.privateKey},A.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(Z){A.warn(`could not set up Context Repo SSH deploy key (${Z instanceof Error?Z.message:String(Z)}); the farm will fall back to the token path.`)}let ve={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:O,contextRepo:P,projectConfig:ht(ee,S,T?.url,N||void 0,"auto",_,V)},Ye=xt(v.farm.publicKey,JSON.stringify(ve));A.step(`handing project ${f} to farm ${v.farm.name}\u2026`);let J;try{J=await Xo(c,u,v.farm.farmId,{projectId:f,sealedBundle:Ye})}catch(Z){throw Z instanceof H&&le(Z.status===409?`farm ${v.farm.name} is offline \u2014 start it and re-run.`:Z.status===504?`farm ${v.farm.name} did not respond in time.`:`HUB \u2192 ${Z.status} ${Z.message}`),Z}J.ok||le(`farm rejected provisioning: ${J.error??"unknown error"}`),await Kc(c,u,f,P,X,Me.repos,null,b),n.clear(),Fc(`done. project ${f} is now hosted on farm ${v.farm.name} (daemon ${J.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Hy(b),await Uy(e,P.cloneUrl,P.branch),Fy(e),a&&await qR(e);{let v=vr(e,dt);Wr(v);let O=ht(ee,S,T?.url,N||void 0,y,_,V),X=Wn(v,O);X.length>0&&A.success(`local project config \u2192 .codepipe/{${X.join(", ")}}`),gr(f,O,{info:ve=>A.message(ve),warn:ve=>A.warn(ve)})}await By(e,Me.repos);let q={hubUrl:c,cliToken:u,projectId:f,...b,...L?{contextWrite:L}:{},...B?{claude:{oauthToken:B}}:{},...j?{youtrack:j}:{}};ne(q),$t({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),A.success(`secrets \u2192 ${ft(f)}`),await Kc(c,u,f,P,b.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,Me.repos,e,b),n.clear();let D=`${c}/?project=${encodeURIComponent(f)}`;cr(D),Fc(`done. your project on the dashboard (sign in there to work with it):
818
- ${D}
819
- starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:R}=await Promise.resolve().then(()=>(Uc(),Cy));await R({})}async function Kc(t,e,r,n,o,i=[],s=null,a={}){let c=await ly(n,o),l=!1;if(!c)try{l=await py(i,{localRoot:s,tokens:a})}catch{l=!1}let u=cy({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await KR({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Gc(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let m=$e(s);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(Mi(),oc)),h=await f(m,void 0,{onLog:k=>A.message(k)});A.success(`project map ready: ${h.events} task events mined from history`)}catch(m){A.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 Bn(t,e,r,{reindex:!1,backfill:!0});A.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){A.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 Bn(t,e,r,{reindex:u.reindex});A.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){A.warn(`could not start indexing: ${m instanceof Error?m.message:String(m)}. You can retry later \u2014 registration is not affected.`)}}async function GR(t,e){let r;try{r=await _d(t,e)}catch(c){throw c instanceof H&&le(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&le("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=Ee(await It({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=ji(i.farmId,i.publicKey)}catch(c){le(c instanceof Error?c.message:String(c))}return Ee(await $n({message:`confirm farm ${i.name} cred-channel fingerprint:
824
+ `)}catch{}}var ls,_y,Uy,jy,Kc,Wc=v(()=>{"use strict";gc();Te();ri();de();mt();as();Uc();la();ls=My(CE(),".codepipe","history"),_y=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Uy=500,jy=40;Kc=!1});import{existsSync as $n,mkdirSync as Gy,readFileSync as Ky,readdirSync as ZE,writeFileSync as Hy}from"node:fs";import{join as xr,resolve as Wy}from"node:path";import{setTimeout as qc}from"node:timers/promises";import{cancel as eR,confirm as vn,intro as qy,isCancel as zc,log as P,multiselect as tR,outro as Yc,password as bo,select as it,spinner as Jc,text as me}from"@clack/prompts";import{simpleGit as ds}from"simple-git";function le(t){eR(t),process.exit(1)}function Se(t){return zc(t)&&le("aborted"),t}function ie(t){return zc(t)&&le("aborted"),typeof t=="string"?t:""}async function Yy(t={}){qy("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();yy();let r=hy(e),n,o=!1;r&&Object.keys(r.answers).length>0?Se(await vn({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 wn(e,r),o=!0):(Oc(e),n=new wn(e)):n=new wn(e);let i=t.force===!0?null:await Bc(e),s=await n.ask("target",async()=>Se(await it({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?P.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||zy(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ie(await me({message:"HUB URL",placeholder:ct,initialValue:z("HUB_URL")??ct,validate:I=>I.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>xn()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Sn(c,l)),d=null;s==="farm"&&(d=await rR(c,u));let f=a?oR(a.parsed.repoName):"",m=await n.ask("projectId",async()=>ie(await me({message:"project id (slug)",placeholder:f||"acme",...f?{initialValue:f}:{},validate:I=>or.test(I.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>ie(await me({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:I=>I.trim().length>0?void 0:"required"})).trim()),y=await n.ask("language",()=>fR()),w=await n.ask("automationLevel",async()=>Se(await it({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"}))),h=s==="farm"?"auto":await n.ask("applyMode",async()=>Se(await it({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),$=await n.ask("trackerProvider",async()=>Se(await it({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"}))),x=$==="internal",R=null,S,b=!0;if(x){let I,W=Jc();W.start("checking task-key prefixes on your account\u2026");try{I=await Kd(c,u,{excludeProjectId:m}),W.stop("prefixes checked")}catch{W.stop("could not reach the HUB",1),le("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 ye=fu(pu(g),I);S=await n.ask("trackerPrefix",async()=>ie(await me({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:ye,initialValue:ye,validate:Pe=>{let X=Pe.trim();if(!Or.test(X))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(I.has(X.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else R=await n.ask("youtrack",()=>rk()),S=await n.ask("youtrackProjectKey",async()=>ie(await me({message:"YouTrack project key",placeholder:"DEV",validate:I=>I.trim().length>0?void 0:"required"})).trim()),b=await n.ask("youtrackWrites",async()=>Se(await vn({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let E=n.get("tokens")??{},O=()=>n.set("tokens",E),B=await n.ask("repos",()=>aR(E,l,a,{onCred:O,initial:n.get("reposPartial")??[],onProgress:I=>n.set("reposPartial",I)}));n.delete("reposPartial");let A=await cR(await n.ask("contextRepo",()=>Zy(m,B,E,l)),m,B,E,l,O,I=>n.set("contextRepo",I)),{spec:k,mode:D}=A,j;x||(P.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),j=await n.ask("assigneeLogin",async()=>ie(await me({message:"your YouTrack login (the assignee value)",...R?.login?{initialValue:R.login}:{},validate:I=>I.trim().length>0?void 0:"required"})).trim()));let K=await n.ask("llmProvider",async()=>{for(;;){if(Se(await it({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.")}}),V=K==="claude"?await n.ask("claudeToken",()=>sy(iy("claude"),{farm:s==="farm"})):"",ee;if(V){let I=await Ad(V);if(I){let W=Ll(I);W&&(ee=W,P.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${W} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let qe={projectId:m,name:g,automationLevel:w,repos:B,trackerProvider:$,youtrackProjectKey:S,language:y};P.step(`${D==="attach"?"attaching to":"provisioning"} Context Repo ${k.owner}/${k.name} (${k.host})\u2026`);let st;try{st=await kn(qe,k,{...ek(E),youtrackWrites:b,...R?{trackerUrl:R.url}:{},mode:D,log:{info:I=>P.message(I),warn:I=>P.warn(I)}})}catch(I){le(`Context Repo provisioning failed: ${I instanceof Error?I.message:String(I)}`)}qe.contextRepo=st,P.success(`Context Repo ready: ${st.owner}/${st.name}@${st.branch}`),P.step(`registering project on ${c}\u2026`);let _;try{_=await Ut(c,u,qe)}catch(I){if(I instanceof H&&I.status===409){P.warn(`project ${m} already exists on HUB \u2014 reusing it`);try{_=await ne(c,u,m)}catch(W){throw W instanceof H&&le(`HUB \u2192 ${W.status} ${W.message}`),W}}else if(I instanceof H&&I.status===401)n.delete("cliToken"),le("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(I instanceof H)le(`HUB \u2192 ${I.status} ${I.message}`);else throw I}let L=_.contextRepo??st;P.success(`project ${_.projectId} ready (${_.provisioningStatus})`);let N=await mR(L),q=R?{url:R.url,token:R.token}:void 0;if(s==="farm"){let I=d,W={...E,...N?{contextWrite:N}:{},...V?{claude:{oauthToken:V}}:{},...q?{youtrack:q}:{}},ye=E.github?.token;if(L.host==="github"&&ye)try{let se=gg(`devpipe-${m}`);await hg(L,ye,se.publicKey,`devpipe-${m}`),W.contextSsh={privateKey:se.privateKey},P.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(se){P.warn(`could not set up Context Repo SSH deploy key (${se instanceof Error?se.message:String(se)}); the farm will fall back to the token path.`)}let Pe={projectId:m,config:{hubUrl:c,cliToken:u,projectId:m},secrets:W,contextRepo:L,projectConfig:yt(qe,b,R?.url,j||void 0,"auto",K,ee)},X=St(I.farm.publicKey,JSON.stringify(Pe));P.step(`handing project ${m} to farm ${I.farm.name}\u2026`);let ue;try{ue=await ei(c,u,I.farm.farmId,{projectId:m,sealedBundle:X})}catch(se){throw se instanceof H&&le(se.status===409?`farm ${I.farm.name} is offline \u2014 start it and re-run.`:se.status===504?`farm ${I.farm.name} did not respond in time.`:`HUB \u2192 ${se.status} ${se.message}`),se}ue.ok||le(`farm rejected provisioning: ${ue.error??"unknown error"}`),await Vc(c,u,m,L,ye,_.repos,null,E),n.clear(),Yc(`done. project ${m} is now hosted on farm ${I.farm.name} (daemon ${ue.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}tk(E),await Jy(e,L.cloneUrl,L.branch),Qy(e),a&&await sR(e);{let I=xr(e,ft);qr(I);let W=yt(qe,b,R?.url,j||void 0,h,K,ee),ye=Yn(I,W);ye.length>0&&P.success(`local project config \u2192 .codepipe/{${ye.join(", ")}}`),yr(m,W,{info:Pe=>P.message(Pe),warn:Pe=>P.warn(Pe)})}await Xy(e,_.repos);let M={hubUrl:c,cliToken:u,projectId:m,...E,...N?{contextWrite:N}:{},...V?{claude:{oauthToken:V}}:{},...q?{youtrack:q}:{}};re(M),vt({hubUrl:c,cliToken:u,projectId:m,accountEmail:p},m),P.success(`secrets \u2192 ${gt(m)}`),await Vc(c,u,m,L,E.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,_.repos,e,E),n.clear();let T=`${c}/?project=${encodeURIComponent(m)}`;lr(T),Yc(`done. your project on the dashboard (sign in there to work with it):
825
+ ${T}
826
+ starting codepipe \u2014 the CLI daemon, an agent worker, and a command line. type /help for commands; Ctrl+D or /quit to exit (restart anytime with \`codepipe\` from this folder).`);let{replCommand:C}=await Promise.resolve().then(()=>(Wc(),By));await C({})}async function Vc(t,e,r,n,o,i=[],s=null,a={}){let c=await by(n,o),l=!1;if(!c)try{l=await xy(i,{localRoot:s,tokens:a})}catch{l=!1}let u=wy({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await tR({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(zc(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let f=xe(s);if(!f)throw new Error("workspace not found");let{bootstrapWorkspaceModel:m}=await Promise.resolve().then(()=>(Fi(),lc)),g=await m(f,void 0,{onLog:y=>P.message(y)});P.success(`project map ready: ${g.events} task events mined from history`)}catch(f){P.warn(`could not build the project map: ${f instanceof Error?f.message:String(f)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:f}=await Gn(t,e,r,{reindex:!1,backfill:!0});P.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){P.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:f}=await Gn(t,e,r,{reindex:u.reindex});P.success(`indexing queued (job ${f}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(f){P.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function rR(t,e){let r;try{r=await Ud(t,e)}catch(c){throw c instanceof H&&le(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&le("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=Se(await it({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=Di(i.farmId,i.publicKey)}catch(c){le(c instanceof Error?c.message:String(c))}return Se(await vn({message:`confirm farm ${i.name} cred-channel fingerprint:
820
827
  ${s}
821
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||le("farm fingerprint not confirmed \u2014 aborting."),_i(i.farmId,s),{farm:i,fingerprint:s}}async function Ly(t){Oy(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();My(e,t.force===!0);let r=se(await me({message:"HUB URL",initialValue:Y("HUB_URL")??st,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await vn(),{cliToken:o,accountEmail:i}=await xn(r,n);A.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await oe(r,o,t.projectId)}catch(d){throw d instanceof H&&le(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||le(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Wy(),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 ss(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}Hy(l),await Uy(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Fy(e);{let d=vr(e,dt);Wr(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}:{}},f=ht(m,!0,c?.url,void 0,"auto",s.llmProvider??ut),h=Wn(d,f);h.length>0&&A.success(`local project config \u2192 .codepipe/{${h.join(", ")}} (defaults \u2014 review and adjust)`),gr(t.projectId,f,{info:k=>A.message(k),warn:k=>A.warn(k)})}await By(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ne(p),$t({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),A.success(`secrets \u2192 ${ft(t.projectId)}`),await Kc(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),Fc("done.")}function My(t,e){if(!bn(t)){Py(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=BR(t).filter(o=>!r.has(o));n.length!==0&&(e||le(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Nc(t){if(!bn(vr(t,".git")))return null;try{let r=(await as(t).remote(["get-url","origin"])||"").toString().trim(),n=r?We(r):null;return n?{parsed:n,defaultBranch:await HR(t)}:null}catch{return null}}async function HR(t){let e=as(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 WR(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return nr.test(e)?e:""}function YR(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function qR(t){let e=vr(t,".gitignore"),r=bn(e)?_y(e,"utf-8"):"";if(YR(r))return;if(!Ee(await $n({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){A.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
828
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||le("farm fingerprint not confirmed \u2014 aborting."),Oi(i.farmId,s),{farm:i,fingerprint:s}}async function Vy(t){qy(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();zy(e,t.force===!0);let r=ie(await me({message:"HUB URL",initialValue:z("HUB_URL")??ct,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await xn(),{cliToken:o,accountEmail:i}=await Sn(r,n);P.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await ne(r,o,t.projectId)}catch(d){throw d instanceof H&&le(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||le(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await rk(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let f=s.repos.find(m=>m.host===d);await us(d,l,f?.owner??s.contextRepo.owner,n,f?.repoName)}tk(l),await Jy(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Qy(e);{let d=xr(e,ft);qr(d);let f={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},m=yt(f,!0,c?.url,void 0,"auto",s.llmProvider??pt),g=Yn(d,m);g.length>0&&P.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),yr(t.projectId,m,{info:y=>P.message(y),warn:y=>P.warn(y)})}await Xy(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};re(p),vt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),P.success(`secrets \u2192 ${gt(t.projectId)}`),await Vc(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),Yc("done.")}function zy(t,e){if(!$n(t)){Gy(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=ZE(t).filter(o=>!r.has(o));n.length!==0&&(e||le(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Bc(t){if(!$n(xr(t,".git")))return null;try{let r=(await ds(t).remote(["get-url","origin"])||"").toString().trim(),n=r?We(r):null;return n?{parsed:n,defaultBranch:await nR(t)}:null}catch{return null}}async function nR(t){let e=ds(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 oR(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return or.test(e)?e:""}function iR(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function sR(t){let e=xr(t,".gitignore"),r=$n(e)?Ky(e,"utf-8"):"";if(iR(r))return;if(!Se(await vn({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(`
822
829
  `)?"":`
823
- `;jy(e,r+o+`
830
+ `;Hy(e,r+o+`
824
831
  # codepipe workspace (added by \`codepipe init\`)
825
832
  .codepipe/
826
- `),A.success(`.codepipe/ added to ${Ny(e)}`)}async function vn(){let t="";try{t=(await as().raw(["config","--global","user.email"])||"").trim()}catch{}return se(await me({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){A.step(`connecting account ${e}`);let r;try{r=await Ld(t,e)}catch(s){throw s instanceof Un&&le(`${e} is not authorized on this HUB yet.
833
+ `),P.success(`.codepipe/ added to ${Wy(e)}`)}async function xn(){let t="";try{t=(await ds().raw(["config","--global","user.email"])||"").trim()}catch{}return ie(await me({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Sn(t,e){P.step(`connecting account ${e}`);let r;try{r=await Hd(t,e)}catch(s){throw s instanceof Fn&&le(`${e} is not authorized on this HUB yet.
827
834
  Sign up at ${t} (registration form on the login screen),
828
835
  wait for the operator to approve it by email, then re-run
829
- \`codepipe init\` with the same email.`),s}r.accountCreated&&A.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&A.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(cr(r.authorizeUrl),A.message(`a browser tab was opened to confirm this CLI:
836
+ \`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&&(lr(r.authorizeUrl),P.message(`a browser tab was opened to confirm this CLI:
830
837
  ${r.authorizeUrl}
831
838
  `+(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
832
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&A.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),A.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 Md(t,r.requestId)}catch(a){A.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Bc(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&A.message(`connected as ${a} (the account confirmed in the browser).`),A.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&le("the HUB rejected this account"),s.status==="expired"&&le("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,A.message(`email confirmed. waiting for the operator to approve your account\u2026
833
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Bc(5e3);continue}await Bc(2e3)}le("bootstrap timed out")}async function Uy(t,e,r){let n=vr(t,dt);if(bn(vr(n,".git"))){A.message(`${n} already cloned \u2014 skipping`);return}bn(n)&&le(`${n} exists but is not a git repo \u2014 remove it and re-run`),Py(n,{recursive:!0}),A.step(`cloning Context Repo \u2192 ${n}`);try{await as().clone(e,n,["--branch",r]),A.success(`cloned ${e}`)}catch(o){le(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function By(t,e){if(e.length===0)return;A.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 ho(t,r,{log:{info:o=>A.message(o),warn:o=>A.warn(o)}});for(let o of n)A.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Fy(t){let e=vr(t,dt,".gitignore"),r="";if(bn(e)&&(r=_y(e,"utf-8")),Ay.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
839
+ 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 Wd(t,r.requestId)}catch(a){P.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await qc(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"&&le("the HUB rejected this account"),s.status==="expired"&&le("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
840
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await qc(5e3);continue}await qc(2e3)}le("bootstrap timed out")}async function Jy(t,e,r){let n=xr(t,ft);if($n(xr(n,".git"))){P.message(`${n} already cloned \u2014 skipping`);return}$n(n)&&le(`${n} exists but is not a git repo \u2014 remove it and re-run`),Gy(n,{recursive:!0}),P.step(`cloning Context Repo \u2192 ${n}`);try{await ds().clone(e,n,["--branch",r]),P.success(`cloned ${e}`)}catch(o){le(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function Xy(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 yo(t,r,{log:{info:o=>P.message(o),warn:o=>P.warn(o)}});for(let o of n)P.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Qy(t){let e=xr(t,ft,".gitignore"),r="";if($n(e)&&(r=Ky(e,"utf-8")),Fy.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
834
841
  `)||r.length===0?"":`
835
- `,i=Ay.join(`
842
+ `,i=Fy.join(`
836
843
  `)+`
837
- `;jy(e,r+o+(r?`
838
- `:"")+i),A.message(`appended runtime entries to ${Ny(e)}`)}async function VR(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;A.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await ss(s.host,t,s.owner,e,s.repoName),i?.();let c=se(await me({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=se(await me({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;Ee(await $n({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=se(await me({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||We(m)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=We(a);A.message(`${c.host}: ${c.owner}/${c.repoName}`),await ss(c.host,t,c.owner,e,c.repoName),i?.();let l=se(await me({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:m=>m.trim().length>0?void 0:"required"})).trim(),u=se(await me({message:"default branch (optional)",placeholder:"main"})).trim(),p=se(await me({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),d={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(d.defaultBranch=u),p&&p!==l&&(d.mountAs=p),o.push(d),n.onProgress?.(o)}return o}async function Ky(t,e,r,n){A.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=Ee(await It({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&A.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=se(await me({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:bt(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!We(p)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(p))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=We(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await JR(),l=se(await me({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=se(await me({message:"Context Repo name",placeholder:bt(t),initialValue:bt(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function Gy(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??Mr()}}async function zR(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await ss(c.host,n,c.owner,o),i?.();let u=Hc();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await Xg(c,Gy(n),{explain:l==="attach"});if(p.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(p.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${p.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(p.detail,1);let d=Ee(await It({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(d==="abort"&&le("aborted"),d==="create")return a={spec:c,mode:"create"},s(a),a;a=await Ky(e,r,n,o),s(a)}}async function JR(){return Ee(await It({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function wo(t,e){let r=Hc();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 Hy(t){Jn(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Xn(t.gitlab?.token??process.env.GITLAB_TOKEN),Qn(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function ss(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await XR(r);i?e.github=i:A.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await QR(r,n,o);i?e.bitbucket=i:A.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 ZR();i?e.gitlab=i:A.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function XR(t){for(;;){let e=se(await ko({message:`GitHub PAT \u2014 blank to skip
844
+ `;Hy(e,r+o+(r?`
845
+ `:"")+i),P.message(`appended runtime entries to ${Wy(e)}`)}async function aR(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;P.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await us(s.host,t,s.owner,e,s.repoName),i?.();let c=ie(await me({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=ie(await me({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;Se(await vn({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=ie(await me({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:f=>!f||!f.trim()||We(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=We(a);P.message(`${c.host}: ${c.owner}/${c.repoName}`),await us(c.host,t,c.owner,e,c.repoName),i?.();let l=ie(await me({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=ie(await me({message:"default branch (optional)",placeholder:"main"})).trim(),p=ie(await me({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),d={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(d.defaultBranch=u),p&&p!==l&&(d.mountAs=p),o.push(d),n.onProgress?.(o)}return o}async function Zy(t,e,r,n){P.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=Se(await it({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&P.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=ie(await me({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:$t(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!We(p)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(p))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=We(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await lR(),l=ie(await me({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=ie(await me({message:"Context Repo name",placeholder:$t(t),initialValue:$t(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function ek(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??Ur()}}async function cR(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await us(c.host,n,c.owner,o),i?.();let u=Jc();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await cy(c,ek(n),{explain:l==="attach"});if(p.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(p.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${p.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(p.detail,1);let d=Se(await it({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(d==="abort"&&le("aborted"),d==="create")return a={spec:c,mode:"create"},s(a),a;a=await Zy(e,r,n,o),s(a)}}async function lR(){return Se(await it({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function $o(t,e){let r=Jc();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 tk(t){Qn(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Zn(t.gitlab?.token??process.env.GITLAB_TOKEN),eo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function us(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await uR(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 dR(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 pR();i?e.gitlab=i:P.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function uR(t){for(;;){let e=ie(await bo({message:`GitHub PAT \u2014 blank to skip
839
846
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
840
847
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
841
848
  if org: approve token in org Settings \u2192 Personal access tokens.
842
849
  (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
843
- set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await wo("GitHub",()=>_t(e,t?{owner:t}:void 0)))return{token:e};A.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function QR(t,e,r){for(A.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
850
+ set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await $o("GitHub",()=>_t(e,t?{owner:t}:void 0)))return{token:e};P.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function dR(t,e,r){for(P.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
844
851
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
845
852
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
846
853
  read:repository:bitbucket + write:repository:bitbucket +
847
854
  read:pullrequest:bitbucket + write:pullrequest:bitbucket
848
855
  \u2014 write scopes do NOT include read: pick BOTH scopes of each pair
849
856
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
850
- The token is shown ONCE \u2014 copy it right away.`);;){let n=se(await me({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=se(await ko({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){A.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await wo("Bitbucket",async()=>{let i=await jt(n,o,t);if(t&&r){let s=await qo(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};A.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function ZR(){for(;;){let t=se(await ko({message:`GitLab PAT \u2014 blank to skip
851
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await wo("GitLab",()=>Nt(t))){let e=await Wu(t);return e&&A.warn(e),{token:t}}A.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function eI(t){if(Ee(await $n({message:`Issue a separate context-write token (scoped to the Context Repo only)?
857
+ The token is shown ONCE \u2014 copy it right away.`);;){let n=ie(await me({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:i=>!i||!i.trim()||i.includes("@")?void 0:"must be an email"})).trim();if(!n)return;let o=ie(await bo({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 $o("Bitbucket",async()=>{let i=await jt(n,o,t);if(t&&r){let s=await Jo(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 pR(){for(;;){let t=ie(await bo({message:`GitLab PAT \u2014 blank to skip
858
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await $o("GitLab",()=>Nt(t))){let e=await Qu(t);return e&&P.warn(e),{token:t}}P.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function fR(){let t="__other__",e=async()=>ie(await me({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=Se(await it({message:"project language",options:[...On.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:nr};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:nr}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",nr].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===nr?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=Se(await it({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function mR(t){if(Se(await vn({message:`Issue a separate context-write token (scoped to the Context Repo only)?
852
859
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
853
860
  credential. A scoped token hardens setups where the SANDBOX runs outside
854
- your trusted network.`,initialValue:!1})))for(t.host==="github"?A.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
861
+ your trusted network.`,initialValue:!1})))for(t.host==="github"?P.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
855
862
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
856
- required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):A.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
857
- (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=se(await ko({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await wo("contextWrite",()=>tI(r,t)))return{token:r};A.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function tI(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function Wy(){for(;;){let t=se(await me({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=se(await ko({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await wo("YouTrack",()=>Lt({baseUrl:t,token:e}))){let r=await id({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}A.warn("re-enter the YouTrack URL / token.")}}var Ay,go=x(()=>{"use strict";Ae();K();He();Jg();zo();Oe();vt();yr();Fr();es();dc();ts();Ot();ar();ay();xe();uy();fy();Ja();mi();ue();ns();pt();Ay=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});K();Ae();Oe();import{Command as NI}from"commander";Oo();import{homedir as $u}from"node:os";import{join as vu}from"node:path";function xu(){ir(vu($u(),".devpipe"),vu($u(),".codepipe"))}Oe();ue();async function Du(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=Xe(e);r&&!t.force&&(console.error(`already configured at ${Dr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");$t({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...W(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ne(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Dr(e)}`)}Ds();Oe();uc();xe();ue();vt();pc();pt();mi();import{homedir as fc}from"node:os";import{join as ao}from"node:path";async function gh(t={profile:void 0}){let{cfg:e,profile:r}=Uo(t.profile),n=W(e.projectId);n&&Ln(n),Jn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Xn(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Qn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=ao(fc(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Ko("CLI_LOG",i,o);if(s.enabled){let d=new Ur(s);Go(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=Lo(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=ao(fc(),".codepipe",r?ao("profiles",r,"context"):"context");if(await ea(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await mh(()=>Fi({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 ea(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=ao(fc(),".codepipe",r?ao("profiles",r,"context-config"):"context-config");si(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=Ui(e,{...a?{workspace:a}:{},onEvent:d=>{d.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function p(d){u||(u=!0,console.log(`
858
- [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}hn();Oe();xe();async function Hg(t={profile:void 0}){let e=Fe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Jo(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 oe(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=Ie(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`)")}go();import{readFileSync as rI}from"node:fs";K();Oe();vt();es();yr();Ot();ar();xe();ue();function fe(t){throw new Error(t)}function be(t,e){return(typeof t!="string"||t.trim().length===0)&&fe(`config: '${e}' must be a non-empty string`),t.trim()}function bo(t,e){if(t==null)return;typeof t!="string"&&fe(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function nI(t){(!t||typeof t!="object")&&fe("config: expected a JSON object");let e=t,r=be(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||fe("config: 'hubUrl' must start with http(s)://");let n=be(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&fe("config: 'project' is required");let i=o,s=be(i.id,"project.id");nr.test(s)||fe("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=be(i.name,"project.name"),c=be(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&fe("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||fe("config: 'project.repos' must be an array");let u=l.map((g,$)=>{(!g||typeof g!="object")&&fe(`config: project.repos[${$}] must be an object`);let T=g,C=be(T.host,`project.repos[${$}].host`);C!=="github"&&C!=="bitbucket"&&C!=="gitlab"&&fe(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let S={name:be(T.name,`project.repos[${$}].name`),host:C,owner:be(T.owner,`project.repos[${$}].owner`),repoName:be(T.repoName,`project.repos[${$}].repoName`)},b=bo(T.defaultBranch,`project.repos[${$}].defaultBranch`);b&&(S.defaultBranch=b);let I=bo(T.mountAs,`project.repos[${$}].mountAs`);return I&&(S.mountAs=I),S}),p=i.contextRepo;(!p||typeof p!="object")&&fe("config: 'project.contextRepo' is required");let d=p,m=bo(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&fe("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:be(d.owner,"project.contextRepo.owner"),name:bo(d.name,"project.contextRepo.name")??bt(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},k=bo(i.youtrackProjectKey,"project.youtrackProjectKey");if(k&&(h.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&fe("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&fe("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let g=be(i.llmProvider,"project.llmProvider");g==="codex"&&fe(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),g!=="claude"&&fe("config: 'project.llmProvider' must be 'claude'"),h.project.llmProvider=g}let y=e.secrets;if(y!==void 0){(typeof y!="object"||y===null)&&fe("config: 'secrets' must be an object");let g=y,$={};if(g.github){let T=g.github;$.github={token:be(T.token,"secrets.github.token")}}if(g.bitbucket){let T=g.bitbucket;$.bitbucket={email:be(T.email,"secrets.bitbucket.email"),apiToken:be(T.apiToken,"secrets.bitbucket.apiToken")}}if(g.gitlab){let T=g.gitlab;$.gitlab={token:be(T.token,"secrets.gitlab.token")}}if(g.youtrack){let T=g.youtrack;$.youtrack={url:be(T.url,"secrets.youtrack.url").replace(/\/$/,""),token:be(T.token,"secrets.youtrack.token")}}if(g.contextWrite){let T=g.contextWrite;$.contextWrite={token:be(T.token,"secrets.contextWrite.token")}}h.secrets=$}return h}async function oI(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function iI(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await _t(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 jt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await qo(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 Nt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Lt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Yy(t){let e=!t.configPath||t.configPath==="-"?await oI():rI(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){fe(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=nI(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 iI(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 yn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Mr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){fe(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await Ut(o,i,a)}catch(d){if(d instanceof H&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await oe(o,i,s.id);else if(d instanceof H)fe(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(ne(p),$t({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${ft(s.id)}`),gr(s.id,ht(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??ut),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Bn(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`)}Oe();ue();import{cancel as qy,intro as Vy,isCancel as zy,log as Wc,outro as sI,password as Jy}from"@clack/prompts";async function aI(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Xy(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await aI(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Vy("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Wc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Jy({message:"Claude OAuth token"});zy(i)&&(qy("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Ou({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Fo()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Fe(t.profile);if(!e){Vy(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Wc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Jy({message:"Claude OAuth token"});zy(i)&&(qy("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=W(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ne(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Wc.success("Claude OAuth token saved."),sI("It will be sealed into job bundles when a SANDBOX (re)connects."))}Mi();K();Oe();vt();es();yr();ts();xe();ue();import{cancel as cI,confirm as lI,intro as uI,isCancel as Qy,log as Ce,outro as dI,select as Zy,text as Qt}from"@clack/prompts";function ek(t){cI(t),process.exit(1)}function Sn(t){return Qy(t)&&ek("aborted"),t}function $o(t){return Qy(t)&&ek("aborted"),typeof t=="string"?t:""}async function pI(t,e){let r=Sn(await Zy({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=$o(await Qt({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=$o(await Qt({message:"Context Repo name",placeholder:bt(t),initialValue:bt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function tk(t={profile:void 0}){let e=Fe(t.profile);uI(`codepipe project add \u2192 ${e.hubUrl}`);let r=Sn(await Qt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>nr.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Sn(await Qt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Sn(await Zy({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=Sn(await Qt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Sn(await lI({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=$o(await Qt({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:y=>!y||!y.trim()||We(y)?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=We(d);Ce.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=$o(await Qt({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:y=>y.trim().length>0?void 0:"required"})).trim(),h=$o(await Qt({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:f,host:m.host,owner:m.owner,repoName:m.repoName};h&&(k.defaultBranch=h),a.push(k)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await pI(r,a),u=W(e.projectId);Ce.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await yn(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??Mr(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Ce.message(d),warn:d=>Ce.warn(d)}})}catch(d){Ce.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Ce.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Ut(e.hubUrl,e.cliToken,c);Ce.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),gr(r,ht(c,s,u?.youtrack?.url),{info:m=>Ce.message(m),warn:m=>Ce.warn(m)}),d.contextRepo&&(Ce.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Ce.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Ce.error(` error: ${d.provisioningError}`),dI("done")}catch(d){d instanceof H?(Ce.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Ce.message(JSON.stringify(d.payload,null,2))):Ce.error(d instanceof Error?d.message:String(d)),process.exit(1)}}hn();Oe();xe();ue();pt();go();import{existsSync as fI,rmSync as mI}from"node:fs";import{confirm as hI,intro as gI,isCancel as yI,log as Zt,outro as kI,spinner as wI}from"@clack/prompts";function yt(t){Zt.error(t),process.exit(1)}var rk=t=>t.trim().replace(/\/+$/,"");async function nk(t){gI("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??$e()?.spec.projectId??void 0;e||yt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Xe(e);r||yt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=rk(r.hubUrl),o=r.projectId,i=rk(t.hub);i.startsWith("http")||yt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&yt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let y=wI();y.start(`reading project ${o} from ${n}\u2026`);try{l=await oe(n,r.cliToken,o),y.stop(`read project ${o} (${l.name})`)}catch(g){throw y.stop("could not read the source project",1),g instanceof H&&yt(`source HUB ${n} \u2192 ${g.status} ${g.message}. The source HUB must be reachable with a valid token to move a project.`),g}}l.contextRepo||yt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=W(o),p=(t.account??r.accountEmail??await vn()).trim().toLowerCase();if(Zt.message(`move project '${o}'
863
+ required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):P.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
864
+ (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=ie(await bo({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await $o("contextWrite",()=>gR(r,t)))return{token:r};P.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function gR(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function rk(){for(;;){let t=ie(await me({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=ie(await bo({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await $o("YouTrack",()=>Lt({baseUrl:t,token:e}))){let r=await pd({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}P.warn("re-enter the YouTrack URL / token.")}}var Fy,ko=v(()=>{"use strict";_e();G();He();ay();Qo();Le();xt();kr();Gr();os();hc();is();Ot();cr();ky();Te();$y();Sy();tc();yi();de();as();mt();Fy=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});G();_e();Le();import{Command as VR}from"commander";Mo();import{homedir as Iu}from"node:os";import{join as Cu}from"node:path";function Au(){sr(Cu(Iu(),".devpipe"),Cu(Iu(),".codepipe"))}Le();de();async function Ku(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=Xe(e);r&&!t.force&&(console.error(`already configured at ${Lr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");vt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...Y(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};re(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Lr(e)}`)}Fs();Le();gc();Te();de();xt();yc();mt();yi();import{homedir as kc}from"node:os";import{join as lo}from"node:path";async function Sg(t={profile:void 0}){let{cfg:e,profile:r}=Go(t.profile),n=Y(e.projectId);n&&Un(n),Qn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Zn(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),eo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=lo(kc(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Wo("CLI_LOG",i,o);if(s.enabled){let d=new Br(s);qo(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=Bo(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=lo(kc(),".codepipe",r?lo("profiles",r,"context"):"context");if(await ia(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await vg(()=>Hi({cfg:e,secrets:n,contextDir:d,log:{info:f=>console.log(f),warn:f=>console.warn(f)}}),{log:{warn:f=>console.warn(f)}}),a||await ia(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let f=lo(kc(),".codepipe",r?lo("profiles",r,"context-config"):"context-config");li(a.contextDir,f,{info:m=>console.log(m),warn:m=>console.warn(m)})}}let l=Gi(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(`
865
+ [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}hn();Le();Te();async function ty(t={profile:void 0}){let e=Fe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Zo(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 ne(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=Ce(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`)")}ko();import{readFileSync as hR}from"node:fs";G();Le();xt();os();kr();Ot();cr();Te();de();function ge(t){throw new Error(t)}function ve(t,e){return(typeof t!="string"||t.trim().length===0)&&ge(`config: '${e}' must be a non-empty string`),t.trim()}function vo(t,e){if(t==null)return;typeof t!="string"&&ge(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function yR(t){(!t||typeof t!="object")&&ge("config: expected a JSON object");let e=t,r=ve(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ge("config: 'hubUrl' must start with http(s)://");let n=ve(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ge("config: 'project' is required");let i=o,s=ve(i.id,"project.id");or.test(s)||ge("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=ve(i.name,"project.name"),c=ve(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ge("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ge("config: 'project.repos' must be an array");let u=l.map((h,$)=>{(!h||typeof h!="object")&&ge(`config: project.repos[${$}] must be an object`);let x=h,R=ve(x.host,`project.repos[${$}].host`);R!=="github"&&R!=="bitbucket"&&R!=="gitlab"&&ge(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let S={name:ve(x.name,`project.repos[${$}].name`),host:R,owner:ve(x.owner,`project.repos[${$}].owner`),repoName:ve(x.repoName,`project.repos[${$}].repoName`)},b=vo(x.defaultBranch,`project.repos[${$}].defaultBranch`);b&&(S.defaultBranch=b);let E=vo(x.mountAs,`project.repos[${$}].mountAs`);return E&&(S.mountAs=E),S}),p=i.contextRepo;(!p||typeof p!="object")&&ge("config: 'project.contextRepo' is required");let d=p,f=vo(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&ge("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:ve(d.owner,"project.contextRepo.owner"),name:vo(d.name,"project.contextRepo.name")??$t(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},y=vo(i.youtrackProjectKey,"project.youtrackProjectKey");if(y&&(g.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&ge("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ge("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let h=ve(i.llmProvider,"project.llmProvider");h==="codex"&&ge(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),h!=="claude"&&ge("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=h}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&ge("config: 'secrets' must be an object");let h=w,$={};if(h.github){let x=h.github;$.github={token:ve(x.token,"secrets.github.token")}}if(h.bitbucket){let x=h.bitbucket;$.bitbucket={email:ve(x.email,"secrets.bitbucket.email"),apiToken:ve(x.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let x=h.gitlab;$.gitlab={token:ve(x.token,"secrets.gitlab.token")}}if(h.youtrack){let x=h.youtrack;$.youtrack={url:ve(x.url,"secrets.youtrack.url").replace(/\/$/,""),token:ve(x.token,"secrets.youtrack.token")}}if(h.contextWrite){let x=h.contextWrite;$.contextWrite={token:ve(x.token,"secrets.contextWrite.token")}}g.secrets=$}return g}async function kR(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function wR(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await _t(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 jt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await Jo(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 Nt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Lt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function nk(t){let e=!t.configPath||t.configPath==="-"?await kR():hR(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){ge(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=yR(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 wR(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??Ur(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){ge(`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 Ut(o,i,a)}catch(d){if(d instanceof H&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await ne(o,i,s.id);else if(d instanceof H)ge(`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(re(p),vt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${gt(s.id)}`),yr(s.id,yt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??pt),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await Gn(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`)}Le();de();import{cancel as ok,intro as ik,isCancel as sk,log as Xc,outro as bR,password as ak}from"@clack/prompts";async function $R(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function ck(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await $R(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){ik("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Xc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await ak({message:"Claude OAuth token"});sk(i)&&(ok("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Gu({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Ho()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Fe(t.profile);if(!e){ik(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Xc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await ak({message:"Claude OAuth token"});sk(i)&&(ok("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=Y(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},re(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Xc.success("Claude OAuth token saved."),bR("It will be sealed into job bundles when a SANDBOX (re)connects."))}Fi();G();Le();xt();os();kr();is();Te();de();import{cancel as vR,confirm as xR,intro as SR,isCancel as lk,log as Ae,outro as TR,select as uk,text as Qt}from"@clack/prompts";function dk(t){vR(t),process.exit(1)}function Tn(t){return lk(t)&&dk("aborted"),t}function xo(t){return lk(t)&&dk("aborted"),typeof t=="string"?t:""}async function ER(t,e){let r=Tn(await uk({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=xo(await Qt({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=xo(await Qt({message:"Context Repo name",placeholder:$t(t),initialValue:$t(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function pk(t={profile:void 0}){let e=Fe(t.profile);SR(`codepipe project add \u2192 ${e.hubUrl}`);let r=Tn(await Qt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>or.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Tn(await Qt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=Tn(await uk({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=Tn(await Qt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Tn(await xR({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=xo(await Qt({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:w=>!w||!w.trim()||We(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let f=We(d);Ae.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=xo(await Qt({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),g=xo(await Qt({message:"default branch (optional)",placeholder:"main"})).trim(),y={name:m,host:f.host,owner:f.owner,repoName:f.repoName};g&&(y.defaultBranch=g),a.push(y)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await ER(r,a),u=Y(e.projectId);Ae.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??Ur(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Ae.message(d),warn:d=>Ae.warn(d)}})}catch(d){Ae.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Ae.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await Ut(e.hubUrl,e.cliToken,c);Ae.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),yr(r,yt(c,s,u?.youtrack?.url),{info:f=>Ae.message(f),warn:f=>Ae.warn(f)}),d.contextRepo&&(Ae.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Ae.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Ae.error(` error: ${d.provisioningError}`),TR("done")}catch(d){d instanceof H?(Ae.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Ae.message(JSON.stringify(d.payload,null,2))):Ae.error(d instanceof Error?d.message:String(d)),process.exit(1)}}hn();Le();Te();de();mt();ko();import{existsSync as RR,rmSync as IR}from"node:fs";import{confirm as CR,intro as AR,isCancel as PR,log as Zt,outro as _R,spinner as jR}from"@clack/prompts";function wt(t){Zt.error(t),process.exit(1)}var fk=t=>t.trim().replace(/\/+$/,"");async function mk(t){AR("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??xe()?.spec.projectId??void 0;e||wt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Xe(e);r||wt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=fk(r.hubUrl),o=r.projectId,i=fk(t.hub);i.startsWith("http")||wt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&wt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=jR();w.start(`reading project ${o} from ${n}\u2026`);try{l=await ne(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(h){throw w.stop("could not read the source project",1),h instanceof H&&wt(`source HUB ${n} \u2192 ${h.status} ${h.message}. The source HUB must be reachable with a valid token to move a project.`),h}}l.contextRepo||wt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=Y(o),p=(t.account??r.accountEmail??await xn()).trim().toLowerCase();if(Zt.message(`move project '${o}'
859
866
  from : ${n} (profile ${e})
860
867
  to : ${i} (profile ${s}, project ${a}, account ${p})
861
868
  \u2022 the source registration on the old HUB is left intact (non-destructive)
862
869
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
863
- `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let y=await hI({message:"Continue?",initialValue:!0});(yI(y)||!y)&&yt("aborted")}!c&&a===o&&Zt.warn(`source and destination share the same project id, so they share one secrets file (${ft(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}:{}};Zt.step(`registering project on ${i}\u2026`);let h;try{h=await Ut(i,d,f)}catch(y){if(y instanceof H&&y.status===409){Zt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await oe(i,d,a)}catch(g){throw g instanceof H&&yt(`target HUB \u2192 ${g.status} ${g.message}`),g}}else if(y instanceof H&&y.status===403)yt(`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(y instanceof H)yt(`target HUB \u2192 ${y.status} ${y.message}`);else throw y}Zt.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),$t({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let k={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete k.sandboxPins,ne(k),Zt.success(`profile '${s}' \u2192 ${ft(a)}`),c){let y=nt(s);fI(y)&&(mI(y),Zt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}kI(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Oe();$a();ts();xe();Kr();ue();pt();import{existsSync as Yc,rmSync as bI,statSync as $I}from"node:fs";import{join as cs,relative as vI,resolve as xI}from"node:path";import{cancel as SI,intro as ik,isCancel as TI,log as he,outro as sk,text as xr}from"@clack/prompts";import{simpleGit as ak}from"simple-git";function De(t){SI(t),process.exit(1)}function Sr(t){return TI(t)&&De("aborted"),typeof t=="string"?t:""}async function ok(t){try{let e=await ak(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function RI(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function II(t,e){let r=W(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(RI(r,e)){he.message(`reusing existing ${e} credentials`);return}if(he.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Sr(await xr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Sr(await xr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Sr(await xr({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}}ne(r),he.success(`saved ${e} credentials`)}async function ck(t){let e=Fe(t.profile);ik(`codepipe repo add \u2192 project ${e.projectId}`);let r=$e()??void 0,n;try{n=(await oe(e.hubUrl,e.cliToken,e.projectId)).repos}catch(g){De(`could not read project from HUB: ${g instanceof Error?g.message:String(g)}`)}let o=t.target?.trim();if(!o){let g=await ok(process.cwd());g?(o=process.cwd(),he.message(`using the current directory (${g})`)):o=Sr(await xr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:$=>$.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Yc(o)&&$I(o).isDirectory()){i=xI(o);let g=await ok(i);g||De(`${i} is not a git repository (no origin remote)`);let $=We(g);$||De(`origin ${g} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=g,he.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let g=We(o);g||De(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=g,s=o,he.message(`${a}: ${c}/${l}`)}let u=Sr(await xr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:g=>g.trim()?void 0:"required"})).trim();n.some(g=>g.name===u)&&De(`a repo named "${u}" is already registered`);let p=Sr(await xr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let g=vI(r.root,i);d=g===""?".":g}let m=Sr(await xr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(g=>(g.mountAs??g.name)===m)&&De(`mount_as "${m}" is already used by another repo`),await II(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!i){let g=r?cs(r.root,m):Re(e.projectId,u);if(Yc(cs(g,".git")))he.message(`already cloned at ${g}`);else{he.info(`cloning ${s} \u2192 ${g} \u2026`);try{await ak().clone(s,g),he.success(`cloned into ${g}`)}catch($){De(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
864
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await Hd(e.hubUrl,e.cliToken,e.projectId,f)}catch(g){g instanceof H&&De(`HUB \u2192 ${g.status} ${g.message}`),De(g instanceof Error?g.message:String(g))}let{updated:k,errors:y}=zn(e.projectId,h.repos,r?.contextDir);for(let g of k)he.message(`updated ${g}`);for(let g of y)he.warn(`could not update ${g.path}: ${g.error}`);he.success(`added "${u}" \u2014 project now has ${h.repos.length} repo(s)`),sk("done")}async function lk(t){let e=Fe(t.profile);ik(`codepipe repo remove \u2192 project ${e.projectId}`);let r=$e()??void 0,n;try{let c=(await oe(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 Wd(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof H&&(a.status===404&&De(`no repo named "${t.name}" in this project`),De(`HUB \u2192 ${a.status} ${a.message}`)),De(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=zn(e.projectId,o.repos,r?.contextDir);for(let a of i)he.message(`updated ${a}`);for(let a of s)he.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")he.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?cs(r.root,n):Re(e.projectId,t.name);if(Yc(cs(a,".git")))try{bI(a,{recursive:!0,force:!0}),he.message(`deleted local clone ${a}`)}catch(c){he.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else he.message(`no local clone found to purge (${a})`)}he.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),sk("done")}async function uk(t){let e=Fe(t.profile),r;try{r=(await oe(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}`)}}ns();jc();Uc();hn();K();Ae();hn();Oe();xe();go();import{hostname as EI}from"node:os";import{cancel as CI,confirm as dk,intro as AI,isCancel as mk,log as Tn,multiselect as PI,outro as pk,password as _I,select as qc,text as Vc}from"@clack/prompts";function vo(t){CI(t),process.exit(1)}function Rn(t){return mk(t)&&vo("aborted"),t}function ls(t){return mk(t)&&vo("aborted"),typeof t=="string"?t:""}function us(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function fk(t,e){try{let{secret:r}=await Qo(t,e);return r}catch(r){throw r instanceof H&&r.status===404&&vo("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 jI(t,e){if(Rn(await qc({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let o=await Qs(t,e);if(o.length>0)return Rn(await PI({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}));Tn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Tn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return ls(await Vc({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 zc(t){AI("codepipe worker \u2014 set up this machine as a runner");let e=Ie(t.profile);e&&(Tn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Rn(await dk({message:"re-register this worker?",initialValue:!1}))||vo("keeping the existing registration"));let r=Xe(t.profile)??Xe(),n=ls(await Vc({message:"HUB URL",placeholder:st,initialValue:Y("HUB_URL")??r?.hubUrl??st,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Rn(await qc({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 fk(n,a),Tn.success("account-issued registration token minted");else if(i==="login"){let d=await vn();a=(await xn(n,d)).cliToken,s=await fk(n,a),Tn.success("account-issued registration token minted")}else s=ls(await _I({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||vo("a registration token is required");let c=await jI(n,a),l=ls(await Vc({message:"worker name",initialValue:EI(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Rn(await qc({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 br({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Tn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Rn(await dk({message:"start the claim-loop now?",initialValue:!0}))){pk("registered. start later with `codepipe worker`.");return}pk("starting the claim-loop\u2026"),await fo(t.profile?{profile:t.profile}:{})}function OI(){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 Y("PROFILE")}var de=OI();bu(de);xu();var Ne=new NI;Ne.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ue).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{us()?await Mc({profile:de}):await _c({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ne.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 Yy({configPath:t.config,skipVerify:t.skipVerify===!0}):await Dy({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ne.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 Du({...t,profile:de})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ne.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 Ly({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ne.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await gh({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ne.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 ky({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ne.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 Xy({profile:de,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ne.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Hg({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ne.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await _c({profile:de,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var hk=Ne.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");hk.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??Y("HUB_URL")??Xe(de)?.hubUrl??st,r=t.token??Y("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&us()){await zc({profile:de});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let n=Y("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??Y("WORKER_NAME"),i=t.llm??Y("WORKER_LLM");await br({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...de?{profile:de}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});hk.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Ie(de)&&us()){await zc({profile:de});return}await fo(de?{profile:de}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var gk=Ne.command("project").description("Manage CodePipe projects");gk.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await tk({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});gk.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 nk({...t,cliProfile:de})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Jc=Ne.command("repo").description("Manage the project's git repositories");Jc.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 ck({profile:de,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Jc.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 lk({profile:de,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Jc.command("list").description("List the project's repos").action(async()=>{try{await uk({profile:de})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var yk=Ne.command("model").description("Project map (model/ in the Context Repo)");yk.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 rc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});yk.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 nc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ne.parseAsync();
870
+ `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let w=await CR({message:"Continue?",initialValue:!0});(PR(w)||!w)&&wt("aborted")}!c&&a===o&&Zt.warn(`source and destination share the same project id, so they share one secrets file (${gt(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:f}=await Sn(i,p),m={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:f,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Zt.step(`registering project on ${i}\u2026`);let g;try{g=await Ut(i,d,m)}catch(w){if(w instanceof H&&w.status===409){Zt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await ne(i,d,a)}catch(h){throw h instanceof H&&wt(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if(w instanceof H&&w.status===403)wt(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof H)wt(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}Zt.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),vt({hubUrl:i,cliToken:d,projectId:a,accountEmail:f},s);let y={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete y.sandboxPins,re(y),Zt.success(`profile '${s}' \u2192 ${gt(a)}`),c){let w=nt(s);RR(w)&&(IR(w),Zt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}_R(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Le();Ea();is();Te();Kr();de();mt();import{existsSync as Qc,rmSync as NR,statSync as OR}from"node:fs";import{join as ps,relative as DR,resolve as LR}from"node:path";import{cancel as MR,intro as hk,isCancel as UR,log as he,outro as yk,text as Sr}from"@clack/prompts";import{simpleGit as kk}from"simple-git";function Me(t){MR(t),process.exit(1)}function Tr(t){return UR(t)&&Me("aborted"),typeof t=="string"?t:""}async function gk(t){try{let e=await kk(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function BR(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function FR(t,e){let r=Y(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(BR(r,e)){he.message(`reusing existing ${e} credentials`);return}if(he.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=Tr(await Sr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=Tr(await Sr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=Tr(await Sr({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}}re(r),he.success(`saved ${e} credentials`)}async function wk(t){let e=Fe(t.profile);hk(`codepipe repo add \u2192 project ${e.projectId}`);let r=xe()??void 0,n;try{n=(await ne(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){Me(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await gk(process.cwd());h?(o=process.cwd(),he.message(`using the current directory (${h})`)):o=Tr(await Sr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:$=>$.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Qc(o)&&OR(o).isDirectory()){i=LR(o);let h=await gk(i);h||Me(`${i} is not a git repository (no origin remote)`);let $=We(h);$||Me(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=h,he.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=We(o);h||Me(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,he.message(`${a}: ${c}/${l}`)}let u=Tr(await Sr({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:h=>h.trim()?void 0:"required"})).trim();n.some(h=>h.name===u)&&Me(`a repo named "${u}" is already registered`);let p=Tr(await Sr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=DR(r.root,i);d=h===""?".":h}let f=Tr(await Sr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(h=>(h.mountAs??h.name)===f)&&Me(`mount_as "${f}" is already used by another repo`),await FR(e,a);let m={name:u,host:a,owner:c,repoName:l,mountAs:f,...p?{defaultBranch:p}:{}};if(!i){let h=r?ps(r.root,f):Ie(e.projectId,u);if(Qc(ps(h,".git")))he.message(`already cloned at ${h}`);else{he.info(`cloning ${s} \u2192 ${h} \u2026`);try{await kk().clone(s,h),he.success(`cloned into ${h}`)}catch($){Me(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
871
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await Xd(e.hubUrl,e.cliToken,e.projectId,m)}catch(h){h instanceof H&&Me(`HUB \u2192 ${h.status} ${h.message}`),Me(h instanceof Error?h.message:String(h))}let{updated:y,errors:w}=Xn(e.projectId,g.repos,r?.contextDir);for(let h of y)he.message(`updated ${h}`);for(let h of w)he.warn(`could not update ${h.path}: ${h.error}`);he.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),yk("done")}async function bk(t){let e=Fe(t.profile);hk(`codepipe repo remove \u2192 project ${e.projectId}`);let r=xe()??void 0,n;try{let c=(await ne(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 Qd(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof H&&(a.status===404&&Me(`no repo named "${t.name}" in this project`),Me(`HUB \u2192 ${a.status} ${a.message}`)),Me(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Xn(e.projectId,o.repos,r?.contextDir);for(let a of i)he.message(`updated ${a}`);for(let a of s)he.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")he.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?ps(r.root,n):Ie(e.projectId,t.name);if(Qc(ps(a,".git")))try{NR(a,{recursive:!0,force:!0}),he.message(`deleted local clone ${a}`)}catch(c){he.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else he.message(`no local clone found to purge (${a})`)}he.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),yk("done")}async function $k(t){let e=Fe(t.profile),r;try{r=(await ne(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}`)}}as();Uc();Wc();hn();G();_e();hn();Le();Te();ko();import{hostname as GR}from"node:os";import{cancel as KR,confirm as vk,intro as HR,isCancel as Tk,log as En,multiselect as WR,outro as xk,password as qR,select as Zc,text as el}from"@clack/prompts";function So(t){KR(t),process.exit(1)}function Rn(t){return Tk(t)&&So("aborted"),t}function fs(t){return Tk(t)&&So("aborted"),typeof t=="string"?t:""}function ms(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Sk(t,e){try{let{secret:r}=await ti(t,e);return r}catch(r){throw r instanceof H&&r.status===404&&So("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 YR(t,e){if(Rn(await Zc({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 na(t,e);if(o.length>0)return Rn(await WR({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}));En.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){En.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return fs(await el({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 tl(t){HR("codepipe worker \u2014 set up this machine as a runner");let e=Ce(t.profile);e&&(En.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Rn(await vk({message:"re-register this worker?",initialValue:!1}))||So("keeping the existing registration"));let r=Xe(t.profile)??Xe(),n=fs(await el({message:"HUB URL",placeholder:ct,initialValue:z("HUB_URL")??r?.hubUrl??ct,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Rn(await Zc({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 Sk(n,a),En.success("account-issued registration token minted");else if(i==="login"){let d=await xn();a=(await Sn(n,d)).cliToken,s=await Sk(n,a),En.success("account-issued registration token minted")}else s=fs(await qR({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||So("a registration token is required");let c=await YR(n,a),l=fs(await el({message:"worker name",initialValue:GR(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=Rn(await Zc({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 $r({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),En.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Rn(await vk({message:"start the claim-loop now?",initialValue:!0}))){xk("registered. start later with `codepipe worker`.");return}xk("starting the claim-loop\u2026"),await go(t.profile?{profile:t.profile}:{})}function zR(){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 z("PROFILE")}var pe=zR();Ru(pe);Au();var De=new VR;De.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ue).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{ms()?await Hc({profile:pe}):await Mc({profile:pe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.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 nk({configPath:t.config,skipVerify:t.skipVerify===!0}):await Yy({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.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 Ku({...t,profile:pe})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await Vy({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});De.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Sg({profile:pe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.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 Cy({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.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 ck({profile:pe,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await ty({profile:pe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});De.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await Mc({profile:pe,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Ek=De.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Ek.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??z("HUB_URL")??Xe(pe)?.hubUrl??ct,r=t.token??z("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ms()){await tl({profile:pe});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=z("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??z("WORKER_NAME"),i=t.llm??z("WORKER_LLM");await $r({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...pe?{profile:pe}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ek.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Ce(pe)&&ms()){await tl({profile:pe});return}await go(pe?{profile:pe}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Rk=De.command("project").description("Manage CodePipe projects");Rk.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await pk({profile:pe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Rk.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 mk({...t,cliProfile:pe})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var rl=De.command("repo").description("Manage the project's git repositories");rl.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 wk({profile:pe,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});rl.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 bk({profile:pe,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});rl.command("list").description("List the project's repos").action(async()=>{try{await $k({profile:pe})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Ik=De.command("model").description("Project map (model/ in the Context Repo)");Ik.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 ac({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ik.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 cc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});De.parseAsync();