@code-partner/codepipe 0.8.2-dev.190.g9513b8f → 0.8.2-dev.192.g182c321

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 +141 -139
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,55 +1,55 @@
1
1
  #!/usr/bin/env node
2
- var Mh=Object.defineProperty;var k=(t,e)=>()=>(t&&(e=t(t=0)),e);var sc=(t,e)=>{for(var r in e)Mh(t,r,{get:e[r],enumerable:!0})};var je,Je,ji=k(()=>{"use strict";je="0.8.2-dev.190.g9513b8f",Je="https://hub.dev.codepipe.dev"});function to(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Uh&&t<=Xe}var Xe,Uh,ac=k(()=>{"use strict";ji();Xe=4,Uh=4});var cc=k(()=>{"use strict";ji()});function ro(t=4){return`# CodePipe Context Repo format version.
2
+ var ly=Object.defineProperty;var $=(t,e)=>()=>(t&&(e=t(t=0)),e);var Wi=(t,e)=>{for(var r in e)ly(t,r,{get:e[r],enumerable:!0})};var Ne,Ze,Yi=$(()=>{"use strict";Ne="0.8.2-dev.192.g182c321",Ze="https://hub.dev.codepipe.dev"});function lo(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=uy&&t<=et}var et,uy,Sc=$(()=>{"use strict";Yi();et=4,uy=4});var Tc=$(()=>{"use strict";Yi()});function uo(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 uc(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 dc(t,e=lc){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 pc(t,e=lc){return e.filter(r=>r.version>t)}var Qe,cn,lc,mc=k(()=>{"use strict";Qe=".codepipe-context.yaml",cn=".devpipe-context.yaml",lc=[{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",Qe]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Qe]},{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 no(t){return`model/facts/identity/${t}.yaml`}function Di(t){return`model/facts/events/${t}.yaml`}function fc(t){return`model/derived/correlates/${t}.yaml`}function Bh(t){return t===""?"root":t.replace(/\//g,"-")}function gc(t,e){return`model/derived/structure/${t}/${Bh(e)}.yaml`}function Li(t){return typeof t=="string"&&Kh.test(t)}function he(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(!Fh.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&n!=="system"||i===""?null:{level:n,repo:o,path:i}}function ye(t,e,r){return`${t}:${e}:${r}`}function Hh(t){return{...t,edges:pr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function hc(t){return mr(Hh(t))}function $t(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Mi(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function Fe(t){return typeof t=="string"&&t.length>0}function yc(t){let e=[];if(!$t(t))return{ok:!1,errors:["shard: not an object"]};Mi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Fe(t.repo)||e.push("repo: missing or empty"),Fe(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(!$t(o)){e.push(`nodes[${i}]: not an object`);return}let s=he(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&&!Li(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(!$t(o)){e.push(`edges[${i}]: not an object`);return}Gh.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!Fe(o.to)||!he(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!Fe(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 wc(t){let e=[];if(!$t(t))return{ok:!1,errors:["identity: not an object"]};if(Mi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Fe(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!Fe(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(!$t(n)){e.push(`entities[${o}]: not an object`);return}Li(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)})`),he(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),Fe(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),Fe(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!$t(i)||!he(i.key)||!Fe(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 bc(t){let e=[];return $t(t)?(Mi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Fe(t.taskKey)||e.push("taskKey: missing or empty"),t.origin!=="bootstrap"&&t.origin!=="pipeline"&&e.push("origin: expected bootstrap|pipeline"),(!Array.isArray(t.commits)||t.commits.some(r=>!Fe(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!$t(r)||!he(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Li(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 pr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Wh(t){return{...t,nodes:pr(t.nodes,e=>e.key),edges:pr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function qh(t){return{...t,entities:pr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:pr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Yh(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:pr(t.files,r=>r.key),...e?{links:e}:{}}}function ln(t){return Vh.test(t)?t:JSON.stringify(t)}function kc(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 $c(t){return t===null||["boolean","number","string"].includes(typeof t)}function _i(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function vc(t,e,r){if(Array.isArray(t)){for(let n of t)if($c(n))r.push(`${e}- ${kc(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=_i(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Ni(i,s,c,`${e} `,r)})}}return}for(let[n,o]of _i(t))Ni(n,o,e,e,r)}function Ni(t,e,r,n,o){if($c(e))o.push(`${r}${ln(t)}: ${kc(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${ln(t)}: []`):(o.push(`${r}${ln(t)}:`),vc(e,`${n} `,o));else{let i=_i(e);if(i.length===0)o.push(`${r}${ln(t)}: {}`);else{o.push(`${r}${ln(t)}:`);for(let[s,a]of i)Ni(s,a,`${n} `,`${n} `,o)}}}function mr(t){let e=[];return vc(t,"",e),e.join(`
5
+ `}function Cc(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 Ec(t,e=Rc){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 Ic(t,e=Rc){return e.filter(r=>r.version>t)}var tt,wn,Rc,Pc=$(()=>{"use strict";tt=".codepipe-context.yaml",wn=".devpipe-context.yaml",Rc=[{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",tt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[tt]},{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 po(t){return`model/facts/identity/${t}.yaml`}function kr(t){return`model/facts/events/${t}.yaml`}function Ac(t){return`model/derived/correlates/${t}.yaml`}function dy(t){return t===""?"root":t.replace(/\//g,"-")}function jc(t,e){return`model/derived/structure/${t}/${dy(e)}.yaml`}function Ji(t){return typeof t=="string"&&my.test(t)}function ce(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(!py.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!fy.includes(n)||i===""?null:{level:n,repo:o,path:i}}function br(t){return`task::${t}`}function fe(t,e,r){return`${t}:${e}:${r}`}function Nc(t){let e=[];return rt(t)?(fo(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(!rt(r)){e.push(`edges[${n}]: not an object`);return}_c.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),ce(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),ce(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 gy(t){return{...t,edges:yr(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function mo(t){return $r(gy(t))}function rt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function fo(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function Ke(t){return typeof t=="string"&&t.length>0}function Dc(t){let e=[];if(!rt(t))return{ok:!1,errors:["shard: not an object"]};fo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ke(t.repo)||e.push("repo: missing or empty"),Ke(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(!rt(o)){e.push(`nodes[${i}]: not an object`);return}let s=ce(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&&!Ji(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(!rt(o)){e.push(`edges[${i}]: not an object`);return}_c.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!Ke(o.to)||!ce(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!Ke(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 Lc(t){let e=[];if(!rt(t))return{ok:!1,errors:["identity: not an object"]};if(fo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ke(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!Ke(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(!rt(n)){e.push(`entities[${o}]: not an object`);return}Ji(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)})`),ce(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),Ke(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),Ke(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!rt(i)||!ce(i.key)||!Ke(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 go(t){let e=[];return rt(t)?(fo(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),Ke(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=>!Ke(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!rt(r)||!ce(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Ji(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 yr(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function hy(t){return{...t,nodes:yr(t.nodes,e=>e.key),edges:yr(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function yy(t){return{...t,entities:yr(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:yr(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function wy(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:yr(t.files,r=>r.key),...e?{links:e}:{}}}function kn(t){return ky.test(t)?t:JSON.stringify(t)}function Mc(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 Uc(t){return t===null||["boolean","number","string"].includes(typeof t)}function qi(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function Bc(t,e,r){if(Array.isArray(t)){for(let n of t)if(Uc(n))r.push(`${e}- ${Mc(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=qi(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Vi(i,s,c,`${e} `,r)})}}return}for(let[n,o]of qi(t))Vi(n,o,e,e,r)}function Vi(t,e,r,n,o){if(Uc(e))o.push(`${r}${kn(t)}: ${Mc(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${kn(t)}: []`):(o.push(`${r}${kn(t)}:`),Bc(e,`${n} `,o));else{let i=qi(e);if(i.length===0)o.push(`${r}${kn(t)}: {}`);else{o.push(`${r}${kn(t)}:`);for(let[s,a]of i)Vi(s,a,`${n} `,`${n} `,o)}}}function $r(t){let e=[];return Bc(t,"",e),e.join(`
6
6
  `)+`
7
- `}function xc(t){return mr(Wh(t))}function Sc(t){return mr(qh(t))}function Rc(t){return mr(Yh(t))}var Oi,Fh,Gh,Kh,dt,Vh,Ui=k(()=>{"use strict";Oi="model/derived/INDEX.yaml";Fh=["system","container","component","code","task","adr"],Gh=["contains","touched_by","correlates","relates","references","depends_on"],Kh=/^e_[0-9a-f]{8}$/;dt={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Vh=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var Tc=k(()=>{"use strict"});var zh,PR,Cc=k(()=>{"use strict";zh=[{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"]}],PR=zh.flatMap(t=>t.phases)});function Ht(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ic,Bi=k(()=>{"use strict";Ic=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function Ec(t,e){return e.toLowerCase().includes(t.toLowerCase())}function jc(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||Xh.every(o=>e.some(i=>Ec(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 Jh){let i=n.find(s=>Ec(o,s.id));if(i)return i.id}return n[0].id}var Ze,Pc,Ge,un,Ac,Fi,Gi,Jh,Xh,Ki=k(()=>{"use strict";Ze="claude",Pc=[Ze],Ge="opus",un="sonnet",Ac="haiku",Fi=[Ge,un,Ac],Gi={analyze:Ge,implement:Ge,"resolve-conflict":Ge,rework:Ge,estimate:un,build:un,"code-review":Ge,draft:un,index:Ge,backfill:Ge,analysis:Ge,chat:Ge},Jh=[Ge,un,Ac],Xh=Array.from(new Set(Object.values(Gi)))});function vt(t){return Qh.has(t)?!0:Zh.some(e=>t.startsWith(e))}function oo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Wt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function Hi(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function Lc(t,e){let r=oo(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Wt(r.id,"id")??n;if(!_c.test(o))throw new Error(`id must match ${_c} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Wt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=oo(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!_e.test(d))throw new Error(`env name "${d}" must match ${_e}`);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>Nc)throw new Error(`too many params (max ${Nc})`);let p=new Set;a=c.map((d,m)=>ey(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>Oc)throw new Error(`too many steps (max ${Oc})`);let u=l.map((p,d)=>{let m=oo(p,`steps[${d}]`),f=Wt(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=Wt(m.name,`steps[${d}].name`),y=Hi(m.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:f,...g?{name:g}:{},...y!==void 0?{timeout_sec:y}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function ey(t,e,r){let n=oo(t,`params[${e}]`),o=Wt(n.name,`params[${e}].name`);if(!o||!_e.test(o))throw new Error(`params[${e}].name must match ${_e}`);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=Wt(n.label,`params[${e}].label`),c=Wt(n.help,`params[${e}].help`),l=n.required===!0,u=Hi(n.min,`params[${e}].min`),p=Hi(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 Mc(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 _e,Qh,Zh,Dc,_c,Nc,Oc,Wi=k(()=>{"use strict";_e=/^[A-Z][A-Z0-9_]*$/,Qh=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Zh=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Dc=600,_c=/^[a-z0-9-]+$/,Nc=32,Oc=64});function Gc(t=ty){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Gc(r.groups));return e}function ry(t,e){let r=JSON.stringify(e);return Gc().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function Kc(t){let e=ry(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>Uc)return{ok:!1,error:`${e.id} must have \u2264 ${Uc} entries`};let s={};for(let[a,c]of i){if(!_e.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${_e}`};if(vt(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>Bc)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Bc} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var Uc,Bc,Fc,ty,Hc=k(()=>{"use strict";Wi();Bi();Ki();Ui();Uc=64,Bc=2e3,Fc=2e3,ty=[{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:[...Pc],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:[...Fi],help:"Overrides the recommended defaults for every role not listed below."},...Ic.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Fi],help:`recommended: ${Gi[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:Fc,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:Fc,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.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 ${dt.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 ${dt.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 ${dt.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 ${dt.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 ${dt.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 ${dt.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 Wc=k(()=>{"use strict"});var qc=k(()=>{"use strict"});var Yc=k(()=>{"use strict"});function Vc(t){return`codepipe-host-${t}`}var zc=k(()=>{"use strict"});function Jc(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 pt(t){return`${t}${ny}`}var qt,ny,Xc=k(()=>{"use strict";qt=/^[a-z][a-z0-9-]{1,30}$/,ny="-codepipe-ctx"});var Qc=k(()=>{"use strict"});var Zc=k(()=>{"use strict"});function fr(t){for(let e of oy){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var oy,el=k(()=>{"use strict";oy=[{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 tl=k(()=>{"use strict"});var rl=k(()=>{"use strict"});var nl=k(()=>{"use strict"});function ol(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function sl(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=ol(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(gr.test(r))return r;let n=ol(t);return gr.test(n)?n:qi}function al(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 pn(t){return`tasks/${t}/issue.yaml`}var il,io,qi,gr,Yi,qR,so,dn,cl=k(()=>{"use strict";il=["bug","feature","epic"],io="feature",qi="TASK",gr=/^[A-Z][A-Z0-9]{1,9}$/;Yi={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},qR=Yi.backlog,so="tracker/config.yaml",dn="tracker/counter"});var ll=k(()=>{"use strict"});function hr(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 ao(t){switch(t){case mn.gitlab:return"oauth2";case mn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var mn,Yt,ul=k(()=>{"use strict";mn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Yt="x-bitbucket-api-token-auth"});var dl=k(()=>{"use strict"});var pl=k(()=>{"use strict";ll();ul();dl()});var ml,W=k(()=>{"use strict";ac();cc();mc();Ui();Tc();Cc();Bi();Ki();Hc();Wi();Wc();qc();Yc();zc();Xc();Qc();Zc();el();tl();rl();nl();cl();pl();ml=20});function H(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var xe=k(()=>{"use strict"});import{existsSync as fl,renameSync as iy}from"node:fs";function Vt(t,e,r=n=>console.error(n)){if(fl(e)||!fl(t))return!1;try{return iy(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var co=k(()=>{"use strict"});import{existsSync as lo,readFileSync as gl,readdirSync as sy,writeFileSync as ay}from"node:fs";import{dirname as cy,join as xt}from"node:path";import{parse as ly}from"yaml";function uy(t=process.cwd()){let e=t;for(;;){if(lo(xt(e,et,"project.yaml")))return e;if(lo(xt(e,Vi,"project.yaml")))return Vt(xt(e,Vi),xt(e,et))&&py(e),e;let r=cy(e);if(r===e)return null;e=r}}function dy(t){let e=xt(t,et);return lo(e)?e:xt(t,Vi)}function py(t){let e=xt(t,".gitignore");if(!lo(e))return;let r=gl(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&&ay(e,n)}function ge(t=process.cwd()){let e=uy(t);if(!e)return null;let r=dy(e),n=my(gl(xt(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function hl(t,e,r){return sy(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 uo(t,e=process.cwd()){try{let r=ge(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function my(t){let e=ly(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 yl(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 et,Vi,tt=k(()=>{"use strict";co();et=".codepipe",Vi=".devpipe"});import{homedir as wl}from"node:os";import{mkdirSync as fy,readFileSync as gy,writeFileSync as hy,existsSync as zi}from"node:fs";import{dirname as kl,join as po,resolve as yy}from"node:path";import{fileURLToPath as wy}from"node:url";function $l(t){let e=po(bl,".env");if(zi(e)&&process.loadEnvFile(e),t){let r=po(bl,"profiles",t,".env");zi(r)&&process.loadEnvFile(r)}}function yr(t){let e=H("CONFIG");return e||(t?po(wl(),".codepipe","profiles",t,"config.json"):po(wl(),".codepipe","config.json"))}function Ke(t){let e=yr(t);if(!zi(e))return null;let r=gy(e,"utf-8");return JSON.parse(r)}function mt(t,e){let r=yr(e);fy(kl(r),{recursive:!0}),hy(r,JSON.stringify(t,null,2)+`
9
- `,{mode:384})}function mo(t){if(t)return{cfg:Ne(t),profile:t};let e;try{e=ge()?.spec.projectId||void 0}catch{}if(e){let r=Ke(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:Ne(void 0),profile:void 0}}function Ne(t){let e=Ke(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 ${yr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var bl,Ie=k(()=>{"use strict";xe();tt();bl=yy(kl(wy(import.meta.url)),"..")});import{homedir as Rl}from"node:os";import{existsSync as Tl,mkdirSync as Cl,readFileSync as Il,writeFileSync as El}from"node:fs";import{dirname as Pl,join as Al}from"node:path";function jl(t,e,r){let n=G(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},X(n)}function _l(t,e){let r=G(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],X(r),!0)}function Nl(t){return Object.keys(G(t)?.secrets??{}).sort()}function fo(t,e,r){let n=G(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,X(n),"pinned")}function Ol(t,e){let r=G(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],X(r),!0):!1}function rt(t){return Al(Rl(),".codepipe","secrets",`${t}.json`)}function G(t){let e=rt(t);return Tl(e)?JSON.parse(Il(e,"utf-8")):null}function X(t){let e=rt(t.projectId);Cl(Pl(e),{recursive:!0}),El(e,JSON.stringify(t,null,2)+`
10
- `,{mode:384})}function go(){return Al(Rl(),".codepipe","shared.json")}function Ji(){let t=go();return Tl(t)?JSON.parse(Il(t,"utf-8")):null}function Dl(t){let e=go();Cl(Pl(e),{recursive:!0}),El(e,JSON.stringify(t,null,2)+`
11
- `,{mode:384})}function wr(t){let e=G(t)?.claude?.oauthToken;return e||Ji()?.claude?.oauthToken}function fn(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 Xi){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function br(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Xi,oe=k(()=>{"use strict";Xi=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as by,existsSync as Ml,mkdirSync as ky,renameSync as Ul,statSync as $y,unlinkSync as vy}from"node:fs";import{Writable as xy}from"node:stream";import{join as Sy}from"node:path";function ho(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Ry(process.env[`${t}_MAX_BYTES`]??String(Bl.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Bl.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Ry(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 yo(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(Ty(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 Ty(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Cy(o)).join(" ");return`${r} ${t} ${n}`}function Cy(t){try{return JSON.stringify(t)}catch{return String(t)}}var Bl,kr,Qi=k(()=>{"use strict";Bl={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},kr=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&ky(e.dir,{recursive:!0}),this.currentPath=Sy(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 Fc(t){return $r(hy(t))}function Gc(t){return $r(yy(t))}function bn(t){return $r(wy(t))}var zi,wr,py,_c,my,fy,He,Oc,ky,Xi=$(()=>{"use strict";zi="model/derived/INDEX.yaml",wr="model/derived/relates.yaml";py=["system","container","component","code","task","adr"],_c=["contains","touched_by","correlates","relates","references","depends_on"],my=/^e_[0-9a-f]{8}$/;fy=["system","task","adr"];He={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Oc=2;ky=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});var Kc=$(()=>{"use strict"});var by,sR,Hc=$(()=>{"use strict";by=[{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"]}],sR=by.flatMap(t=>t.phases)});function Wt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Wc,Qi=$(()=>{"use strict";Wc=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat"]});function Yc(t,e){return e.toLowerCase().includes(t.toLowerCase())}function zc(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||vy.every(o=>e.some(i=>Yc(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 $y){let i=n.find(s=>Yc(o,s.id));if(i)return i.id}return n[0].id}var nt,qc,We,$n,Vc,Zi,es,$y,vy,ts=$(()=>{"use strict";nt="claude",qc=[nt],We="opus",$n="sonnet",Vc="haiku",Zi=[We,$n,Vc],es={analyze:We,implement:We,"resolve-conflict":We,rework:We,estimate:$n,build:$n,"code-review":We,draft:$n,index:We,backfill:We,analysis:We,chat:We},$y=[We,$n,Vc],vy=Array.from(new Set(Object.values(es)))});function xt(t){return xy.has(t)?!0:Sy.some(e=>t.startsWith(e))}function ho(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Yt(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function rs(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function el(t,e){let r=ho(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Yt(r.id,"id")??n;if(!Jc.test(o))throw new Error(`id must match ${Jc} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Yt(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=ho(r.env,"env");s={};for(let[d,m]of Object.entries(p)){if(!Oe.test(d))throw new Error(`env name "${d}" must match ${Oe}`);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>Xc)throw new Error(`too many params (max ${Xc})`);let p=new Set;a=c.map((d,m)=>Ty(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>Qc)throw new Error(`too many steps (max ${Qc})`);let u=l.map((p,d)=>{let m=ho(p,`steps[${d}]`),f=Yt(m.run,`steps[${d}].run`);if(!f||f.trim().length===0)throw new Error(`steps[${d}].run is required`);let g=Yt(m.name,`steps[${d}].name`),y=rs(m.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:f,...g?{name:g}:{},...y!==void 0?{timeout_sec:y}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function Ty(t,e,r){let n=ho(t,`params[${e}]`),o=Yt(n.name,`params[${e}].name`);if(!o||!Oe.test(o))throw new Error(`params[${e}].name must match ${Oe}`);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=Yt(n.label,`params[${e}].label`),c=Yt(n.help,`params[${e}].help`),l=n.required===!0,u=rs(n.min,`params[${e}].min`),p=rs(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 tl(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 Oe,xy,Sy,Zc,Jc,Xc,Qc,ns=$(()=>{"use strict";Oe=/^[A-Z][A-Z0-9_]*$/,xy=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),Sy=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];Zc=600,Jc=/^[a-z0-9-]+$/,Xc=32,Qc=64});function il(t=Ry){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...il(r.groups));return e}function Cy(t,e){let r=JSON.stringify(e);return il().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function sl(t){let e=Cy(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>rl)return{ok:!1,error:`${e.id} must have \u2264 ${rl} entries`};let s={};for(let[a,c]of i){if(!Oe.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${Oe}`};if(xt(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>nl)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${nl} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var rl,nl,ol,Ry,al=$(()=>{"use strict";ns();Qi();ts();Xi();rl=64,nl=2e3,ol=2e3,Ry=[{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:[...qc],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:[...Zi],help:"Overrides the recommended defaults for every role not listed below."},...Wc.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Zi],help:`recommended: ${es[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:ol,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:ol,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.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 ${He.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 ${He.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 ${He.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 ${He.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 ${He.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 ${He.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 cl=$(()=>{"use strict"});var ll=$(()=>{"use strict"});var ul=$(()=>{"use strict"});function dl(t){return`codepipe-host-${t}`}var pl=$(()=>{"use strict"});function ml(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 gt(t){return`${t}${Ey}`}var qt,Ey,fl=$(()=>{"use strict";qt=/^[a-z][a-z0-9-]{1,30}$/,Ey="-codepipe-ctx"});var gl=$(()=>{"use strict"});var hl=$(()=>{"use strict"});function vr(t){for(let e of Iy){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Iy,yl=$(()=>{"use strict";Iy=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}]});var wl=$(()=>{"use strict"});var kl=$(()=>{"use strict"});var bl=$(()=>{"use strict"});function $l(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function xl(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=$l(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(xr.test(r))return r;let n=$l(t);return xr.test(n)?n:os}function Sl(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 xn(t){return`tasks/${t}/issue.yaml`}var vl,yo,os,xr,is,vR,wo,vn,Tl=$(()=>{"use strict";vl=["bug","feature","epic"],yo="feature",os="TASK",xr=/^[A-Z][A-Z0-9]{1,9}$/;is={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},vR=is.backlog,wo="tracker/config.yaml",vn="tracker/counter"});var Rl=$(()=>{"use strict"});function Sr(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 ko(t){switch(t){case Sn.gitlab:return"oauth2";case Sn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Sn,Vt,Cl=$(()=>{"use strict";Sn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Vt="x-bitbucket-api-token-auth"});var El=$(()=>{"use strict"});var Il=$(()=>{"use strict";Rl();Cl();El()});var Pl,W=$(()=>{"use strict";Sc();Tc();Pc();Xi();Kc();Hc();Qi();ts();al();ns();cl();ll();ul();pl();fl();gl();hl();yl();wl();kl();bl();Tl();Il();Pl=20});function H(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Re=$(()=>{"use strict"});import{existsSync as Al,renameSync as Py}from"node:fs";function zt(t,e,r=n=>console.error(n)){if(Al(e)||!Al(t))return!1;try{return Py(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 bo=$(()=>{"use strict"});import{existsSync as $o,readFileSync as jl,readdirSync as Ay,writeFileSync as jy}from"node:fs";import{dirname as _y,join as St}from"node:path";import{parse as Ny}from"yaml";function Oy(t=process.cwd()){let e=t;for(;;){if($o(St(e,ot,"project.yaml")))return e;if($o(St(e,ss,"project.yaml")))return zt(St(e,ss),St(e,ot))&&Ly(e),e;let r=_y(e);if(r===e)return null;e=r}}function Dy(t){let e=St(t,ot);return $o(e)?e:St(t,ss)}function Ly(t){let e=St(t,".gitignore");if(!$o(e))return;let r=jl(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&&jy(e,n)}function ye(t=process.cwd()){let e=Oy(t);if(!e)return null;let r=Dy(e),n=My(jl(St(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function _l(t,e,r){return Ay(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 vo(t,e=process.cwd()){try{let r=ye(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function My(t){let e=Ny(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 Nl(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 ot,ss,it=$(()=>{"use strict";bo();ot=".codepipe",ss=".devpipe"});import{homedir as Ol}from"node:os";import{mkdirSync as Uy,readFileSync as By,writeFileSync as Fy,existsSync as as}from"node:fs";import{dirname as Ll,join as xo,resolve as Gy}from"node:path";import{fileURLToPath as Ky}from"node:url";function Ml(t){let e=xo(Dl,".env");if(as(e)&&process.loadEnvFile(e),t){let r=xo(Dl,"profiles",t,".env");as(r)&&process.loadEnvFile(r)}}function Tr(t){let e=H("CONFIG");return e||(t?xo(Ol(),".codepipe","profiles",t,"config.json"):xo(Ol(),".codepipe","config.json"))}function Ye(t){let e=Tr(t);if(!as(e))return null;let r=By(e,"utf-8");return JSON.parse(r)}function ht(t,e){let r=Tr(e);Uy(Ll(r),{recursive:!0}),Fy(r,JSON.stringify(t,null,2)+`
9
+ `,{mode:384})}function So(t){if(t)return{cfg:De(t),profile:t};let e;try{e=ye()?.spec.projectId||void 0}catch{}if(e){let r=Ye(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:De(void 0),profile:void 0}}function De(t){let e=Ye(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Tr(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var Dl,Pe=$(()=>{"use strict";Re();it();Dl=Gy(Ll(Ky(import.meta.url)),"..")});import{homedir as Gl}from"node:os";import{existsSync as Kl,mkdirSync as Hl,readFileSync as Wl,writeFileSync as Yl}from"node:fs";import{dirname as ql,join as Vl}from"node:path";function zl(t,e,r){let n=G(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},X(n)}function Jl(t,e){let r=G(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],X(r),!0)}function Xl(t){return Object.keys(G(t)?.secrets??{}).sort()}function To(t,e,r){let n=G(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,X(n),"pinned")}function Ql(t,e){let r=G(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],X(r),!0):!1}function st(t){return Vl(Gl(),".codepipe","secrets",`${t}.json`)}function G(t){let e=st(t);return Kl(e)?JSON.parse(Wl(e,"utf-8")):null}function X(t){let e=st(t.projectId);Hl(ql(e),{recursive:!0}),Yl(e,JSON.stringify(t,null,2)+`
10
+ `,{mode:384})}function Ro(){return Vl(Gl(),".codepipe","shared.json")}function cs(){let t=Ro();return Kl(t)?JSON.parse(Wl(t,"utf-8")):null}function Zl(t){let e=Ro();Hl(ql(e),{recursive:!0}),Yl(e,JSON.stringify(t,null,2)+`
11
+ `,{mode:384})}function Rr(t){let e=G(t)?.claude?.oauthToken;return e||cs()?.claude?.oauthToken}function Tn(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 ls){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Cr(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var ls,oe=$(()=>{"use strict";ls=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as Hy,existsSync as tu,mkdirSync as Wy,renameSync as ru,statSync as Yy,unlinkSync as qy}from"node:fs";import{Writable as Vy}from"node:stream";import{join as zy}from"node:path";function Co(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Jy(process.env[`${t}_MAX_BYTES`]??String(nu.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):nu.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Jy(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 Eo(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(Xy(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 Xy(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Qy(o)).join(" ");return`${r} ${t} ${n}`}function Qy(t){try{return JSON.stringify(t)}catch{return String(t)}}var nu,Er,us=$(()=>{"use strict";nu={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Er=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Wy(e.dir,{recursive:!0}),this.currentPath=zy(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
- `;by(this.currentPath,r,"utf-8")}asWritable(){return new xy({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||!Ml(this.currentPath)||$y(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Ml(n)&&(r>=this.cfg.maxFiles?vy(n):Ul(n,`${this.currentPath}.${r+1}`))}Ul(this.currentPath,`${this.currentPath}.1`)}}}});import{createHash as Iy}from"node:crypto";import{existsSync as Ey,readFileSync as Py}from"node:fs";import{homedir as Ay,hostname as Zi}from"node:os";import{join as jy}from"node:path";function Fl(t){return Iy("sha256").update(t).digest("hex").slice(0,12)}function _y(){let t=H("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=jy(Ay(),".claude","credentials.json");if(!Ey(e))return;let r=JSON.parse(Py(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 Gl(t){let e=_y(),r=H("ACCOUNT_ID")?.trim(),n=H("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=wr(t);return o?{accountId:`acct-${Fl(o)}`,label:n||Zi(),...e?{email:e}:{}}:{accountId:`acct-${Fl(`host:${Zi()}`)}`,label:n||Zi(),...e?{email:e}:{}}}var Kl=k(()=>{"use strict";xe();oe()});function bo(t){return t===429||t>=500}function Hl(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
14
- `+t.slice(t.length-e)}async function St(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),wo);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new Oe(`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(bo(i.status))throw new Oe(`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 ko(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),wo);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 Oe(`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(bo(s.status))throw new Oe(`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 Rt(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(),wo);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new Oe(`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(bo(s.status))throw new Oe(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await Ny(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 Ny(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function $o(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=Wl.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: ${Wl.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Tt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),wo);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 Oe(`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(bo(n.status))throw new Oe(`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 ql(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 Oy(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 es(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 He(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new rs(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new ts(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new ns(e)}return new os}var zt,Oe,wo,Wl,ts,rs,ns,os,Ct=k(()=>{"use strict";zt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},Oe=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},wo=5e3;Wl=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];ts=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 zt(`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()}`)}},rs=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 zt(`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(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!g.ok)continue;let y=await g.text();u.push(`### CI job: ${f.name}
15
-
16
- ${Hl(y,8e3)}`)}}return u.length===0?void 0:Hl(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()}`)}},ns=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 zt(`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=Oy(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()}`)}};os=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(es(e,r,"merge"))}async closePR(e,r,n){throw new Error(es(e,r,"close"))}async addPRComment(e,r,n){throw new Error(es(e,r,"comment"))}}});import{X509Certificate as zl}from"node:crypto";import{readFileSync as Dy}from"node:fs";import It from"node:tls";function Ly(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Ql(t=Xl){if(Yl)return;Yl=!0;let e=H("EXTRA_CA_FILE");if(!(!e||!Jl))try{let r=Ly(Dy(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}It.setDefaultCACertificates([...It.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 Zl(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 My(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 Uy(t,e,r){return new Promise((n,o)=>{let i=It.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 zl(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function is(t,e,r){return new Promise(n=>{let o=It.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 By(t){try{let e=await fetch(t);return e.ok?new zl(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function eu(t,e=443,r=Xl){let n=`${t}:${e}`,o=Vl.get(n);if(o)return o;let i=Fy(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Vl.set(n,i),i}async function Fy(t,e,r){if(!Jl)return!1;let n=8e3;if(await is(t,e,n))return!0;let o=await Uy(t,e,n),i=It.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=My(o);if(!c)break;let l=await By(c);if(!l)break;if(s.push(l.toString()),It.setDefaultCACertificates([...i,...s]),await is(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 is(t,e,n)}var Jl,Yl,Vl,Xl,tu=k(()=>{"use strict";xe();Jl=typeof It.getCACertificates=="function"&&typeof It.setDefaultCACertificates=="function",Yl=!1,Vl=new Map,Xl=t=>console.warn(t)});function iu(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function De(t,e,r){Ql();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(Zl(s)&&await eu(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Gy(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Ky(){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 ss(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Ky(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await De(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&&Gy(l.status,u)){await ru(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await ru(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Et(t){let e;try{e=await De(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 su(t){try{let e=await De(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function Hy(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=nu.get(o);if(i)return i;let s=await De(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 nu.set(o,l.id),l.id}async function au(t,e,r,n=gn){let o=await Hy(t,e,r,n);await ss(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 cu(t,e,r){return await(await ss(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function lu(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await ss(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function uu(t,e){let r=ou.get(e);if(r)return r;let n=await De(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 ou.set(e,i.id),i.id}async function du(t,e,r,n,o,i=gn){let s=await uu(t,e),a=await De(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 pu(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await De(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 gu(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 hu(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 yu(t,e){let r=e.stageField??gn,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=${fu}&$top=200`,s=await De(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>ku(c,r))}async function wu(t,e,r=gn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${fu}`,o=await De(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return ku(await o.json(),r)}async function bu(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${qy}&$top=500`,o=await De(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=gu(s.attachments);return c&&(a.attachments=c),a})}function Yy(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 ku(t,e=gn){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=gu(t.attachments);a&&(s.attachments=a);let c=Yy(t.links);return c&&(s.links=c),s}async function $u(t,e){let r=await Vy(t,e);return r.length>0?r:zy(t,e)}async function Vy(t,e){let r=await uu(t,e),n=await De(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:vu(s.bundle)});return i}async function zy(t,e){let r=`project: ${e}`,n=await De(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:vu(s.projectCustomField?.bundle)});return i}function vu(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var ru,gn,nu,ou,mu,Wy,fu,qy,Jt=k(()=>{"use strict";tu();ru=t=>new Promise(e=>setTimeout(e,t));gn="Stage",nu=new Map;ou=new Map;mu="attachments(id,name,url,size,mimeType)",Wy="links(direction,linkType(name),issues(idReadable))",fu=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${mu},${Wy}`,qy=`id,text,created,author(login),${mu}`});function We(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function $r(t){return t instanceof Oe}async function xu(t,e){let r=G(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 Et({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:We(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:We(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 St(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){$r(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:We(c)}),o.push({kind:"github",present:!0,ok:!1,detail:We(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 Rt(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){$r(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:We(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:We(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Tt(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){$r(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:We(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:We(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 ko(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){$r(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:We(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await ko(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){$r(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:We(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await ko(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){$r(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:We(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=wr(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 Pt(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 Pt(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 Su(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 vr=k(()=>{"use strict";oe();Ct();Jt()});import Jy from"node:http";import as from"node:crypto";function vo(){let t=cs(as.randomBytes(32)),e=cs(as.createHash("sha256").update(t).digest()),r=cs(as.randomBytes(32));return{verifier:t,challenge:e,state:r}}function us(t){let e=new URL(Xy);return e.search=new URLSearchParams({response_type:"code",client_id:Ru,redirect_uri:t.redirectUri,scope:Zy,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function tw(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 Tu(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 rw(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 ds(t){let e=await fetch(Qy,{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:Ru,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return rw(await e.json())}async function ps(t){let e=t.timeoutMs??ew,r=Jy.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=us({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(tw(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>ds({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Cu(t){let e=await ps(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 Ru,Xy,Qy,ls,Zy,ew,cs,ms=k(()=>{"use strict";Ru="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Xy="https://platform.claude.com/oauth/authorize",Qy="https://platform.claude.com/v1/oauth/token",ls="https://platform.claude.com/oauth/code/callback",Zy="org:create_api_key user:profile user:inference",ew=12e4,cs=t=>Buffer.from(t).toString("base64url")});async function Iu(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(H("ORIGIN")==="farm"||H("CLAUDE_AUTOLOGIN")==="0"){s("autologin_disabled");return}let a;try{a=await ps(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 Pt(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=G(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},X(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 Eu=k(()=>{"use strict";xe();vr();oe();ms()});function Pu(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?H("ORIGIN")==="farm"||H("CLAUDE_AUTOLOGIN")==="0"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Au(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}var ju=k(()=>{"use strict";xe()});import{spawn as nw}from"node:child_process";function Xt(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=nw(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var xo=k(()=>{"use strict"});import{setTimeout as ow}from"node:timers/promises";import iw from"ws";function So(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new iw(r)}async function At(t,e,r){return qe(t,e,"/projects",r)}async function _u(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new U(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Ro(t,e,r,n){return qe(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Nu(t,e,r,n){return qe(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Ou(t,e,r,n){return qe(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Du(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 U(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function To(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new U(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function fs(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new U(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Lu(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await fs(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 ow(r.delayMs??1500)}throw o}async function Mu(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 hn(e)}if(!r.ok)throw new U(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Uu(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new U(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Bu(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new U(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Fu(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 U(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function gs(t,e,r,n){return qe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Gu(t,e,r,n,o){return qe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function Ku(t,e,r,n,o){return qe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function Hu(t,e,r,n,o){return qe(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function yn(t,e,r,n){return qe(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function hs(t,e,r,n){await qe(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Wu(t,e,r,n){return qe(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function qu(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 U(o.status,s,a)}return s}async function Q(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new U(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function qe(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new U(o.status,s,a)}return s}var U,hn,we=k(()=>{"use strict";U=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};hn=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});function Vu(t){Yu=t}function wn(t,e="info"){Yu(t,e)}var Yu,Co=k(()=>{"use strict";Yu=t=>console.log(t)});import{homedir as sw,tmpdir as aw}from"node:os";import{existsSync as cw,mkdirSync as lw,mkdtempSync as uw,rmSync as dw}from"node:fs";import{join as bn}from"node:path";import{simpleGit as Io}from"simple-git";function Se(t,e,r){let n=r??bn(sw(),".codepipe","repos");return bn(n,t,e)}async function Zt(t,e,r={}){let n=Se(t,e.name,r.baseDir),o=r.cloneUrlOverride??$n(e);if(!cw(bn(n,".git"))){lw(n,{recursive:!0});let a=Io();wn(`[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=Io(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 Qt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function er(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&&wn(`[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 Qt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Qt(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([...Eo,"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 Qt(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Qt(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 zu(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,()=>er(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 Qt(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([...Eo,"cherry-pick",d])}catch(b){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let h=b instanceof Error?b.message:String(b);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 b=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(b)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:g,pushed:y}}async function Ju(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 Xu(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await kn(t,i,()=>er(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 Qu(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,()=>er(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));await t.fetch().catch(()=>{});let d=`origin/${a}`;if(await Qt(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=uw(bn(aw(),"codepipe-apply-")),g=bn(f,"wt");try{await t.raw(["worktree","add","--detach",g,d]);let y=Io(g);try{await y.raw([...Eo,"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 b=(await y.revparse(["HEAD"])).trim();return await t.raw(["branch","-f",c,b]),{commit:b,branch:c}}finally{await t.raw(["worktree","remove","--force",g]).catch(()=>{}),dw(f,{recursive:!0,force:!0}),await t.raw(["worktree","prune"]).catch(()=>{})}}async function Zu(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await Qt(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(`
13
+ `;Hy(this.currentPath,r,"utf-8")}asWritable(){return new Vy({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||!tu(this.currentPath)||Yy(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;tu(n)&&(r>=this.cfg.maxFiles?qy(n):ru(n,`${this.currentPath}.${r+1}`))}ru(this.currentPath,`${this.currentPath}.1`)}}}});import{createHash as Zy}from"node:crypto";import{existsSync as ew,readFileSync as tw}from"node:fs";import{homedir as rw,hostname as ds}from"node:os";import{join as nw}from"node:path";function ou(t){return Zy("sha256").update(t).digest("hex").slice(0,12)}function ow(){let t=H("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=nw(rw(),".claude","credentials.json");if(!ew(e))return;let r=JSON.parse(tw(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 iu(t){let e=ow(),r=H("ACCOUNT_ID")?.trim(),n=H("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=Rr(t);return o?{accountId:`acct-${ou(o)}`,label:n||ds(),...e?{email:e}:{}}:{accountId:`acct-${ou(`host:${ds()}`)}`,label:n||ds(),...e?{email:e}:{}}}var su=$(()=>{"use strict";Re();oe()});function Po(t){return t===429||t>=500}function au(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
14
+ `+t.slice(t.length-e)}async function Tt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Io);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new Le(`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(Po(i.status))throw new Le(`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 Ao(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Io);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 Le(`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(Po(s.status))throw new Le(`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 Rt(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(),Io);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new Le(`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(Po(s.status))throw new Le(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await iw(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 iw(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=cu.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: ${cu.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function Ct(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Io);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 Le(`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(Po(n.status))throw new Le(`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 lu(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 sw(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 ps(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 fs(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new ms(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new gs(e)}return new hs}var Jt,Le,Io,cu,ms,fs,gs,hs,Et=$(()=>{"use strict";Jt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},Le=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Io=5e3;cu=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];ms=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 Jt(`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()}`)}},fs=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 Jt(`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(g=>g.conclusion==="failure")){let g=await fetch(`${o}/actions/jobs/${f.id}/logs`,{headers:n});if(!g.ok)continue;let y=await g.text();u.push(`### CI job: ${f.name}
15
+
16
+ ${au(y,8e3)}`)}}return u.length===0?void 0:au(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()}`)}},gs=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 Jt(`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=sw(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()}`)}};hs=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(ps(e,r,"merge"))}async closePR(e,r,n){throw new Error(ps(e,r,"close"))}async addPRComment(e,r,n){throw new Error(ps(e,r,"comment"))}}});import{X509Certificate as pu}from"node:crypto";import{readFileSync as aw}from"node:fs";import It from"node:tls";function cw(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function gu(t=fu){if(uu)return;uu=!0;let e=H("EXTRA_CA_FILE");if(!(!e||!mu))try{let r=cw(aw(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}It.setDefaultCACertificates([...It.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 hu(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 lw(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 uw(t,e,r){return new Promise((n,o)=>{let i=It.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 pu(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function ys(t,e,r){return new Promise(n=>{let o=It.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 dw(t){try{let e=await fetch(t);return e.ok?new pu(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function yu(t,e=443,r=fu){let n=`${t}:${e}`,o=du.get(n);if(o)return o;let i=pw(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return du.set(n,i),i}async function pw(t,e,r){if(!mu)return!1;let n=8e3;if(await ys(t,e,n))return!0;let o=await uw(t,e,n),i=It.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=lw(o);if(!c)break;let l=await dw(c);if(!l)break;if(s.push(l.toString()),It.setDefaultCACertificates([...i,...s]),await ys(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 ys(t,e,n)}var mu,uu,du,fu,wu=$(()=>{"use strict";Re();mu=typeof It.getCACertificates=="function"&&typeof It.setDefaultCACertificates=="function",uu=!1,du=new Map,fu=t=>console.warn(t)});function vu(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function Me(t,e,r){gu();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(hu(s)&&await yu(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function mw(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function fw(){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 ws(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=fw(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await Me(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&&mw(l.status,u)){await ku(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await ku(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Pt(t){let e;try{e=await Me(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function xu(t){try{let e=await Me(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function gw(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=bu.get(o);if(i)return i;let s=await Me(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 bu.set(o,l.id),l.id}async function Su(t,e,r,n=Rn){let o=await gw(t,e,r,n);await ws(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 Tu(t,e,r){return await(await ws(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Ru(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await ws(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Cu(t,e){let r=$u.get(e);if(r)return r;let n=await Me(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 $u.set(e,i.id),i.id}async function Eu(t,e,r,n,o,i=Rn){let s=await Cu(t,e),a=await Me(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 Iu(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await Me(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 ju(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 _u(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 Nu(t,e){let r=e.stageField??Rn,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${Au}&$top=200`,s=await Me(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Lu(c,r))}async function Ou(t,e,r=Rn){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Au}`,o=await Me(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Lu(await o.json(),r)}async function Du(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${yw}&$top=500`,o=await Me(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=ju(s.attachments);return c&&(a.attachments=c),a})}function ww(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 Lu(t,e=Rn){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=ju(t.attachments);a&&(s.attachments=a);let c=ww(t.links);return c&&(s.links=c),s}async function Mu(t,e){let r=await kw(t,e);return r.length>0?r:bw(t,e)}async function kw(t,e){let r=await Cu(t,e),n=await Me(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:Uu(s.bundle)});return i}async function bw(t,e){let r=`project: ${e}`,n=await Me(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:Uu(s.projectCustomField?.bundle)});return i}function Uu(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var ku,Rn,bu,$u,Pu,hw,Au,yw,Xt=$(()=>{"use strict";wu();ku=t=>new Promise(e=>setTimeout(e,t));Rn="Stage",bu=new Map;$u=new Map;Pu="attachments(id,name,url,size,mimeType)",hw="links(direction,linkType(name),issues(idReadable))",Au=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Pu},${hw}`,yw=`id,text,created,author(login),${Pu}`});function Ve(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function Ir(t){return t instanceof Le}async function Bu(t,e){let r=G(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 Pt({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:Ve(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Ve(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 Tt(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Ir(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:Ve(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Ve(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 Rt(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){Ir(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:Ve(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Ve(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Ct(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Ir(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:Ve(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Ve(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 Ao(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){Ir(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:Ve(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Ao(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){Ir(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:Ve(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Ao(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){Ir(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:Ve(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=Rr(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await At(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 At(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 Fu(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 Pr=$(()=>{"use strict";oe();Et();Xt()});import $w from"node:http";import ks from"node:crypto";function _o(){let t=bs(ks.randomBytes(32)),e=bs(ks.createHash("sha256").update(t).digest()),r=bs(ks.randomBytes(32));return{verifier:t,challenge:e,state:r}}function vs(t){let e=new URL(vw);return e.search=new URLSearchParams({response_type:"code",client_id:Gu,redirect_uri:t.redirectUri,scope:Sw,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function Rw(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 Ku(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 Cw(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 xs(t){let e=await fetch(xw,{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:Gu,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return Cw(await e.json())}async function Ss(t){let e=t.timeoutMs??Tw,r=$w.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(Rw(m.searchParams,t.state))}catch(f){u(f)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>xs({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function Hu(t){let e=await Ss(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 Gu,vw,xw,$s,Sw,Tw,bs,Ts=$(()=>{"use strict";Gu="9d1c250a-e61b-44d9-88ed-5944d1962f5e",vw="https://platform.claude.com/oauth/authorize",xw="https://platform.claude.com/v1/oauth/token",$s="https://platform.claude.com/oauth/code/callback",Sw="org:create_api_key user:profile user:inference",Tw=12e4,bs=t=>Buffer.from(t).toString("base64url")});async function Wu(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(H("ORIGIN")==="farm"||H("CLAUDE_AUTOLOGIN")==="0"){s("autologin_disabled");return}let a;try{a=await Ss(_o())}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 At(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=G(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},X(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 Yu=$(()=>{"use strict";Re();Pr();oe();Ts()});function qu(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?H("ORIGIN")==="farm"||H("CLAUDE_AUTOLOGIN")==="0"||e?"none":"open":r?.ok===!0?"rearm":"none"}function Vu(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}var zu=$(()=>{"use strict";Re()});import{spawn as Ew}from"node:child_process";function Qt(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Ew(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var No=$(()=>{"use strict"});import{setTimeout as Iw}from"node:timers/promises";import Pw from"ws";function Oo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Pw(r)}async function jt(t,e,r){return ze(t,e,"/projects",r)}async function Ju(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new U(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Do(t,e,r,n){return ze(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Xu(t,e,r,n){return ze(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Qu(t,e,r,n){return ze(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Zu(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 U(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function Lo(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new U(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Rs(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new U(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function ed(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Rs(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 Iw(r.delayMs??1500)}throw o}async function td(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 Cn(e)}if(!r.ok)throw new U(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function rd(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new U(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function nd(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new U(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function od(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 U(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Cs(t,e,r,n){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function id(t,e,r,n,o){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function sd(t,e,r,n,o){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function ad(t,e,r,n,o){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function En(t,e,r,n){return ze(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Es(t,e,r,n){await ze(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function cd(t,e,r,n){return ze(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function ld(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 U(o.status,s,a)}return s}async function Q(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new U(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function ze(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 U(o.status,s,a)}return s}var U,Cn,we=$(()=>{"use strict";U=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};Cn=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});function dd(t){ud=t}function Zt(t,e="info"){ud(t,e)}var ud,Mo=$(()=>{"use strict";ud=t=>console.log(t)});import{homedir as Aw,tmpdir as jw}from"node:os";import{existsSync as _w,mkdirSync as Nw,mkdtempSync as Ow,rmSync as Dw}from"node:fs";import{join as In}from"node:path";import{simpleGit as Uo}from"simple-git";function $e(t,e,r){let n=r??In(Aw(),".codepipe","repos");return In(n,t,e)}async function tr(t,e,r={}){let n=$e(t,e.name,r.baseDir),o=r.cloneUrlOverride??An(e);if(!_w(In(n,".git"))){Nw(n,{recursive:!0});let a=Uo();Zt(`[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=Uo(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 er(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function rr(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&&Zt(`[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 er(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await er(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([...Bo,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function Pn(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await er(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await er(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 pd(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 Pn(t,i,()=>rr(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 er(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([...Bo,"cherry-pick",d])}catch(k){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let h=k instanceof Error?k.message:String(k);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 k=p?["--force-with-lease","-u","origin",a]:["-u","origin",a];await t.push(k)}return await t.push([n,"--delete",o]).catch(()=>{}),{commit:g,pushed:y}}async function md(t,e,r){let n=r.force?["--force-with-lease","-u","origin",r.branchName]:["-u","origin",r.branchName];return await t.push(n),{pushed:!0}}async function fd(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await Pn(t,i,()=>rr(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 gd(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,baseRef:a,branchName:c,commitMessage:l,defaultBranch:u}=r,p=await Pn(t,i,()=>rr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));await t.fetch().catch(()=>{});let d=`origin/${a}`;if(await er(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=Ow(In(jw(),"codepipe-apply-")),g=In(f,"wt");try{await t.raw(["worktree","add","--detach",g,d]);let y=Uo(g);try{await y.raw([...Bo,"cherry-pick",p])}catch(h){await y.raw(["cherry-pick","--abort"]).catch(()=>{});let b=h instanceof Error?h.message:String(h);throw new Error(`cherry-pick of ${i.slice(0,10)} onto ${a} hit conflicts
24
+ ${b.trim()}`)}let k=(await y.revparse(["HEAD"])).trim();return await t.raw(["branch","-f",c,k]),{commit:k,branch:c}}finally{await t.raw(["worktree","remove","--force",g]).catch(()=>{}),Dw(f,{recursive:!0,force:!0}),await t.raw(["worktree","prune"]).catch(()=>{})}}async function hd(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await er(t,i))throw new Error(`rewrite_cluster_branch: ${i} not found upstream`);let s=`origin/${r.defaultBranch??"main"}`,a=(await t.raw(["merge-base",i,s])).trim(),c=(await t.raw(["rev-list","--reverse",`${a}..${i}`])).split(`
25
25
  `).map(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(y=>y.trim().toUpperCase()).filter(y=>y.length>0).some(y=>l.has(y))?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([...Eo,"cherry-pick","--allow-empty","--keep-redundant-commits",m])}catch(f){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let g=f instanceof Error?f.message:String(f);throw new Error(`rewrite_cluster_branch: replaying ${m.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
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 ed(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 $n(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 td(t){return(await Io().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 rd(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var Eo,xr=k(()=>{"use strict";Co();Eo=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{existsSync as Ao,readFileSync as pw,writeFileSync as mw}from"node:fs";import{join as rr}from"node:path";import{simpleGit as Po}from"simple-git";function od(t){return rr(t,fw)}function nr(t){let e=od(t);if(!Ao(e))return{};try{return JSON.parse(pw(e,"utf-8"))}catch{return{}}}function ws(t,e){mw(od(t),JSON.stringify(e,null,2)+`
29
- `)}async function id(t,e,r,n,o){let i;try{i=await gs(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(b=>b.name===d.repoName);if(!m)return{ok:!1,message:`repo "${d.repoName}" not in project.yaml \u2014 run /sync`};let f=rr(t.root,m.mountAs);if(!Ao(rr(f,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Po(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=Po(d.dir),f=await gw(m),g=d.claimRepo;try{await m.fetch()}catch(h){return await ys(a,o),{ok:!1,message:`fetch failed in ${d.spec.mountAs}: ${tr(h)}`}}let y=`origin/${g.baseRef}`,b;try{b=await er(m,{contextRepoCloneUrl:g.contextRepoCloneUrl,deliveryRef:g.deliveryRef,deliverySha:g.deliverySha,baseSha:g.baseSha,commitMessage:g.commitMessage})}catch(h){return await ys(a,o),{ok:!1,message:`fetch delivery failed in ${d.spec.mountAs}: ${tr(h)}`}}a.push({git:m,dir:d.dir,mountAs:d.spec.mountAs,originalRef:f,branch:g.branchName,baseSha:y,deliveryCommit:b,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([...nd,"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([...nd,"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 ys(a,o),{ok:!1,message:`apply failed in ${d.mountAs}: ${tr(m)} (rolled back all repos)`}}let l=nr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},ws(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}
26
+ `).map(y=>y.trim().toUpperCase()).filter(y=>y.length>0).some(y=>l.has(y))?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([...Bo,"cherry-pick","--allow-empty","--keep-redundant-commits",m])}catch(f){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let g=f instanceof Error?f.message:String(f);throw new Error(`rewrite_cluster_branch: replaying ${m.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
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 yd(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 An(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}async function wd(t){return(await Uo().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 kd(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var Bo,Ar=$(()=>{"use strict";Mo();Bo=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{existsSync as Go,readFileSync as Lw,writeFileSync as Mw}from"node:fs";import{join as or}from"node:path";import{simpleGit as Fo}from"simple-git";function $d(t){return or(t,Uw)}function ir(t){let e=$d(t);if(!Go(e))return{};try{return JSON.parse(Lw(e,"utf-8"))}catch{return{}}}function Ps(t,e){Mw($d(t),JSON.stringify(e,null,2)+`
29
+ `)}async function vd(t,e,r,n,o){let i;try{i=await Cs(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(k=>k.name===d.repoName);if(!m)return{ok:!1,message:`repo "${d.repoName}" not in project.yaml \u2014 run /sync`};let f=or(t.root,m.mountAs);if(!Go(or(f,".git")))return{ok:!1,message:`${m.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Fo(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=Fo(d.dir),f=await Bw(m),g=d.claimRepo;try{await m.fetch()}catch(h){return await Is(a,o),{ok:!1,message:`fetch failed in ${d.spec.mountAs}: ${nr(h)}`}}let y=`origin/${g.baseRef}`,k;try{k=await rr(m,{contextRepoCloneUrl:g.contextRepoCloneUrl,deliveryRef:g.deliveryRef,deliverySha:g.deliverySha,baseSha:g.baseSha,commitMessage:g.commitMessage})}catch(h){return await Is(a,o),{ok:!1,message:`fetch delivery failed in ${d.spec.mountAs}: ${nr(h)}`}}a.push({git:m,dir:d.dir,mountAs:d.spec.mountAs,originalRef:f,branch:g.branchName,baseSha:y,deliveryCommit:k,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([...bd,"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([...bd,"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 Is(a,o),{ok:!1,message:`apply failed in ${d.mountAs}: ${nr(m)} (rolled back all repos)`}}let l=ir(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Ps(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 sd(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=rr(t.root,l.mountAs);if(!Ao(rr(u,".git")))return{ok:!1,message:`${l.mountAs}/ not cloned \u2014 run /sync first`};n.push({git:Po(u),dir:u,spec:l,cr:c})}let o=[],i=[];for(let c of n)try{let{commit:l}=await Qu(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}: ${tr(l)}`}}try{await gs(t.hubUrl,t.cliToken,t.projectId,e.taskKey)}catch(c){return{ok:!1,message:`branch created but claim failed: ${tr(c)} \u2014 retried on the next reconnect`,branches:o.map(l=>l.branch)}}let s=nr(t.contextDir);s[e.taskKey]={mode:"apply",claimedAt:new Date().toISOString(),repos:i},ws(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 xd(t,e,r){let n=[];for(let c of e.repos){let l=t.repos.find(p=>p.name===c.repoName);if(!l)return{ok:!1,message:`repo "${c.repoName}" not in project.yaml \u2014 run /sync`};let u=or(t.root,l.mountAs);if(!Go(or(u,".git")))return{ok:!1,message:`${l.mountAs}/ not cloned \u2014 run /sync first`};n.push({git:Fo(u),dir:u,spec:l,cr:c})}let o=[],i=[];for(let c of n)try{let{commit:l}=await gd(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}: ${nr(l)}`}}try{await Cs(t.hubUrl,t.cliToken,t.projectId,e.taskKey)}catch(c){return{ok:!1,message:`branch created but claim failed: ${nr(c)} \u2014 retried on the next reconnect`,branches:o.map(l=>l.branch)}}let s=ir(t.contextDir);s[e.taskKey]={mode:"apply",claimedAt:new Date().toISOString(),repos:i},Ps(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 bs(t,e){let r=nr(t);r[e]&&(delete r[e],ws(t,r))}async function ys(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}: ${tr(n)} \u2014 check manually`)}}async function ad(t,e,r){let o=nr(t.contextDir)[e];if(o){for(let i of o.repos){let s=rr(t.root,i.mountAs);if(!Ao(rr(s,".git")))continue;let a=Po(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}: ${tr(u)} \u2014 check manually`)}}bs(t.contextDir,e)}}async function gw(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function tr(t){return t instanceof Error?t.message.trim():String(t)}var nd,fw,ks=k(()=>{"use strict";we();xr();nd=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],fw="apply-queue.json"});import{existsSync as hw}from"node:fs";import{join as yw}from"node:path";import{simpleGit as ww}from"simple-git";async function cd(t,e){if(!hw(yw(t,".git")))return{status:"skipped"};let r=ww(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${bw(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 bw(t){return t instanceof Error?t.message.trim():String(t)}var ld=k(()=>{"use strict"});import{existsSync as ud,readFileSync as dd,readdirSync as kw,statSync as $w}from"node:fs";import{join as $s}from"node:path";import{parse as pd}from"yaml";function jo(t){let e=$s(t,"actions"),r=[],n=[];if(!ud(e))return{defs:r,errors:n};let o;try{o=kw(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=$s(e,s);try{if(!$w(a).isFile())continue;let c=Lc(s,pd(dd(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 md(t){let e={},r=$s(t,"project.yaml");if(!ud(r))return e;let n;try{n=pd(dd(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))!_e.test(i)||vt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var vs=k(()=>{"use strict";W()});import{existsSync as xs,readFileSync as fd,readdirSync as vw,watch as xw}from"node:fs";import{join as vn}from"node:path";var _o,gd=k(()=>{"use strict";vs();_o=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,vn(this.contextDir,"prompts"),vn(this.contextDir,"actions")];for(let n of r)if(xs(n))try{let o=xw(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=jo(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=vn(this.contextDir,e);if(!xs(r))return null;try{return fd(r,"utf-8")}catch{return null}}readPrompts(){let e=vn(this.contextDir,"prompts"),r={};if(!xs(e))return r;let n;try{n=vw(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=fd(vn(e,o),"utf-8")}catch{}}return r}}});import{existsSync as jt,mkdirSync as hd,readFileSync as Ss,writeFileSync as Sr}from"node:fs";import{homedir as Sw}from"node:os";import{join as nt}from"node:path";import{simpleGit as Rw}from"simple-git";function xn(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=nt(t,o);jt(s)||(Sr(s,i),r.push(o))}return r}function or(t,e,r){let n=nt(Sw(),".codepipe","profiles",t,"context-config");return hd(n,{recursive:!0}),Sr(nt(n,"project.yaml"),e.projectYaml),Sr(nt(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function No(t,e,r){if(jt(e))for(let n of Rr){let o=nt(e,n),i=nt(t,n);if(!(!jt(o)||jt(i)))try{Sr(i,Ss(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 Tr(t){let e=nt(t,".gitignore"),r=jt(e)?Ss(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Rr.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 As(t,e){let r=ir(t);r[e]&&(delete r[e],Ps(t,r))}async function Is(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}: ${nr(n)} \u2014 check manually`)}}async function Sd(t,e,r){let o=ir(t.contextDir)[e];if(o){for(let i of o.repos){let s=or(t.root,i.mountAs);if(!Go(or(s,".git")))continue;let a=Fo(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}: ${nr(u)} \u2014 check manually`)}}As(t.contextDir,e)}}async function Bw(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function nr(t){return t instanceof Error?t.message.trim():String(t)}var bd,Uw,js=$(()=>{"use strict";we();Ar();bd=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Uw="apply-queue.json"});import{existsSync as Fw}from"node:fs";import{join as Gw}from"node:path";import{simpleGit as Kw}from"simple-git";async function Td(t,e){if(!Fw(Gw(t,".git")))return{status:"skipped"};let r=Kw(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Hw(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 Hw(t){return t instanceof Error?t.message.trim():String(t)}var Rd=$(()=>{"use strict"});import{existsSync as Cd,readFileSync as Ed,readdirSync as Ww,statSync as Yw}from"node:fs";import{join as _s}from"node:path";import{parse as Id}from"yaml";function Ko(t){let e=_s(t,"actions"),r=[],n=[];if(!Cd(e))return{defs:r,errors:n};let o;try{o=Ww(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=_s(e,s);try{if(!Yw(a).isFile())continue;let c=el(s,Id(Ed(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 Pd(t){let e={},r=_s(t,"project.yaml");if(!Cd(r))return e;let n;try{n=Id(Ed(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))!Oe.test(i)||xt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var Ns=$(()=>{"use strict";W()});import{existsSync as Os,readFileSync as Ad,readdirSync as qw,watch as Vw}from"node:fs";import{join as jn}from"node:path";var Ho,jd=$(()=>{"use strict";Ns();Ho=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,jn(this.contextDir,"prompts"),jn(this.contextDir,"actions")];for(let n of r)if(Os(n))try{let o=Vw(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=Ko(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=jn(this.contextDir,e);if(!Os(r))return null;try{return Ad(r,"utf-8")}catch{return null}}readPrompts(){let e=jn(this.contextDir,"prompts"),r={};if(!Os(e))return r;let n;try{n=qw(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Ad(jn(e,o),"utf-8")}catch{}}return r}}});import{existsSync as _t,mkdirSync as _d,readFileSync as Ds,writeFileSync as jr}from"node:fs";import{homedir as zw}from"node:os";import{join as at}from"node:path";import{simpleGit as Jw}from"simple-git";function _n(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=at(t,o);_t(s)||(jr(s,i),r.push(o))}return r}function sr(t,e,r){let n=at(zw(),".codepipe","profiles",t,"context-config");return _d(n,{recursive:!0}),jr(at(n,"project.yaml"),e.projectYaml),jr(at(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Wo(t,e,r){if(_t(e))for(let n of _r){let o=at(e,n),i=at(t,n);if(!(!_t(o)||_t(i)))try{jr(i,Ds(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 Nr(t){let e=at(t,".gitignore"),r=_t(e)?Ds(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(_r.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
34
34
  `)?"":`
35
- `;return Sr(e,r+i+Tw.join(`
35
+ `;return jr(e,r+i+Xw.join(`
36
36
  `)+`
37
- `),!0}async function yd(t,e){try{if(!jt(nt(t,".git")))return;let r=Rw(t),n=(await r.raw(["ls-files","--",...Rr])).split(`
38
- `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;Tr(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 Cs(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 Rs(t){let e=new Map;for(let r of Rr){let n=nt(t,r);jt(n)&&e.set(r,Ss(n))}return e}function Ts(t,e){hd(t,{recursive:!0});for(let[r,n]of e){let o=nt(t,r);jt(o)||Sr(o,n)}}var Rr,Tw,ft=k(()=>{"use strict";ot();Rr=["project.yaml","regimen.yaml"];Tw=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Cw,mkdirSync as Iw,rmSync as Ew,writeFileSync as Is}from"node:fs";import{dirname as Pw,isAbsolute as Aw,join as kd,normalize as Lo}from"node:path";import{simpleGit as $d}from"simple-git";async function Es(t,e){let r=Lo(t),o=(Do.get(r)??Promise.resolve()).catch(()=>{}).then(e);Do.set(r,o);try{return await o}finally{Do.get(r)===o&&Do.delete(r)}}async function Ee(t,e,r){return Es(t,()=>Ps(t,e,r))}async function Ps(t,e,r){if(!Cw(kd(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=me(t,a.path);if(a.deleted){Ew(c,{force:!0});continue}Iw(Pw(c),{recursive:!0}),a.encoding==="base64"?Is(c,Buffer.from(a.content,"base64")):Is(c,a.content)}let n=$d(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+=Oo)await n.raw(["add","-A","-f","--",...o.slice(a,a+Oo)]);for(let a=0;a<i.length;a+=Oo)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+Oo)]);await n.raw(["reset","-q","--",...Rr]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await Cs(t))}async function Cs(t){let e=$d(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=wd;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 Ow(e);if(i.length>0&&i.every(a=>jw.has(a)||bd.test(a)||_w.test(a))){for(let a of i)bd.test(a)?await Nw(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 ${wd} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Nw(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);Is(me(e,r),i.join(`
37
+ `),!0}async function Nd(t,e){try{if(!_t(at(t,".git")))return;let r=Jw(t),n=(await r.raw(["ls-files","--",..._r])).split(`
38
+ `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;Nr(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 Us(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 Ls(t){let e=new Map;for(let r of _r){let n=at(t,r);_t(n)&&e.set(r,Ds(n))}return e}function Ms(t,e){_d(t,{recursive:!0});for(let[r,n]of e){let o=at(t,r);_t(o)||jr(o,n)}}var _r,Xw,yt=$(()=>{"use strict";Je();_r=["project.yaml","regimen.yaml"];Xw=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as Qw,mkdirSync as Zw,rmSync as ek,writeFileSync as Bs}from"node:fs";import{dirname as tk,isAbsolute as rk,join as Ld,normalize as Vo}from"node:path";import{simpleGit as Md}from"simple-git";async function Fs(t,e){let r=Vo(t),o=(qo.get(r)??Promise.resolve()).catch(()=>{}).then(e);qo.set(r,o);try{return await o}finally{qo.get(r)===o&&qo.delete(r)}}async function ke(t,e,r){return Fs(t,()=>Gs(t,e,r))}async function Gs(t,e,r){if(!Qw(Ld(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=ge(t,a.path);if(a.deleted){ek(c,{force:!0});continue}Zw(tk(c),{recursive:!0}),a.encoding==="base64"?Bs(c,Buffer.from(a.content,"base64")):Bs(c,a.content)}let n=Md(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+=Yo)await n.raw(["add","-A","-f","--",...o.slice(a,a+Yo)]);for(let a=0;a<i.length;a+=Yo)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+Yo)]);await n.raw(["reset","-q","--",..._r]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await Us(t))}async function Us(t){let e=Md(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Od;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 sk(e);if(i.length>0&&i.every(a=>nk.has(a)||Dd.test(a)||ok.test(a))){for(let a of i)Dd.test(a)?await ik(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 ${Od} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function ik(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);Bs(ge(e,r),i.join(`
40
40
  `)+(i.length>0?`
41
- `:""))}async function Ow(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
42
- `).map(r=>r.trim()).filter(Boolean)}function me(t,e){if(Aw(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Lo(kd(t,e)),n=Lo(t+"/");if(r!==Lo(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var wd,jw,_w,bd,Oo,Do,ot=k(()=>{"use strict";ft();wd=3,jw=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),_w=/^model\/derived\//,bd=/^tasks\/[^/]+\/comments\.jsonl$/,Oo=500,Do=new Map});import{existsSync as As,readFileSync as vd,readdirSync as Dw}from"node:fs";import{join as xd}from"node:path";import{simpleGit as Lw}from"simple-git";function Bw(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 Fw(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
44
- `),a=s.findIndex(b=>b.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,m=a>=0?a+1:0;for(let b=m;b<s.length;b++){let h=(s[b]??"").trim();if(h===""){m=b+1;continue}let $=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(h);if(!$)break;let S=($[1]??"").trim().toLowerCase(),D=($[2]??"").trim(),E=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(h);E&&(d=parseInt(E[1]??"",10)),S==="tasks"&&(p=D),l.has(S)||u.push(h),m=b+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(m).join(`
41
+ `:""))}async function sk(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
42
+ `).map(r=>r.trim()).filter(Boolean)}function ge(t,e){if(rk(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Vo(Ld(t,e)),n=Vo(t+"/");if(r!==Vo(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Od,nk,ok,Dd,Yo,qo,Je=$(()=>{"use strict";yt();Od=3,nk=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),ok=/^model\/derived\//,Dd=/^tasks\/[^/]+\/comments\.jsonl$/,Yo=500,qo=new Map});import{existsSync as Ks,readFileSync as Ud,readdirSync as ak}from"node:fs";import{join as Bd}from"node:path";import{simpleGit as ck}from"simple-git";function dk(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 pk(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
44
+ `),a=s.findIndex(k=>k.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,m=a>=0?a+1:0;for(let k=m;k<s.length;k++){let h=(s[k]??"").trim();if(h===""){m=k+1;continue}let b=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(h);if(!b)break;let S=(b[1]??"").trim().toLowerCase(),D=(b[2]??"").trim(),I=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(h);I&&(d=parseInt(I[1]??"",10)),S==="tasks"&&(p=D),l.has(S)||u.push(h),m=k+1}let f=p?p.includes(n)?p:`${p}, ${n}`:n,g=s.slice(m).join(`
45
45
  `).replace(/^\n+/,""),y=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${f}`,...u,"",g].join(`
46
46
  `);return{content:y.endsWith(`
47
47
  `)?y:y+`
48
- `,supersedes:d}}function Gw(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
48
+ `,supersedes:d}}function mk(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
49
49
 
50
- - **Status:** superseded by ADR-${r}`):n}function Kw(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(`
50
+ - **Status:** superseded by ADR-${r}`):n}function fk(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 Sd(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await Lw(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 b=me(t,i(y));if(!As(b)){a.push(y);continue}s.push({slug:y,content:vd(b,"utf-8")})}let c=xd(t,"adr"),l=new Map;if(As(c))for(let y of Dw(c)){let b=Mw.exec(y);!b||y===Uw||l.set(y,{num:parseInt(b[1]??"",10),slug:b[2]??"",content:vd(xd(c,y),"utf-8")})}let u=Math.max(0,...[...l.values()].map(y=>y.num))+1,p=new Map,d=[],m=[];for(let y of s){if([...l.entries()].find(([,E])=>E.slug===y.slug&&E.content.includes(e))){m.push(y.slug);continue}let h=u++,$=`${String(h).padStart(4,"0")}-${y.slug}.md`,{content:S,supersedes:D}=Fw(y.content,h,y.slug,e,n);if(p.set($,S),l.set($,{num:h,slug:y.slug,content:S}),d.push(`adr/${$}`),D!==null){let E=[...l.keys()].find(v=>v.startsWith(`${String(D).padStart(4,"0")}-`));if(E&&E!==$){let v=Gw(p.get(E)??l.get(E).content,h);p.set(E,v),l.set(E,{...l.get(E),content:v})}}}let f=[];if(o==="staging")for(let y of s)As(me(t,`adr/DRAFT-${y.slug}.md`))&&f.push({path:`adr/DRAFT-${y.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let y=[...l.entries()].map(([b,h])=>({num:h.num,file:b,header:Bw(h.content)}));p.set("INDEX.md",Kw(y))}for(let[y,b]of p.entries())f.push({path:`adr/${y}`,content:b});let g=d.length>0?`adr(${e}): promote ${s.map(y=>y.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await Ee(t,f,g),{promoted:d,skipped:m,missing:a}}var Mw,Uw,Rd=k(()=>{"use strict";ot();Mw=/^(\d{4})-(.+)\.md$/,Uw="0000-template.md"});import{existsSync as Td,readFileSync as Ww}from"node:fs";import{join as Cd}from"node:path";function qw(t){for(let e of[Qe,cn]){let r=Cd(t,e);if(Td(r))try{return uc(Ww(r,"utf-8"))}catch{return 0}}return 0}function Yw(t,e,r,n=4){let o=e<n,i=o?dc(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Mo(t,e){return Yw(e,qw(t),r=>Td(Cd(t,r)))}var js=k(()=>{"use strict";W()});import{existsSync as _t,readFileSync as Cr,readdirSync as Ed}from"node:fs";import{join as _s}from"node:path";import{simpleGit as Pd}from"simple-git";import{parse as Ad}from"yaml";function jd(t){try{let e=me(t,so);if(!_t(e))return null;let r=Ad(Cr(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!gr.test(n)?null:{prefix:n}}catch{return null}}function _d(t){return`# Built-in tracker configuration \u2014 shared by every team member.
52
+ `}async function Fd(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await ck(t).pull(void 0,void 0,["--rebase"])}catch{}let i=y=>o==="staging"?`adr/DRAFT-${y}.md`:`tasks/${e}/adr/DRAFT-${y}.md`,s=[],a=[];for(let y of r){let k=ge(t,i(y));if(!Ks(k)){a.push(y);continue}s.push({slug:y,content:Ud(k,"utf-8")})}let c=Bd(t,"adr"),l=new Map;if(Ks(c))for(let y of ak(c)){let k=lk.exec(y);!k||y===uk||l.set(y,{num:parseInt(k[1]??"",10),slug:k[2]??"",content:Ud(Bd(c,y),"utf-8")})}let u=Math.max(0,...[...l.values()].map(y=>y.num))+1,p=new Map,d=[],m=[];for(let y of s){if([...l.entries()].find(([,I])=>I.slug===y.slug&&I.content.includes(e))){m.push(y.slug);continue}let h=u++,b=`${String(h).padStart(4,"0")}-${y.slug}.md`,{content:S,supersedes:D}=pk(y.content,h,y.slug,e,n);if(p.set(b,S),l.set(b,{num:h,slug:y.slug,content:S}),d.push(`adr/${b}`),D!==null){let I=[...l.keys()].find(v=>v.startsWith(`${String(D).padStart(4,"0")}-`));if(I&&I!==b){let v=mk(p.get(I)??l.get(I).content,h);p.set(I,v),l.set(I,{...l.get(I),content:v})}}}let f=[];if(o==="staging")for(let y of s)Ks(ge(t,`adr/DRAFT-${y.slug}.md`))&&f.push({path:`adr/DRAFT-${y.slug}.md`,content:"",deleted:!0});if(d.length===0&&f.length===0)return{promoted:d,skipped:m,missing:a};if(d.length>0){let y=[...l.entries()].map(([k,h])=>({num:h.num,file:k,header:dk(h.content)}));p.set("INDEX.md",fk(y))}for(let[y,k]of p.entries())f.push({path:`adr/${y}`,content:k});let g=d.length>0?`adr(${e}): promote ${s.map(y=>y.slug).join(", ")}`:`adr(${e}): drop stale staged ${m.join(", ")}`;return await ke(t,f,g),{promoted:d,skipped:m,missing:a}}var lk,uk,Gd=$(()=>{"use strict";Je();lk=/^(\d{4})-(.+)\.md$/,uk="0000-template.md"});import{existsSync as Kd,readFileSync as hk}from"node:fs";import{join as Hd}from"node:path";function yk(t){for(let e of[tt,wn]){let r=Hd(t,e);if(Kd(r))try{return Cc(hk(r,"utf-8"))}catch{return 0}}return 0}function wk(t,e,r,n=4){let o=e<n,i=o?Ec(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function zo(t,e){return wk(e,yk(t),r=>Kd(Hd(t,r)))}var Hs=$(()=>{"use strict";W()});import{existsSync as Nt,readFileSync as Or,readdirSync as Yd}from"node:fs";import{join as Ws}from"node:path";import{simpleGit as qd}from"simple-git";import{parse as Vd}from"yaml";function zd(t){try{let e=ge(t,wo);if(!Nt(e))return null;let r=Vd(Or(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!xr.test(n)?null:{prefix:n}}catch{return null}}function Jd(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 Ns(t=0){return`${t}
61
- `}function Vw(t){return t==="depends_on"||t==="subtask"}function zw(t){let e;try{e=Ad(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=il.includes(r.type)?r.type:io,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;Vw(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 Os(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 Ys(t=0){return`${t}
61
+ `}function kk(t){return t==="depends_on"||t==="subtask"}function bk(t){let e;try{e=Vd(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=vl.includes(r.type)?r.type:yo,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;kk(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 qs(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 Rn(t,e){let r=me(t,pn(e));return _t(r)?zw(Cr(r,"utf-8")):null}function Nd(t){let e=_s(t,"tasks");if(!_t(e))return[];let r=[];for(let n of Ed(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Rn(t,n.name);o&&r.push(o)}return r}function Jw(t,e){let r=me(t,`tasks/${e}/task.md`);if(!_t(r))return;let n=Cr(r,"utf-8").split(`
63
+ `}function On(t,e){let r=ge(t,xn(e));return Nt(r)?bk(Or(r,"utf-8")):null}function Xd(t){let e=Ws(t,"tasks");if(!Nt(e))return[];let r=[];for(let n of Yd(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=On(t,n.name);o&&r.push(o)}return r}function $k(t,e){let r=ge(t,`tasks/${e}/task.md`);if(!Nt(r))return;let n=Or(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 Tn(t,e,r={}){let n=r.withDescription?Jw(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:Xw(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function Xw(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Qw(t){let e=me(t,dn);if(!_t(e))return 0;let r=Number.parseInt(Cr(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function Zw(t,e){let r=_s(t,"tasks");if(!_t(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of Ed(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 eb(t,e){return Math.max(Qw(t),Zw(t,e))+1}async function Od(t,e,r,n){return Es(t,()=>tb(t,e,r,n))}async function tb(t,e,r,n){if(!_t(_s(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Sn(t);let o=null;for(let i=0;i<Id;i++){let s=eb(t,e),a=`${e}-${s}`,c=[...r(a),{path:dn,content:Ns(s)}];try{return await Ps(t,c,n(a)),a}catch(l){if(o=l,await nb(t,n(a)),await Sn(t),rb(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Id} attempts: ${o instanceof Error?o.message:String(o)}`)}function rb(t,e){for(let r of e){let n=me(t,r.path);if(!_t(n)||(r.encoding==="base64"?Cr(n).toString("base64"):Cr(n,"utf-8"))!==r.content)return!1}return!0}async function Sn(t){let e=Pd(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 nb(t,e){let r=Pd(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 Dn(t,e,r={}){let n=r.withDescription?$k(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:vk(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function vk(t){return t.charAt(0).toUpperCase()+t.slice(1)}function xk(t){let e=ge(t,vn);if(!Nt(e))return 0;let r=Number.parseInt(Or(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function Sk(t,e){let r=Ws(t,"tasks");if(!Nt(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of Yd(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 Tk(t,e){return Math.max(xk(t),Sk(t,e))+1}async function Qd(t,e,r,n){return Fs(t,()=>Rk(t,e,r,n))}async function Rk(t,e,r,n){if(!Nt(Ws(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Nn(t);let o=null;for(let i=0;i<Wd;i++){let s=Tk(t,e),a=`${e}-${s}`,c=[...r(a),{path:vn,content:Ys(s)}];try{return await Gs(t,c,n(a)),a}catch(l){if(o=l,await Ek(t,n(a)),await Nn(t),Ck(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Wd} attempts: ${o instanceof Error?o.message:String(o)}`)}function Ck(t,e){for(let r of e){let n=ge(t,r.path);if(!Nt(n)||(r.encoding==="base64"?Or(n).toString("base64"):Or(n,"utf-8"))!==r.content)return!1}return!0}async function Nn(t){let e=qd(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 Ek(t,e){let r=qd(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 Id,Uo=k(()=>{"use strict";W();ot();Id=5});function Ir(t,e,r,n){return[{path:"README.md",content:gb(t,e)},{path:".gitignore",content:lb()},{path:"CLAUDE.md",content:db(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:ub()},{path:"knowledge/README.md",content:pb()},{path:"knowledge/build.yaml",content:fb()},{path:"actions/README.md",content:mb()},{path:"model/README.md",content:ob()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:cb()},{path:"adr/README.md",content:ib()},{path:"adr/0000-template.md",content:sb()},{path:"adr/INDEX.md",content:ab()},{path:Qe,content:ro()},...t.trackerProvider==="internal"?[{path:so,content:_d(t.youtrackProjectKey??qi)},{path:dn,content:Ns()}]:[]]}function ob(){return`# model/ \u2014 the project map
68
+ `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Wd,Jo=$(()=>{"use strict";W();Je();Wd=5});function Dr(t,e,r,n){return[{path:"README.md",content:Bk(t,e)},{path:".gitignore",content:Nk()},{path:"CLAUDE.md",content:Dk(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Ok()},{path:"knowledge/README.md",content:Lk()},{path:"knowledge/build.yaml",content:Uk()},{path:"actions/README.md",content:Mk()},{path:"model/README.md",content:Ik()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:_k()},{path:"adr/README.md",content:Pk()},{path:"adr/0000-template.md",content:Ak()},{path:"adr/INDEX.md",content:jk()},{path:tt,content:uo()},...t.trackerProvider==="internal"?[{path:wo,content:Jd(t.youtrackProjectKey??os)},{path:vn,content:Ys()}]:[]]}function Ik(){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 ib(){return`# ADR \u2014 architecture decision records
95
+ `}function Pk(){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 sb(){return`# ADR-NNNN: <title>
123
+ `}function Ak(){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 ab(){return`# ADR index
145
+ `}function jk(){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 cb(){return`# Audit
150
+ `}function _k(){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 it(t,e,r,n,o="auto",i=Ze,s){let a=t.trackerProvider==="internal";return{projectYaml:a?hb(t,o):yb(t,r,n,o),regimenYaml:wb(t.automationLevel,a?!0:e,a,i,s)}}function lb(){return`# codepipe project config is local to each member's workspace
159
+ `}function ct(t,e,r,n,o="auto",i=nt,s){let a=t.trackerProvider==="internal";return{projectYaml:a?Fk(t,o):Gk(t,r,n,o),regimenYaml:Kk(t.automationLevel,a?!0:e,a,i,s)}}function Nk(){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 ub(){return`# Index prompt
166
+ `}function Ok(){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 db(t){return`# Project context for the CodePipe agent
223
+ `}function Dk(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 pb(){return`# Knowledge
251
+ `}function Lk(){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 mb(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
268
+ `}function Mk(){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 fb(){return`# BUILD phase config. Discovered & maintained by the agent.
307
+ `}function Uk(){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 gb(t,e){return`# ${e.name}
323
+ `}function Bk(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 hb(t,e="auto"){return`# Project description for CodePipe.
349
+ `}function Fk(t,e="auto"){return`# Project description for CodePipe.
350
350
  id: ${t.projectId}
351
351
  name: ${t.name}
352
352
 
@@ -369,15 +369,15 @@ branch:
369
369
  pattern: codepipe/<TASK_ID>
370
370
 
371
371
  repos:
372
- ${Dd(t)}
373
- `}function Dd(t){return t.repos.length===0?` [] # add repos here
372
+ ${Zd(t)}
373
+ `}function Zd(t){return t.repos.length===0?` [] # add repos here
374
374
  `:t.repos.map(e=>` - name: ${e.name}
375
375
  host: ${e.host}
376
376
  owner: ${e.owner}
377
377
  repo: ${e.repoName}
378
378
  mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
379
379
  default_branch: ${e.defaultBranch}`:"")).join(`
380
- `)}function yb(t,e,r,n="auto"){let o=e?`
380
+ `)}function Gk(t,e,r,n="auto"){let o=e?`
381
381
  tracker_url: ${e}`:`
382
382
  # tracker_url: https://your.youtrack.cloud`,i=r?`require_assignee: true
383
383
  assignee: ${r}`:`require_assignee: false
@@ -425,7 +425,7 @@ ${Dd(t)}
425
425
  # non-empty assignee. assignee only takes effect when require_assignee=true.
426
426
  ${i}`:` # project_key: \u2026
427
427
  # tracker_url: https://your.youtrack.cloud
428
- poll_interval_sec: 60`,a=Dd(t);return`# Project description for CodePipe.
428
+ poll_interval_sec: 60`,a=Zd(t);return`# Project description for CodePipe.
429
429
  id: ${t.projectId}
430
430
  name: ${t.name}
431
431
 
@@ -456,7 +456,7 @@ branch:
456
456
 
457
457
  repos:
458
458
  ${a}
459
- `}function wb(t,e,r=!1,n=Ze,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
459
+ `}function Kk(t,e,r=!1,n=nt,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
460
460
  # model in the recommended per-role split, so CodePipe set a single default
461
461
  # your subscription can serve for all roles. Tune per role later from the
462
462
  # dashboard (Project Settings \u2192 llm.models) or by editing this file.
@@ -607,29 +607,35 @@ ${a}
607
607
  # # While this key stays commented out, the project keeps its current mode \u2014
608
608
  # # only new projects start on cluster-pr. Uncomment and set a value to switch.
609
609
  # mode: cluster-pr
610
- `}var ir=k(()=>{"use strict";W();Uo()});import{existsSync as Ld,mkdirSync as bb,mkdtempSync as kb,rmSync as Md,writeFileSync as Ud}from"node:fs";import{tmpdir as $b}from"node:os";import{dirname as vb,join as Bo}from"node:path";import{simpleGit as Ds}from"simple-git";function xb(t){return`codepipe/context-migration-v${t}`}function Sb(t){let e=pc(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 \`${Qe}\` stamp (renamed from \`${cn}\``,"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 Bd(t,e,r,n){let o=Ds(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Mo(t,e);if(!i.outdated)return i;let s=xb(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 Rb(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=He(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:Sb(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 Rb(t,e,r,n,o,i,s){let a=Ds(t),c=kb(Bo($b(),"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(Ir(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===Qe)continue;let y=p.get(g);if(y==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let b=Bo(c,g);Ld(b)||(bb(vb(b),{recursive:!0}),Ud(b,y),d++)}Ud(Bo(c,Qe),ro(n.currentVersion)),d++;let m=Bo(c,cn);Ld(m)&&(Md(m,{force:!0}),d++);let f=Ds(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(()=>{}),Md(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var Fd=k(()=>{"use strict";W();Ct();js();ir()});import{existsSync as Tb,readFileSync as Cb,writeFileSync as Ib}from"node:fs";import{homedir as Eb}from"node:os";import{join as Gd}from"node:path";import{parseDocument as Pb}from"yaml";function Ab(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 jb(t,e){let r=Pb(t);return r.set("repos",e.map(Ab)),r.toString()}function _b(t,e){let r=[Gd(Eb(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Gd(e,"project.yaml")),r}function Cn(t,e,r){let n=[],o=[];for(let i of _b(t,r))if(Tb(i))try{let s=Cb(i,"utf-8"),a=jb(s,e);a!==s&&(Ib(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 Ls=k(()=>{"use strict"});import{createCipheriv as Nb,createDecipheriv as Ob,createHash as Db,createPrivateKey as Lb,createPublicKey as Ms,diffieHellman as Kd,generateKeyPairSync as Hd,hkdfSync as Wd,randomBytes as Mb}from"node:crypto";function Fo(){let{publicKey:t,privateKey:e}=Hd("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Re(t){let e=Buffer.from(t,"base64");return(Db("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function gt(t,e){let r=Ms({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Hd("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Kd({privateKey:o,publicKey:r}),c=Buffer.from(Wd("sha256",a,Buffer.concat([i,s]),qd,32)),l=Mb(12),u=Nb("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 Er(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=Lb({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Ms({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Ms(n).export({type:"spki",format:"der"}),a=Kd({privateKey:n,publicKey:o}),c=Buffer.from(Wd("sha256",a,Buffer.concat([i,s]),qd,32)),l=Ob("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 qd,Le=k(()=>{"use strict";qd=Buffer.from("devpipe-sealedbox-v1","utf-8")});function Ub(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 Yd(t,e,r,n){let o=Ub(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=fo(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=gt(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 Vd=k(()=>{"use strict";Le();oe()});function In(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 En(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 Pn(t,e=process.env){if(!t)return!1;let r=`https://${Yt}:${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 Us(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 zd(t,e=process.env){return Us(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>In(t,e),e)}function Jd(t,e=process.env){return Us(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>En(t,e),e)}function Xd(t,e=process.env){return Us(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Yt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Pn(t,e),e)}var Go=k(()=>{"use strict";W()});function Qd(t){let e=G(t);if(!e)return null;if(!e.sealKey){let r=Fo();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},X(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Re(e.sealKey.publicKey)}}async function Zd(t,e,r,n){let o;try{o=JSON.parse(Er(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=G(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 St(o.token);return i.github={token:o.token},Pr(i,()=>{process.env.GH_TOKEN=o.token,zd(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Tt(o.token);return i.gitlab={token:o.token},Pr(i,()=>{process.env.GITLAB_TOKEN=o.token,Jd(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 Rt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Pr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Xd(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 Et({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Pr(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 Pt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Pr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Pr(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 Pr(t,e){X(t),e()}var ep=k(()=>{"use strict";Le();oe();Ct();Jt();vr();Go()});import{spawn as Bb}from"node:child_process";function Gb(t,e,r,n,o,i){let s={...t},a=(c,l)=>{vt(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 np(t){let{def:e,onEvent:r}=t,n=Gb(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
612
- `,o.length>tp&&(o=o.slice(o.length-tp))},s=(a,c)=>{let l=c.length>rp?c.slice(0,rp)+"\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 Kb(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 Kb(t,e,r,n,o){return new Promise(i=>{let s=Bb("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Dc)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=m=>{let f="";return{data:g=>{f+=g.toString("utf-8");let y;for(;(y=f.indexOf(`
613
- `))!==-1;)o(m,f.slice(0,y).replace(/\r$/,"")),f=f.slice(y+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?Fb:m??(f?1:0))})})}var Fb,tp,rp,op=k(()=>{"use strict";W();Fb=124,tp=16*1024,rp=4e3});import{existsSync as Hb,readFileSync as Wb,statSync as ip}from"node:fs";function qb(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function ap(t,e){let r=me(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!Hb(r)||!ip(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=ip(r);if(n>sp)throw new Error(`file too large: ${e} is ${n} bytes (limit ${sp})`);let o=Wb(r);return qb(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}var sp,cp=k(()=>{"use strict";ot();sp=2*1024*1024});import{existsSync as Yb,readFileSync as Vb,writeFileSync as zb}from"node:fs";import{join as Jb}from"node:path";import{parseDocument as Xb}from"yaml";async function lp(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=Kc(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=Jb(t,o);if(!Yb(s))throw new Error(`${o} not found in context repo (${t})`);let a=Xb(Vb(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);zb(s,a.toString()),n.push(o)}return{files:n}}var up=k(()=>{"use strict";W()});import{existsSync as Qb,readFileSync as Zb,writeFileSync as ek}from"node:fs";import{join as tk}from"node:path";import{isMap as dp,parseDocument as rk}from"yaml";async function pp(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||!Jc(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=tk(t,"project.yaml");if(!Qb(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=rk(Zb(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>dp(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!dp(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),ek(o,i.toString()),{repoName:r,defaultBranch:n}}var mp=k(()=>{"use strict";W()});import{existsSync as Bs,readFileSync as Fs,writeFileSync as nk}from"node:fs";import{join as Ko}from"node:path";import{parseDocument as Gs}from"yaml";async function fp(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=Ko(t,"project.yaml");if(!Bs(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Gs(Fs(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=Ko(t,"regimen.yaml");if(!Bs(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Gs(Fs(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)nk(Ko(t,i.path),i.content);return{files:r.map(i=>i.path)}}function Ho(t){if(!t)return"Stage";try{let e=Ko(t,"project.yaml");if(!Bs(e))return"Stage";let n=Gs(Fs(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var Ks=k(()=>{"use strict"});var An,Hs=k(()=>{"use strict";Ks();Jt();An=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return yu(this.cfg,e)}getIssue(e,r){return wu(this.cfg,e,r??Ho(this.contextDir))}listComments(e,r){return bu(this.cfg,e,r)}downloadAttachment(e){return hu(this.cfg,e)}updateStatus(e,r){return au(this.cfg,e,r,Ho(this.contextDir))}addComment(e,r,n){return cu(this.cfg,e,r)}createIssue(e){return du(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,Ho(this.contextDir))}editIssue(e,r){return lu(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return pu(this.cfg,e,r,n)}fetchStateFields(e){return $u(this.cfg,e)}}});import{existsSync as gp,readFileSync as ok,readdirSync as ik}from"node:fs";function Wo(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=lk(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:sk(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:ck(ak(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 qo(t,e,r){if(r.length===0)return;let n=Wo(t,e,r),o=r.map(i=>i.issue.key);await Ee(t,n,`sync(${o.join(", ")}): task data`)}function sk(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(`
614
- `)}function ak(t,e,r){let n=new Map,o=me(t,`tasks/${e}/comments.jsonl`);if(gp(o))for(let i of ok(o,"utf-8").split(`
615
- `)){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=fr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function ck(t){return t.map(e=>JSON.stringify(e)).join(`
610
+ `}var ar=$(()=>{"use strict";W();Jo()});import{existsSync as ep,mkdirSync as Hk,mkdtempSync as Wk,rmSync as tp,writeFileSync as rp}from"node:fs";import{tmpdir as Yk}from"node:os";import{dirname as qk,join as Xo}from"node:path";import{simpleGit as Vs}from"simple-git";function Vk(t){return`codepipe/context-migration-v${t}`}function zk(t){let e=Ic(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 \`${tt}\` stamp (renamed from \`${wn}\``,"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 np(t,e,r,n){let o=Vs(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=zo(t,e);if(!i.outdated)return i;let s=Vk(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 Jk(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:zk(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 Jk(t,e,r,n,o,i,s){let a=Vs(t),c=Wk(Xo(Yk(),"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(Dr(l,u).map(g=>[g.path,g.content])),d=0;for(let g of n.missingPaths){if(g===tt)continue;let y=p.get(g);if(y==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let k=Xo(c,g);ep(k)||(Hk(qk(k),{recursive:!0}),rp(k,y),d++)}rp(Xo(c,tt),uo(n.currentVersion)),d++;let m=Xo(c,wn);ep(m)&&(tp(m,{force:!0}),d++);let f=Vs(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(()=>{}),tp(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}var op=$(()=>{"use strict";W();Et();Hs();ar()});import{existsSync as Xk,readFileSync as Qk,writeFileSync as Zk}from"node:fs";import{homedir as eb}from"node:os";import{join as ip}from"node:path";import{parseDocument as tb}from"yaml";function rb(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 nb(t,e){let r=tb(t);return r.set("repos",e.map(rb)),r.toString()}function ob(t,e){let r=[ip(eb(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(ip(e,"project.yaml")),r}function Ln(t,e,r){let n=[],o=[];for(let i of ob(t,r))if(Xk(i))try{let s=Qk(i,"utf-8"),a=nb(s,e);a!==s&&(Zk(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 zs=$(()=>{"use strict"});import{createCipheriv as ib,createDecipheriv as sb,createHash as ab,createPrivateKey as cb,createPublicKey as Js,diffieHellman as sp,generateKeyPairSync as ap,hkdfSync as cp,randomBytes as lb}from"node:crypto";function Qo(){let{publicKey:t,privateKey:e}=ap("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Ce(t){let e=Buffer.from(t,"base64");return(ab("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function wt(t,e){let r=Js({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=ap("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=sp({privateKey:o,publicKey:r}),c=Buffer.from(cp("sha256",a,Buffer.concat([i,s]),lp,32)),l=lb(12),u=ib("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 Lr(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=cb({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Js({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Js(n).export({type:"spki",format:"der"}),a=sp({privateKey:n,publicKey:o}),c=Buffer.from(cp("sha256",a,Buffer.concat([i,s]),lp,32)),l=sb("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 lp,Ue=$(()=>{"use strict";lp=Buffer.from("devpipe-sealedbox-v1","utf-8")});function ub(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 up(t,e,r,n){let o=ub(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=To(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=wt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}var dp=$(()=>{"use strict";Ue();oe()});function Mn(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 Un(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 Bn(t,e=process.env){if(!t)return!1;let r=`https://${Vt}:${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 Xs(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 pp(t,e=process.env){return Xs(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Mn(t,e),e)}function mp(t,e=process.env){return Xs(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Un(t,e),e)}function fp(t,e=process.env){return Xs(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Vt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Bn(t,e),e)}var Zo=$(()=>{"use strict";W()});function gp(t){let e=G(t);if(!e)return null;if(!e.sealKey){let r=Qo();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},X(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Ce(e.sealKey.publicKey)}}async function hp(t,e,r,n){let o;try{o=JSON.parse(Lr(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=G(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 Tt(o.token);return i.github={token:o.token},Mr(i,()=>{process.env.GH_TOKEN=o.token,pp(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Ct(o.token);return i.gitlab={token:o.token},Mr(i,()=>{process.env.GITLAB_TOKEN=o.token,mp(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 Rt(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Mr(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,fp(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Pt({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Mr(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 At(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Mr(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Mr(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 Mr(t,e){X(t),e()}var yp=$(()=>{"use strict";Ue();oe();Et();Xt();Pr();Zo()});import{spawn as db}from"node:child_process";function mb(t,e,r,n,o,i){let s={...t},a=(c,l)=>{xt(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 bp(t){let{def:e,onEvent:r}=t,n=mb(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
612
+ `,o.length>wp&&(o=o.slice(o.length-wp))},s=(a,c)=>{let l=c.length>kp?c.slice(0,kp)+"\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 fb(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 fb(t,e,r,n,o){return new Promise(i=>{let s=db("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??Zc)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=m=>{let f="";return{data:g=>{f+=g.toString("utf-8");let y;for(;(y=f.indexOf(`
613
+ `))!==-1;)o(m,f.slice(0,y).replace(/\r$/,"")),f=f.slice(y+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?pb:m??(f?1:0))})})}var pb,wp,kp,$p=$(()=>{"use strict";W();pb=124,wp=16*1024,kp=4e3});import{existsSync as gb,readFileSync as hb,statSync as vp}from"node:fs";function yb(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Sp(t,e){let r=ge(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!gb(r)||!vp(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=vp(r);if(n>xp)throw new Error(`file too large: ${e} is ${n} bytes (limit ${xp})`);let o=hb(r);return yb(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}var xp,Tp=$(()=>{"use strict";Je();xp=2*1024*1024});import{existsSync as wb,readFileSync as kb,writeFileSync as bb}from"node:fs";import{join as $b}from"node:path";import{parseDocument as vb}from"yaml";async function Rp(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=sl(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=$b(t,o);if(!wb(s))throw new Error(`${o} not found in context repo (${t})`);let a=vb(kb(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);bb(s,a.toString()),n.push(o)}return{files:n}}var Cp=$(()=>{"use strict";W()});import{existsSync as xb,readFileSync as Sb,writeFileSync as Tb}from"node:fs";import{join as Rb}from"node:path";import{isMap as Ep,parseDocument as Cb}from"yaml";async function Ip(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||!ml(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=Rb(t,"project.yaml");if(!xb(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Cb(Sb(o,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>Ep(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!Ep(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",n),Tb(o,i.toString()),{repoName:r,defaultBranch:n}}var Pp=$(()=>{"use strict";W()});import{existsSync as Qs,readFileSync as Zs,writeFileSync as Eb}from"node:fs";import{join as ei}from"node:path";import{parseDocument as ea}from"yaml";async function Ap(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=ei(t,"project.yaml");if(!Qs(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=ea(Zs(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=ei(t,"regimen.yaml");if(!Qs(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=ea(Zs(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)Eb(ei(t,i.path),i.content);return{files:r.map(i=>i.path)}}function ti(t){if(!t)return"Stage";try{let e=ei(t,"project.yaml");if(!Qs(e))return"Stage";let n=ea(Zs(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}var ta=$(()=>{"use strict"});import{existsSync as ra,readFileSync as na}from"node:fs";import{join as oa}from"node:path";import{simpleGit as _p}from"simple-git";import{parse as ia}from"yaml";function Op(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(Ib.source,"g")}function Dp(t){let e=oa(t,"project.yaml");if(ra(e))try{let o=ia(na(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=oa(t,"tracker","config.yaml");if(ra(r))try{let o=ia(na(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function Lp(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 Pb(t,e,r){let o=await _p(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
614
+ `))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=sa.exec(u)??Np.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:Lp(c[3]),churn:l+u})}return i}async function Ab(t,e){let n=await _p(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
615
+ `)){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:Lp(s[3]),churn:a+c})}return o}function jb(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(sa,"").trim();else if(c.prNumber!==null)u=`PR-${c.prNumber}`,p=c.subject.replace(sa,"").replace(Np,"").replace(/^from\s+/,"").trim()||c.subject;else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let y of c.files){let k=o.get(y.path)??y.path;s(k)||m.set(k,(m.get(k)??0)+y.churn)}if(m.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),c.timeSec>0&&(g.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),g.commits.push(c.sha);for(let[y,k]of m){let h=fe("code",e,y),b=g.files.find(S=>S.key===h);if(b)b.churn=(b.churn??0)+k;else{let S=i.get(h);g.files.push({key:h,...S?{entityId:S}:{},churn:k})}}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 jp(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 Mp(t){let e=await Pb(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 Ab(t.repoDir,r.sha))}return jb({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored})}function Up(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?jp(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=jp(ri(t,i),s);if(!a){o++;continue}n.push({path:kr(i),content:bn(a)})}return{files:n,skippedPipeline:o}}function ri(t,e){let r=oa(t,kr(e));if(!ra(r))return null;try{let n=go(ia(na(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var Ib,sa,Np,aa=$(()=>{"use strict";W();Ib=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,sa=/\(#(\d+)\)\s*$/,Np=/^Merge pull request #(\d+)\b/});import{simpleGit as _b}from"simple-git";async function Fp(t,e,r){let o=await _b(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
616
+ `))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 ni(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=ce(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=ce(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function Gp(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 k of n){let h=new Set;for(let I of k.files){let v=o.get(I)??I;!i.has(v)||s(v)||h.add(v)}if(h.size<2||h.size>a.commitFileCap)continue;let b=Math.max(0,r-k.timeSec),S=Math.pow(.5,b/c),D=[...h].sort();for(let I of D)l.set(I,(l.get(I)??0)+S);for(let I=0;I<D.length;I++)for(let v=I+1;v<D.length;v++){let A=`${D[I]}\0${D[v]}`;u.set(A,(u.get(A)??0)+S),p.set(A,(p.get(A)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[k,h]of u){if((p.get(k)??0)<a.supportMin)continue;let[b,S]=k.split("\0"),D=(l.get(b)??0)+(l.get(S)??0)-h,I=D>0?h/D:0;I<m||d.push({a:b,b:S,weight:Math.round(I*Bp)/Bp})}let f=new Map;for(let k of d)for(let h of[k.a,k.b])f.has(h)||f.set(h,[]),f.get(h).push(k);let g=new Map;for(let[,k]of f)k.sort((h,b)=>b.weight-h.weight||(h.a<b.a?-1:h.a>b.a?1:h.b<b.b?-1:1)).slice(0,a.topK).forEach(h=>g.set(h,(g.get(h)??0)+1));return[...g.entries()].filter(([,k])=>k===2).map(([k])=>k).map(k=>({kind:"correlates",from:fe("code",e,k.a),to:fe("code",e,k.b),weight:k.weight})).sort((k,h)=>k.from<h.from?-1:k.from>h.from?1:k.to<h.to?-1:1)}var Ur,Bp,oi=$(()=>{"use strict";W();Ur=["package-lock.json","pnpm-lock.yaml","yarn.lock"];Bp=1e4});import{createHash as Nb}from"node:crypto";function Db(t,e,r,n){for(let o=0;;o++){let s=`e_${Nb("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function Kp(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(v=>v.entityId)),d=new Set,m=[],f=new Map,g=(v,A)=>{d.add(A),f.set(A,v.entityId),m.push(v)},y=[];for(let v of u)l.has(v.currentKey)&&!d.has(v.currentKey)?g({...v,status:"active",lastSeen:r},v.currentKey):y.push(v);let k=[],h=[];for(let v of y){let A=ce(v.currentKey),M=A?i.get(A.path):void 0;if(A&&M){let K=fe(A.level,e,M.finalPath);if(l.has(K)&&!d.has(K)){k.push({entity:v,newKey:K,untilCommit:M.commit}),d.add(K);continue}}h.push(v)}let b=[];if(s){let v=new Map;for(let M of c){if(d.has(M))continue;let K=ce(M);if(K?.level!=="code")continue;let P=a.get(K.path);P&&v.set(P,v.has(P)?null:M)}let A=new Map;for(let M of h){let K=ce(M.currentKey);if(K?.level!=="code")continue;let P=s.get(K.path);P&&A.set(P,A.has(P)?null:M)}for(let M of h){let K=ce(M.currentKey),P=K?.level==="code"?s.get(K.path):void 0,w=P?v.get(P):void 0;P&&w&&A.get(P)===M&&!d.has(w)?(k.push({entity:M,newKey:w,untilCommit:r}),d.add(w)):b.push(M)}}else b.push(...h);let S=new Map;for(let v of k){let A=ce(v.entity.currentKey),M=ce(v.newKey);if(A?.level!=="code"||!M)continue;let K=A.path,P=M.path;for(let w=K.lastIndexOf("/");w>0;w=K.lastIndexOf("/",w-1)){let E=K.slice(0,w),R=K.slice(w+1);if(!P.endsWith(`/${R}`))continue;let T=P.slice(0,P.length-R.length-1);if(T===E)continue;let N=`${E}\0${T}`,j=S.get(N);S.set(N,{count:(j?.count??0)+1,commit:j&&j.commit>v.untilCommit?j.commit:v.untilCommit})}}let D=[...S.entries()].filter(([,v])=>v.count>=Ob).map(([v,A])=>{let[M,K]=v.split("\0");return{from:M,to:K,commit:A.commit}}).sort((v,A)=>A.from.length-v.from.length||(v.from<A.from?-1:1)),I=[];for(let v of b){let A=ce(v.currentKey),M=!1;if(A?.level==="component")for(let K of D){let P=null;if(A.path===K.from?P=K.to:A.path.startsWith(`${K.from}/`)&&(P=K.to+A.path.slice(K.from.length)),P===null)continue;let w=fe("component",e,P);l.has(w)&&!d.has(w)&&(k.push({entity:v,newKey:w,untilCommit:K.commit}),d.add(w),M=!0);break}M||I.push(v)}for(let v of k.sort((A,M)=>A.newKey<M.newKey?-1:1))g({...v.entity,currentKey:v.newKey,aliases:[...v.entity.aliases??[],{key:v.entity.currentKey,until:v.untilCommit}],status:"active",lastSeen:r},v.newKey);for(let v of I)m.push({...v,status:"orphaned"});for(let v of c){if(d.has(v))continue;let A=Db(e,v,r,p);p.add(A),g({entityId:A,currentKey:v,firstSeen:n,lastSeen:r,status:"active"},v)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}var Ob,Hp=$(()=>{"use strict";W();Ob=5});import{simpleGit as Lb}from"simple-git";async function Wp(t,e,r){let n=Lb(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
617
+ `).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 Yp(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 qp=$(()=>{"use strict"});function ii(t){return fe("container",t,Mb)}function Vp(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function zp(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:Vp(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,Ub)}},s=(u,p)=>{let d=fe("component",t,u),m=n.get(d);return{key:d,level:"component",label:Vp(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],g=[p,...m.map(i)],y=[...m.map(k=>({kind:"contains",from:p.key,to:fe("code",t,k.path)})),...f.map(k=>({kind:"contains",from:p.key,to:fe("component",t,k)}))];c(u,g,y)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=Dc(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:jc(t,u),content:Fc(m)})},l={key:ii(t),level:"container",label:t,...n.get(ii(t))?{entityId:n.get(ii(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 Jp(t,e){let r=[ii(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 Mb,Ub,Xp=$(()=>{"use strict";W();Mb=".";Ub=12});import{simpleGit as Zp}from"simple-git";function cr(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 tm(t,e="HEAD"){let r=Zp(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 ca(t,n)}}async function ca(t,e){let n=await Zp(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 Qp(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function rm(t,e){let r=[...t].sort((f,g)=>f.path<g.path?-1:f.path>g.path?1:0),n=new Map,o=new Map;for(let f of r){let g=Qp(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let y=g;for(;y!=="";){let k=Qp(y);o.has(k)||o.set(k,new Set),o.get(k).add(y),y=k}}let i=f=>[...o.get(f)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),g=(n.get(f)??[]).length+i(f).length;if(g<=s)s-=g,c.add(f),l.push(...i(f));else{if(f==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(f)}}let u=[],p=new Map,d=new Map,m=0;for(let f of[...c].sort()){let g=n.get(f)??[];p.set(f,g),d.set(f,i(f)),m+=g.length,f!==""&&u.push(f)}for(let f of a)u.push(f);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:m}}}var em,si=$(()=>{"use strict";em=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as nm,readFileSync as om}from"node:fs";import{join as im}from"node:path";import{simpleGit as Bb}from"simple-git";import{parse as sm}from"yaml";function Fn(t){let e={ignore:em,containerNodeCap:Fb,cochange:{...He},issueKeyPattern:null},r=im(t,"regimen.yaml");if(!nm(r))return e;let n;try{n=sm(om(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}}function la(t,e){let r=im(t,po(e));if(!nm(r))return null;let n=sm(om(r,"utf-8")),o=Lc(n);if(!o.ok)throw new Error(`model: ${po(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function am(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await tm(r),s=cr(o.ignore),a=i.files.filter(h=>!s(h.path)),c=rm(a,o.containerNodeCap),l=la(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await Bb(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=Yp(await Wp(r,l.builtFromCommit,i.commit)),p=new Map((await ca(r,l.builtFromCommit)).map(S=>[S.path,S.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])),m=Kp({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Jp(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=zp(e,i.commit,c,m.byKey),g=cr([...o.ignore,...Ur]),y=Gp({repo:e,headTimeSec:i.commitTimeSec,filesets:await Fp(r,i.commit,o.cochange.windowCommits),pathToCurrent:ni(m.table),currentPaths:new Set(a.map(h=>h.path)),ignored:g,settings:o.cochange}),k=[{path:po(e),content:Gc(m.table)},...f.files.map(h=>({path:h.path,content:h.content})),{path:Ac(e),content:mo({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:y})}];return{repo:e,headCommit:i.commit,files:k,emittedShardPaths:new Set(f.files.map(h=>h.path)),counts:{...f.counts,correlates:y.length},identityTable:m.table,entityByKey:m.byKey}}var Fb,ua=$(()=>{"use strict";W();oi();Hp();qp();Xp();si();Fb=1500});import{existsSync as lm,readFileSync as um,readdirSync as Gb}from"node:fs";import{join as da}from"node:path";import{parse as dm}from"yaml";function Kb(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 pm(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<Oc)return null;let s=i/Math.min(n.size,o.size),a=Kb(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*cm)/cm;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[br(t.taskKey),br(e.taskKey)]:[br(e.taskKey),br(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function mm(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=pm(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 fm(t,e,r,n){let o=br(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=pm(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 ai(t){let e=da(t,"model/facts/events");if(!lm(e))return[];let r=[];for(let n of Gb(e).sort())if(n.endsWith(".yaml"))try{let o=go(dm(um(da(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function gm(t){let e=da(t,wr);if(!lm(e))return[];try{let r=Nc(dm(um(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function ci(t){return mo({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var cm,pa=$(()=>{"use strict";W();cm=1e4});var ym={};Wi(ym,{attachPrToBranchTasks:()=>ga,attachPrToEvent:()=>hm,recordPipelineEvent:()=>fa});import{existsSync as Hb,readFileSync as Wb}from"node:fs";import{join as Yb}from"node:path";import{simpleGit as ma}from"simple-git";async function qb(t,e){let n=await ma(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
618
+ `)){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 Vb(t,e){let r=`tasks/${e}/SOLUTION.md`,n=Yb(t,r);if(!Hb(n))return{};try{let o=Wb(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 fa(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=Fn(e),a=cr([...s.ignore,...Ur]),c=await qb(r,i),l=(await ma(r).raw(["show","-s","--format=%cs",i])).trim(),u=new Map;try{let b=la(e,n);b&&(u=new Map(b.entities.filter(S=>S.status==="active").map(S=>[S.currentKey,S.entityId])))}catch{}let p=[];for(let b of c){if(a(b.path))continue;let S=fe("code",n,b.path),D=u.get(S);p.push({key:S,...D?{entityId:D}:{},churn:b.churn})}if(p.length===0)return{recorded:!1};let d=Vb(e,o),m=ri(e,o),f=m?.origin==="pipeline"?m.files.filter(b=>ce(b.key)?.repo!==n):[],g=m?.origin==="pipeline"?m.commits:[],y={modelFormatVersion:2,taskKey:o,origin:"pipeline",...m?.title?{title:m.title}:{},...l?{date:l}:{},commits:[...new Set([...g,i])],files:[...f,...p],links:{...m?.origin==="pipeline"?m.links:{},...d}};y.links&&Object.keys(y.links).length===0&&delete y.links;let k=[...ai(e).filter(b=>b.taskKey!==o),y],h=fm(gm(e),k,o,s.cochange.halfLifeDays);return await ke(e,[{path:kr(o),content:bn(y)},{path:wr,content:ci(h)}],`model: task event ${o}`),{recorded:!0}}async function ga(t){let e=new Set([t.fallbackTaskKey]);try{let r=ma(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(`
619
+ `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await hm(t.contextDir,r,t.prUrl)}async function hm(t,e,r){let n=ri(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await ke(t,[{path:kr(e),content:bn(o)}],`model: pr link for ${e}`)}var ha=$(()=>{"use strict";W();Je();aa();ua();oi();pa();si()});var Gn,ya=$(()=>{"use strict";ta();Xt();Gn=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return Nu(this.cfg,e)}getIssue(e,r){return Ou(this.cfg,e,r??ti(this.contextDir))}listComments(e,r){return Du(this.cfg,e,r)}downloadAttachment(e){return _u(this.cfg,e)}updateStatus(e,r){return Su(this.cfg,e,r,ti(this.contextDir))}addComment(e,r,n){return Tu(this.cfg,e,r)}createIssue(e){return Eu(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,ti(this.contextDir))}editIssue(e,r){return Ru(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Iu(this.cfg,e,r,n)}fetchStateFields(e){return Mu(this.cfg,e)}}});import{existsSync as wm,readFileSync as zb,readdirSync as Jb}from"node:fs";function li(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=e$(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Xb(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Zb(Qb(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 ui(t,e,r){if(r.length===0)return;let n=li(t,e,r),o=r.map(i=>i.issue.key);await ke(t,n,`sync(${o.join(", ")}): task data`)}function Xb(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(`
620
+ `)}function Qb(t,e,r){let n=new Map,o=ge(t,`tasks/${e}/comments.jsonl`);if(wm(o))for(let i of zb(o,"utf-8").split(`
621
+ `)){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=vr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Zb(t){return t.map(e=>JSON.stringify(e)).join(`
616
622
  `)+(t.length>0?`
617
- `:"")}function lk(t,e,r){let n=[],o=me(t,`tasks/${e}/attachments`);if(gp(o))for(let i of ik(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var Yo=k(()=>{"use strict";W();ot()});import{existsSync as uk,readFileSync as dk}from"node:fs";import{randomBytes as pk}from"node:crypto";function hp(t,e){let r=me(t,`tasks/${e}/comments.jsonl`);if(!uk(r))return[];let n=[];for(let o of dk(r,"utf-8").split(`
618
- `)){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 jn,Ws=k(()=>{"use strict";W();ot();Yo();Uo();jn=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Sn(this.contextDir);let r=e.columns??[];return Nd(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Tn(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Rn(this.contextDir,e);return r?Tn(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return hp(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 Sn(this.contextDir),!Rn(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${pk(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=fr(r);s&&(i.parsedCommand=s);let c=[...hp(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
623
+ `:"")}function e$(t,e,r){let n=[],o=ge(t,`tasks/${e}/attachments`);if(wm(o))for(let i of Jb(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var di=$(()=>{"use strict";W();Je()});import{existsSync as t$,readFileSync as r$}from"node:fs";import{randomBytes as n$}from"node:crypto";function km(t,e){let r=ge(t,`tasks/${e}/comments.jsonl`);if(!t$(r))return[];let n=[];for(let o of r$(r,"utf-8").split(`
624
+ `)){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 Kn,wa=$(()=>{"use strict";W();Je();di();Jo();Kn=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Nn(this.contextDir);let r=e.columns??[];return Xd(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Dn(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=On(this.contextDir,e);return r?Dn(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return km(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 Nn(this.contextDir),!On(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${n$(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=vr(r);s&&(i.parsedCommand=s);let c=[...km(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
619
625
  `)+`
620
- `;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 Od(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:Yi.statusColumns}]}async mutateRecord(e,r,n){let o=Rn(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Tn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:pn(e),content:Os(i)},...Wo(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:io,status:r.targetStatus,links:[],created:n,updated:n},i=Tn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:pn(e),content:Os(o)},...Wo(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}}});import{existsSync as yp,readFileSync as wp}from"node:fs";import{join as bp}from"node:path";import{parseDocument as kp}from"yaml";function qs(t){if(!t)return"youtrack";try{let e=bp(t,"project.yaml");return yp(e)&&kp(wp(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function st(t){let e=qs(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=jd(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=mk(n);return i?{ok:!0,kind:e,provider:new jn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=iu();return r?{ok:!0,kind:e,provider:new An(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function mk(t){try{let e=bp(t,"project.yaml");if(!yp(e))return null;let r=kp(wp(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Vo=k(()=>{"use strict";Jt();Hs();Ws();Uo();Hs();Ws()});async function Ar(t,e){let n=(zo.get(t)??Promise.resolve()).catch(()=>{}).then(e);zo.set(t,n);try{return await n}finally{zo.get(t)===n&&zo.delete(t)}}async function $p(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;wn(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ar(`${i}/${r.name}`,async()=>{let s=await Zt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Se(i,r.name,t.baseDir),{commit:c,pushed:l}=await zu(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});return ie({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 q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ar(`${i}/${r.name}`,async()=>{let s=await Zt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Se(i,r.name,t.baseDir);return await Ju(s,a,{branchName:e.branchName,force:e.force}),ie({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ar(`${i}/${r.name}`,async()=>{let s=await Zt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Se(i,r.name,t.baseDir),{commit:c,pushed:l}=await Xu(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ie({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return q("no repo spec");let i=He(r),s=await i.createPullRequest(r,e);return ie({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return q("no repo spec");let i=He(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ie({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return q("no repo spec");let i=He(r);return await i.closePR(r,e.prNumber,e.comment),ie({prNumber:e.prNumber,host:i.name})}case"rewrite_cluster_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ar(`${i}/${r.name}`,async()=>{let s=await Zt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Se(i,r.name,t.baseDir),{commit:c,dropped:l}=await Zu(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ie({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ar(`${i}/${r.name}`,async()=>{let s=await Zt(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Se(i,r.name,t.baseDir),{mergedSha:c}=await ed(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ie({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return q("no repo spec");let i=t.cloneUrlOverride??$n(r),a=(await td(i)).filter(u=>rd(u,e.issueKey)),c=He(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 ie({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return q("no repo spec");let i=He(r);return await i.addPRComment(r,e.prNumber,e.body),ie({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=st({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ie({issueId:t.trackerIssueId,newStatus:e.newStatus})):q("no tracker_issue_id provided"):q(i.error)}case"tracker_comment":{let i=st({contextDir:t.contextDir});if(!i.ok)return q(i.error);if(!t.trackerIssueId)return q("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ie({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=st({contextDir:t.contextDir});if(!i.ok)return q(i.error);if(!e.projectKey)return q("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 ie({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=st({contextDir:t.contextDir});if(!i.ok)return q(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 q(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ie({applied:s})}case"set_project_setting":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await lp(t.contextDir,e.edits);return ie({files:i.files})}case"tracker_edit":{let i=st({contextDir:t.contextDir});if(!i.ok)return q(i.error);if(!t.contextDir)return q("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 qo(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ie({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await fp(t.contextDir,e);return ie({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await pp(t.contextDir,e);return ie({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ie({reported:!0})):q("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return q("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ie({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return q("no project workspace on this CLI");if(!r)return q("no repo spec");if(!t.onRunActivity)return q("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=jo(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return q(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=Mc(c,e.input);if(!l.ok)return q(l.error);let u=md(t.contextDir),p=G(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),Ar(`${e.projectId}/${r.name}`,async()=>{await Zt(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=Se(e.projectId,r.name,t.baseDir),f=await np({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return ie({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=ap(t.contextDir,e.path);return ie({path:e.path,...i})}case"local_apply":return q("local_apply requires a local workspace (handled by the daemon)");default:return q(`unsupported action type: ${e.type}`)}}catch(i){return q(i instanceof Error?i.message:String(i))}}function ie(t){return{status:"done",result:t}}function q(t){return{status:"failed",error:t}}var zo,vp=k(()=>{"use strict";W();vs();op();cp();oe();up();mp();Ks();Ct();Co();xr();Vo();Yo();zo=new Map});import{existsSync as fk,mkdtempSync as gk,rmSync as hk}from"node:fs";import{tmpdir as yk}from"node:os";import{join as Ys}from"node:path";import{simpleGit as xp}from"simple-git";async function Sp(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=Ys(t.root,c.mountAs);if(!fk(Ys(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=xp(a.dir),l=a.payload;try{await c.fetch()}catch(m){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${_n(m)}`}}let u=`origin/${l.baseRef}`;await $k(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}: ${_n(m)}`}}let d;try{d=await kn(c,l.deliverySha,()=>er(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}: ${_n(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 vk(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await bk(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 kk(i,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${_n(l)} (rolled back all repos)`}}}return{ok:!0,repos:s}}async function bk(t){let e=gk(Ys(yk(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=xp(e);try{await r.raw([...wk,"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(()=>{}),hk(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function kk(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: ${_n(n)} \u2014 check manually`)}}async function $k(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function vk(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function _n(t){return t instanceof Error?t.message.trim():String(t)}var wk,Rp=k(()=>{"use strict";xr();wk=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as xk}from"node:os";import{existsSync as Sk,mkdirSync as Rk,readFileSync as Tk,writeFileSync as Ck}from"node:fs";import{dirname as Ik,join as Ek}from"node:path";function Vs(){return H("FARM_PINS")??Ek(xk(),".codepipe","farm-pins.json")}function Tp(){let t=Vs();if(!Sk(t))return{};try{return JSON.parse(Tk(t,"utf-8"))}catch{return{}}}function Pk(t){let e=Vs();Rk(Ik(e),{recursive:!0}),Ck(e,JSON.stringify(t,null,2)+`
621
- `,{mode:384})}function Ak(t){return Tp()[t]}function Jo(t,e){let r=Tp();r[t]=e,Pk(r)}function Xo(t,e){let r=Re(e),n=Ak(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 ${Vs()}.`);return r}var zs=k(()=>{"use strict";xe();Le()});import{existsSync as Cp,readFileSync as Ip}from"node:fs";import{join as Ep}from"node:path";async function Pp(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=Re(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Xo(e.farmId,e.farmPublicKey);let s=G(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await Q(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Ep(r,"project.yaml"),m=Ep(r,"regimen.yaml");Cp(d)&&Cp(m)?c={projectYaml:Ip(d,"utf-8"),regimenYaml:Ip(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=gt(e.farmPublicKey,JSON.stringify(l));Jo(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await Ro(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 Ap=k(()=>{"use strict";Le();zs();we();oe()});import{homedir as jk}from"node:os";import{existsSync as _k,mkdirSync as Nk,readFileSync as Ok,writeFileSync as Dk}from"node:fs";import{dirname as Lk,join as Mk}from"node:path";function Js(){return H("RUNNER_PINS")??Mk(jk(),".codepipe","runner-pins.json")}function jp(){let t=Js();if(!_k(t))return{};try{return JSON.parse(Ok(t,"utf-8"))}catch{return{}}}function Uk(t){let e=Js();Nk(Lk(e),{recursive:!0}),Dk(e,JSON.stringify(t,null,2)+`
622
- `,{mode:384})}function Bk(t){return jp()[t]}function Xs(t,e){let r=jp();r[t]=e,Uk(r)}function _p(t,e){let r=Re(e),n=Bk(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 ${Js()}.`);return r}var Np=k(()=>{"use strict";xe();Le()});async function Op(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Dp(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 Mp(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(Re(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");_p(e.runnerId,e.runnerPublicKey);let i=G(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 Up(t,e,r,n=Lp){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 Mp(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:[Vc(e.runnerId)]},c=gt(e.runnerPublicKey,JSON.stringify(a));Xs(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 Bp(t,e,r,n=Lp){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 Mp(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=gt(e.runnerPublicKey,JSON.stringify(c));Xs(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 Dp,Fk,Lp,Fp=k(()=>{"use strict";W();Le();Np();we();oe();Dp=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});Fk={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Dp(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)=>Op(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Op(t,e,r,"remove-token")},Lp={api:Fk,fetchProject:Q,provisionOnRunner:Nu,teardownOnRunner:Ou}});function Gk(t){return _e.test(t)?vt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${_e}`}function Kp(t,e,r,n){let o=Gk(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Er(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>Gp)return{ok:!1,detail:`secret value too large (max ${Gp} chars)`};try{return jl(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Hp(t,e){try{return _l(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 Gp,Wp=k(()=>{"use strict";W();Le();oe();Gp=16*1024});function Kk(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Qo,qp=k(()=>{"use strict";Ct();Qo=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=He(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 zt){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=He(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=Kk(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}}});function Yp(t){let{description:e,...r}=t;return r}function Hk(t){let{body:e,...r}=t;return r}function Wk(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 qk(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 Vp(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 Zo,zp=k(()=>{"use strict";W();Yo();Vo();Zo=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??(()=>st({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}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},E=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(E){let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[A,M]=await Promise.all([v.length>0?r.listIssues({projectKey:e.projectKey,columns:v,...$,...S}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...$})]),K=new Map;for(let P of[...A,...M])K.set(P.id,P);o=[...K.values()]}else{let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:v,...$,...S})}}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 S=await Vp(r,$.id,e.sinceMs,this.log);S&&i.set($.id,S)}let c=[];for(let $ of e.offBoardIssueIds){if(s.has($))continue;let S=await Vp(r,$,e.sinceMs,this.log);if(S&&S.length>0&&i.set($,S),e.requireAssignee||S&&S.length>0){let D=await qk(r,$,e.stageField,this.log);if(D)c.push(D);else if(S&&S.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 qo(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let $ of p)this.shippedAttachments.add($)}catch($){let S=$ instanceof Error?$.message:String($);this.abandonTick(`context task sync failed: ${S}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[$,S]of i){let D=S.filter(v=>!m(v.id));if(D.length===0)continue;f.push({issueId:$,comments:D.map(Hk)});let E=D.flatMap(v=>{let A=fr(v.body);return A?[{commentId:v.id,author:v.author,name:A.name,args:A.args,createdAt:v.createdAt}]:[]});E.length>0&&g.push({issueId:$,commands:E})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Yp),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Yp)}:{},observedAtMs:n};this.send(y);let b=f.reduce(($,S)=>$+S.comments.length,0),h=g.reduce(($,S)=>$+S.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${b} 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(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=Wk(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 Xp,rmSync as Yk}from"node:fs";import{join as Nn}from"node:path";import{simpleGit as Vk}from"simple-git";import"ws";function ei(t,e={}){let r=e.log??{info:g=>console.log(g),warn:g=>console.warn(g)};r.info(`codepipe-cli v${je} (protocol ${Xe})`);let n=g=>e.onEvent?.(g),o=e.workspace;o?.contextDir&&yd(o.contextDir,r);let i=Jp("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Jp("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,m=f();function f(){let g=So(t.hubUrl,t.cliToken),y=null,b=new Qo(i,I=>{g.readyState===g.OPEN&&g.send(JSON.stringify(I))},r),h=new Zo(s,I=>{g.readyState===g.OPEN&&g.send(JSON.stringify(I))},r,{contextDir:o?.contextDir??null,isSelfComment:I=>d.has(I)}),$=null,S=async()=>{try{let I={trackerProvider:qs(o?.contextDir??null)};try{let j=await Q(t.hubUrl,t.cliToken,t.projectId);I={...I,repos:j.repos,contextRepo:j.contextRepo}}catch(j){r.warn(`[readiness] could not fetch project summary for push checks: ${j instanceof Error?j.message:String(j)}`)}let T=await xu(t.projectId,I);if(g.readyState!==g.OPEN)return;let R={type:"cli_readiness",projectId:t.projectId,ready:T.ready,checks:T.checks,creds:T.creds,secretNames:Nl(t.projectId),checkedAt:T.checkedAt};if(g.send(JSON.stringify(R)),T.ready)r.info("[readiness] ready");else{let j=T.checks.filter(x=>!x.ok).map(x=>`${x.name}(${x.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${j.join(", ")}`)}let N=Pu(T.creds,u);if(N==="open"){u=!0;let j=Au(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${j}`),Xt(j)}else N==="rearm"&&(u=!1)}catch(I){r.warn(`[readiness] check failed: ${I instanceof Error?I.message:String(I)}`)}},D=()=>{S(),$=setInterval(()=>void S(),a),typeof $.unref=="function"&&$.unref()},E=()=>{$&&(clearInterval($),$=null)},v=150,A=new Map,M=I=>{let T=A.get(I);if(!T||(T.timer&&clearTimeout(T.timer),A.delete(I),T.events.length===0||g.readyState!==g.OPEN))return;let R={type:"run_activity",projectId:t.projectId,runId:I,events:T.events};g.send(JSON.stringify(R))},K=(I,T)=>{let R=A.get(I);if(R||(R={events:[],timer:null},A.set(I,R)),R.events.push(T),T.kind==="result"){M(I);return}R.timer||(R.timer=setTimeout(()=>M(I),v),R.timer.unref?.())},P=o?.contextDir?new _o(o.contextDir,t.projectId,I=>{g.readyState===g.OPEN&&g.send(JSON.stringify(I))},r):null,w=async()=>{let I=o?.contextDir;if(!I)throw new Error("no context repo clone on this CLI");let T;try{T=(await Q(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let R=await Bd(I,t.projectId,T,r);return g.readyState===g.OPEN&&g.send(JSON.stringify(R)),R};return g.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let I=Gl(t.projectId),T=H("ORIGIN")==="farm"?"farm":"local",R=H("FARM_ID"),N=t.accountEmail??I.email,j;try{let C=Qd(t.projectId);C&&(j=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 x={type:"register",projectId:t.projectId,platformVersion:je,protocolVersion:Xe,accountId:I.accountId,accountLabel:I.label,origin:T,inFlightActionIds:[...p],...N?{accountEmail:N}:{},...T==="farm"&&R?{farmId:R}:{},...j?{sealPublicKey:j}:{}};g.send(JSON.stringify(x))}),g.on("message",async I=>{let T=I.toString("utf-8");if(T==="pong"||T==="ping")return;let R;try{R=JSON.parse(T)}catch{return}if(!R||typeof R!="object")return;let N=R.type;if(N==="registered"){let x=R;if(x.ok){if(r.info(`[ws] registered for project ${x.projectId}`),n({kind:"registered",projectId:x.projectId??t.projectId}),b.start(),P?.start(),D(),Zs(t,o,r),o?.contextDir)try{let C=Mo(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,w().catch(()=>{})))}catch(C){r.warn(`[ctx] context-format detect failed (non-fatal): ${C instanceof Error?C.message:String(C)}`)}}else r.warn(`[ws] register rejected: ${x.reason??"unknown"}`),n({kind:"register_rejected",reason:x.reason??"unknown"}),c=!0,g.close();return}if(N==="hello"){let x=R;y=to(x.protocolVersion);let C=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${x.platformVersion} (protocol ${x.protocolVersion}) \u2014 ${C}`),y||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${je}, protocol ${Xe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Qs}`),n({kind:"incompatible",hubVersion:typeof x.platformVersion=="string"?x.platformVersion:null,hubProtocol:typeof x.protocolVersion=="number"?x.protocolVersion:null,updateCommand:Qs}));return}if(N==="tracking_targets"){b.setTargets(R.targets);return}if(N==="youtrack_sync_request"){h.setRequest(R);return}if(N==="youtrack_force_sync"){h.forceSync();return}if(N==="sync_local"){await Xk(R,o,g,r);return}if(N==="provision_repo"){let x=R;r.info(`[repo] provision_repo: ${x.repo.name} (${x.repo.host}:${x.repo.owner}/${x.repo.repoName})`),await zk(t,o,x.repo,r),await Zs(t,o,r);return}if(N==="remove_repo"){let x=R;r.info(`[repo] remove_repo: ${x.repoName}${x.purge?" (purge)":""}`),await Zs(t,o,r),x.purge&&Jk(t,o,x.repoName,r);return}if(N==="context_write"){await Qk(R,o,g,r);return}if(N==="adr_promote"){await Zk(R,o,g,r);return}if(N==="cred_update"){let x=R,C=G(t.projectId),L=C?.sealKey?await Zd(t.projectId,x.kind,x.sealed,C.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},z={type:"cred_update_result",updateId:x.updateId,projectId:t.projectId,ok:L.ok,...L.detail?{detail:L.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(z)),L.ok?(r.info(`[cred] ${x.kind} replaced${L.detail?` \u2014 ${L.detail}`:""}`),S()):r.warn(`[cred] ${x.kind} replacement rejected: ${L.detail??"unknown"}`);return}if(N==="readiness_check"){r.info("[readiness] on-demand check requested"),S();return}if(N==="agent_login_start"){Iu(t,g,R,r,S);return}if(N==="move_to_farm"){let x=R;r.info(`[farm-move] request to move ${t.projectId} onto farm ${x.farmName} (${x.farmId})`);let C=await Pp(t,x,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(N==="gh_runner_setup"){let x=R;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${x.runnerName} (${x.runnerId})`);let C=await Up(t,x,r);g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C.ok?r.info(`[ghr] runners connected on ${x.runnerName}`):r.warn(`[ghr] setup failed: ${C.error??"see per-repo statuses"}`);return}if(N==="gh_runner_teardown"){let x=R;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${x.runnerName} (${x.runnerId})`);let C=await Bp(t,x,r);g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C.ok?r.info(`[ghr] runners disconnected from ${x.runnerName}`):r.warn(`[ghr] teardown failed: ${C.error??"unknown error"}`);return}if(N==="tracker_fields_request"){let x=R,C={type:"tracker_fields_result",requestId:x.requestId,projectId:t.projectId,ok:!1},L=st({contextDir:o?.contextDir??null});if(!L.ok)C.error=L.error;else try{C.fields=await L.provider.fetchStateFields(x.projectKey),C.ok=!0}catch(z){C.error=z instanceof Error?z.message:String(z)}g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C.ok||r.warn(`[yt-fields] listing failed: ${C.error??"unknown"}`);return}if(N==="project_secret_update"||N==="project_secret_delete"){let x=R,C;if(x.type==="project_secret_update"){let z=G(t.projectId);C=z?.sealKey?Kp(t.projectId,x.name,x.sealed,z.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else C=Hp(t.projectId,x.name);let L={type:"project_secret_update_result",updateId:x.updateId,projectId:t.projectId,ok:C.ok,...C.detail?{detail:C.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(L)),C.ok?(r.info(`[secret] ${x.name} ${x.type==="project_secret_update"?"saved":"deleted"}`+(C.detail?` \u2014 ${C.detail}`:"")),S()):r.warn(`[secret] ${x.name} rejected: ${C.detail??"unknown"}`);return}if(N==="auto_apply_local"){let x=R;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${x.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let C=await sd({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},x.claim,r).catch(L=>({ok:!1,message:L instanceof Error?L.message:String(L)}));C.ok?r.info(`[apply] ${x.claim.taskKey}: ${C.message}`):r.warn(`[apply] ${x.claim.taskKey}: ${C.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:x.claim.taskKey,ok:C.ok,...C.ok?{branches:C.branches??[]}:{error:C.message}});return}if(N==="sandbox_keys"){let x=G(t.projectId);if(!x){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let C=wr(t.projectId),L=Yd(R,x,C,r);for(let z of L)g.readyState===g.OPEN&&g.send(JSON.stringify(z));return}if(N!=="dispatch_action")return;let j=R;if(y===!1){let x=`refused: HUB protocol incompatible with CLI v${je} (protocol ${Xe})`;g.send(JSON.stringify({type:"action_result",actionId:j.actionId,status:"failed",error:x})),r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 REFUSED: ${x}`),r.warn(`[exec] update the CLI to clear this: ${Qs}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:!1,error:x});return}if(j.action.type==="local_apply"){p.add(j.actionId);try{let x;if(!o)x={status:"failed",error:"no local workspace on this CLI"};else{let L=await Sp(o,j.action.repos,r);x=L.ok?{status:"done",result:{repos:L.repos}}:{status:"failed",error:L.error}}g.send(JSON.stringify({type:"action_result",actionId:j.actionId,...x}));let C=x.status!=="failed";C?r.info(`[exec] ${j.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${j.actionId} (local_apply) \u2192 FAILED: ${x.status==="failed"?x.error:"?"}`),n({kind:"action",actionId:j.actionId,actionType:"local_apply",ok:C,...x.status==="failed"?{error:x.error}:{}})}finally{p.delete(j.actionId)}return}p.add(j.actionId);try{let x=await $p({action:j.action,repo:j.repo,trackerIssueId:j.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:P?()=>P.reportNow():void 0,refreshContextStatus:o?.contextDir?w:void 0,onRunActivity:K}).catch(z=>({status:"failed",error:z instanceof Error?z.message:String(z)}));j.action.type==="tracker_comment"&&x.status==="done"&&"result"in x&&typeof x.result?.commentId=="string"&&d.add(x.result.commentId),g.send(JSON.stringify({type:"action_result",actionId:j.actionId,...x}));let C=x.status!=="failed",L=!C&&"error"in x?x.error:void 0;C?r.info(`[exec] ${j.actionId} (${j.action.type}) \u2192 done`):r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 FAILED: ${L??"?"}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:C,...L?{error:L}:{}})}finally{p.delete(j.actionId)}}),g.on("close",(I,T)=>{let R=T?.toString("utf-8")??"";if(r.info(`[ws] closed code=${I}${R?` reason=${R}`:""}`),b.stop(),h.stop(),P?.stop(),E(),R==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:I}),!c&&setTimeout(()=>{m=f()},2e3)}),g.on("error",I=>r.warn(`[ws] error: ${I.message}`)),g}return{stop(){c=!0,m.close()}}}async function Zs(t,e,r){try{let n=await Q(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Cn(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 zk(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?Nn(e.root,o):Se(t.projectId,r.name);if(Xp(Nn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await Vk().clone($n(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 Jk(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Nn(e.root,o):Se(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Xp(Nn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Yk(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 Xk(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=Nn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await cd(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 Qk(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 Zk(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 Sd(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 Jp(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var Qs,ea=k(()=>{"use strict";xe();W();Kl();Eu();ju();xo();ks();ld();gd();Rd();ot();ft();js();Fd();Ls();xr();Vd();ep();vp();Rp();Ap();Fp();we();Wp();vr();oe();qp();zp();Vo();Qs="npm i -g @code-partner/codepipe@latest"});import{execFileSync as e$}from"node:child_process";import{mkdtempSync as t$,mkdirSync as r$,readFileSync as Qp,rmSync as n$,writeFileSync as o$}from"node:fs";import{tmpdir as i$}from"node:os";import{dirname as s$,join as Zp}from"node:path";function em(t="codepipe-context"){let e=t$(Zp(i$(),"codepipe-ssh-")),r=Zp(e,"id_ed25519");try{return e$("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Qp(r,"utf-8"),publicKey:Qp(`${r}.pub`,"utf-8").trim()}}finally{n$(e,{recursive:!0,force:!0})}}async function tm(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 rm(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 nm(t,e){r$(s$(t),{recursive:!0});let r=e.endsWith(`
626
+ `;return await ke(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 Qd(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:is.statusColumns}]}async mutateRecord(e,r,n){let o=On(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Dn(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:xn(e),content:qs(i)},...li(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await ke(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:yo,status:r.targetStatus,links:[],created:n,updated:n},i=Dn(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:xn(e),content:qs(o)},...li(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}}});import{existsSync as bm,readFileSync as $m}from"node:fs";import{join as vm}from"node:path";import{parseDocument as xm}from"yaml";function ka(t){if(!t)return"youtrack";try{let e=vm(t,"project.yaml");return bm(e)&&xm($m(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function lt(t){let e=ka(t.contextDir);if(e==="internal"){let n=t.contextDir;if(!n)return{ok:!1,kind:e,error:"internal tracker: no Context Repo clone on this CLI"};let o=zd(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=o$(n);return i?{ok:!0,kind:e,provider:new Kn(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=vu();return r?{ok:!0,kind:e,provider:new Gn(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function o$(t){try{let e=vm(t,"project.yaml");if(!bm(e))return null;let r=xm($m(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var pi=$(()=>{"use strict";Xt();ya();wa();Jo();ya();wa()});async function Br(t,e){let n=(mi.get(t)??Promise.resolve()).catch(()=>{}).then(e);mi.set(t,n);try{return await n}finally{mi.get(t)===n&&mi.delete(t)}}async function Sm(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;Zt(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Br(`${i}/${r.name}`,async()=>{let s=await tr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{commit:c,pushed:l}=await pd(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 fa({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:u,commitSha:c}).catch(p=>{Zt(`[model] task event for ${u} failed: ${p instanceof Error?p.message:String(p)}`)})}return ie({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Br(`${i}/${r.name}`,async()=>{let s=await tr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir);return await md(s,a,{branchName:e.branchName,force:e.force}),ie({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"early_branch":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Br(`${i}/${r.name}`,async()=>{let s=await tr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{commit:c,pushed:l}=await fd(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ie({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return Y("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:$e(c,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:a,prUrl:s.url}).catch(l=>{Zt(`[model] pr link for ${a} failed: ${l instanceof Error?l.message:String(l)}`)})}return ie({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return Y("no repo spec");let i=qe(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ie({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return Y("no repo spec");let i=qe(r);return await i.closePR(r,e.prNumber,e.comment),ie({prNumber:e.prNumber,host:i.name})}case"rewrite_cluster_branch":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Br(`${i}/${r.name}`,async()=>{let s=await tr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{commit:c,dropped:l}=await hd(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:r.defaultBranch});return ie({branch:e.branchName,commit:c,dropped:l,pushed:l>0})})}case"merge_branch":{if(!r)return Y("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Br(`${i}/${r.name}`,async()=>{let s=await tr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{mergedSha:c}=await yd(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ie({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Y("no repo spec");let i=t.cloneUrlOverride??An(r),a=(await wd(i)).filter(u=>kd(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 ie({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Y("no repo spec");let i=qe(r);return await i.addPRComment(r,e.prNumber,e.body),ie({prNumber:e.prNumber,host:i.name})}case"tracker_status":{let i=lt({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ie({issueId:t.trackerIssueId,newStatus:e.newStatus})):Y("no tracker_issue_id provided"):Y(i.error)}case"tracker_comment":{let i=lt({contextDir:t.contextDir});if(!i.ok)return Y(i.error);if(!t.trackerIssueId)return Y("no tracker_issue_id provided");let s=await i.provider.addComment(t.trackerIssueId,e.body,e.author);return ie({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=lt({contextDir:t.contextDir});if(!i.ok)return Y(i.error);if(!e.projectKey)return Y("no projectKey in create_tracker_issue action");let{id:s,key:a}=await i.provider.createIssue({projectKey:e.projectKey,title:e.title,body:e.body,targetStatus:e.targetStatus});return ie({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=lt({contextDir:t.contextDir});if(!i.ok)return Y(i.error);let s=0;for(let a of e.links)try{await i.provider.applyLink(a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return Y(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ie({applied:s})}case"set_project_setting":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=await Rp(t.contextDir,e.edits);return ie({files:i.files})}case"tracker_edit":{let i=lt({contextDir:t.contextDir});if(!i.ok)return Y(i.error);if(!t.contextDir)return Y("no context repo clone on this CLI");await i.provider.editIssue(e.issueKey,{...e.title!==void 0?{title:e.title}:{},...e.body!==void 0?{body:e.body}:{}});let s=await i.provider.getIssue(e.issueKey);return s&&await ui(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ie({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=await Ap(t.contextDir,e);return ie({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=await Ip(t.contextDir,e);return ie({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ie({reported:!0})):Y("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return Y("no context repo clone on this CLI");let i=await t.refreshContextStatus();return ie({outdated:i.outdated,templateVersion:i.templateVersion})}case"run_action":{if(!t.contextDir)return Y("no project workspace on this CLI");if(!r)return Y("no repo spec");if(!t.onRunActivity)return Y("no run-activity stream on this CLI");let i=t.onRunActivity,{defs:s,errors:a}=Ko(t.contextDir),c=s.find(m=>m.id===e.actionId);if(!c){let m=a.find(f=>f.file===`actions/${e.actionId}.yml`);return Y(m?`action "${e.actionId}" failed to parse: ${m.error}`:`unknown action "${e.actionId}"`)}let l=tl(c,e.input);if(!l.ok)return Y(l.error);let u=Pd(t.contextDir),p=G(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),Br(`${e.projectId}/${r.name}`,async()=>{await tr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let m=$e(e.projectId,r.name,t.baseDir),f=await bp({cwd:m,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:g=>i(e.runId,g)});return ie({runId:e.runId,status:f.status,exitCode:f.exitCode,...f.failedStep?{failedStep:f.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Y("no context repo clone on this CLI");let i=Sp(t.contextDir,e.path);return ie({path:e.path,...i})}case"local_apply":return Y("local_apply requires a local workspace (handled by the daemon)");default:return Y(`unsupported action type: ${e.type}`)}}catch(i){return Y(i instanceof Error?i.message:String(i))}}function ie(t){return{status:"done",result:t}}function Y(t){return{status:"failed",error:t}}var mi,Tm=$(()=>{"use strict";W();Ns();$p();Tp();oe();Cp();Pp();ta();Et();Mo();Ar();ha();pi();di();mi=new Map});import{existsSync as i$,mkdtempSync as s$,rmSync as a$}from"node:fs";import{tmpdir as c$}from"node:os";import{join as ba}from"node:path";import{simpleGit as Rm}from"simple-git";async function Cm(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=ba(t.root,c.mountAs);if(!i$(ba(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=Rm(a.dir),l=a.payload;try{await c.fetch()}catch(m){return{ok:!1,error:`fetch failed in ${a.mountAs}: ${Hn(m)}`}}let u=`origin/${l.baseRef}`;await p$(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}: ${Hn(m)}`}}let d;try{d=await Pn(c,l.deliverySha,()=>rr(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}: ${Hn(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 m$(a.git,`refs/heads/${a.branch}`);try{let u=(await a.git.revparse([`${a.deliveryCommit}^`])).trim()===a.startPoint?a.deliveryCommit:await u$(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 d$(i,r),{ok:!1,error:`apply failed in ${a.mountAs}: ${Hn(l)} (rolled back all repos)`}}}return{ok:!0,repos:s}}async function u$(t){let e=s$(ba(c$(),"codepipe-local-apply-"));try{await t.git.raw(["worktree","add","--detach",e,t.startPoint]);let r=Rm(e);try{await r.raw([...l$,"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(()=>{}),a$(e,{recursive:!0,force:!0}),await t.git.raw(["worktree","prune"]).catch(()=>{})}}async function d$(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: ${Hn(n)} \u2014 check manually`)}}async function p$(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function m$(t,e){try{return(await t.raw(["rev-parse","--verify","--quiet",e])).trim()||null}catch{return null}}function Hn(t){return t instanceof Error?t.message.trim():String(t)}var l$,Em=$(()=>{"use strict";Ar();l$=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{homedir as f$}from"node:os";import{existsSync as g$,mkdirSync as h$,readFileSync as y$,writeFileSync as w$}from"node:fs";import{dirname as k$,join as b$}from"node:path";function $a(){return H("FARM_PINS")??b$(f$(),".codepipe","farm-pins.json")}function Im(){let t=$a();if(!g$(t))return{};try{return JSON.parse(y$(t,"utf-8"))}catch{return{}}}function $$(t){let e=$a();h$(k$(e),{recursive:!0}),w$(e,JSON.stringify(t,null,2)+`
627
+ `,{mode:384})}function v$(t){return Im()[t]}function fi(t,e){let r=Im();r[t]=e,$$(r)}function gi(t,e){let r=Ce(e),n=v$(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 ${$a()}.`);return r}var va=$(()=>{"use strict";Re();Ue()});import{existsSync as Pm,readFileSync as Am}from"node:fs";import{join as jm}from"node:path";async function _m(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=Ce(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");gi(e.farmId,e.farmPublicKey);let s=G(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await Q(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=jm(r,"project.yaml"),m=jm(r,"regimen.yaml");Pm(d)&&Pm(m)?c={projectYaml:Am(d,"utf-8"),regimenYaml:Am(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=wt(e.farmPublicKey,JSON.stringify(l));fi(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await Do(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 Nm=$(()=>{"use strict";Ue();va();we();oe()});import{homedir as x$}from"node:os";import{existsSync as S$,mkdirSync as T$,readFileSync as R$,writeFileSync as C$}from"node:fs";import{dirname as E$,join as I$}from"node:path";function xa(){return H("RUNNER_PINS")??I$(x$(),".codepipe","runner-pins.json")}function Om(){let t=xa();if(!S$(t))return{};try{return JSON.parse(R$(t,"utf-8"))}catch{return{}}}function P$(t){let e=xa();T$(E$(e),{recursive:!0}),C$(e,JSON.stringify(t,null,2)+`
628
+ `,{mode:384})}function A$(t){return Om()[t]}function Sa(t,e){let r=Om();r[t]=e,P$(r)}function Dm(t,e){let r=Ce(e),n=A$(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 Lm=$(()=>{"use strict";Re();Ue()});async function Mm(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Um(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 Fm(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(Ce(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Dm(e.runnerId,e.runnerPublicKey);let i=G(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 Gm(t,e,r,n=Bm){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 Fm(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:[dl(e.runnerId)]},c=wt(e.runnerPublicKey,JSON.stringify(a));Sa(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 Km(t,e,r,n=Bm){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 Fm(t,e,n),a={owner:s.owner,repo:s.repoName};try{a.removeToken=await n.api.mintRemoveToken(i,s.owner,s.repoName)}catch(p){r.warn(`[ghr] remove-token for ${s.owner}/${s.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`)}let c={projectId:t.projectId,runners:[a]},l=wt(e.runnerPublicKey,JSON.stringify(c));Sa(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 Um,j$,Bm,Hm=$(()=>{"use strict";W();Ue();Lm();we();oe();Um=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});j$={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Um(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)=>Mm(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Mm(t,e,r,"remove-token")},Bm={api:j$,fetchProject:Q,provisionOnRunner:Xu,teardownOnRunner:Qu}});function _$(t){return Oe.test(t)?xt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${Oe}`}function Ym(t,e,r,n){let o=_$(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Lr(n,r).toString("utf-8"));if(typeof s.value!="string"||s.value.length===0)return{ok:!1,detail:"payload has no value"};i=s.value}catch(s){return{ok:!1,detail:`cannot open the sealed secret (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}if(i.length>Wm)return{ok:!1,detail:`secret value too large (max ${Wm} chars)`};try{return zl(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function qm(t,e){try{return Jl(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 Wm,Vm=$(()=>{"use strict";W();Ue();oe();Wm=16*1024});function N$(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var hi,zm=$(()=>{"use strict";Et();hi=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 Jt){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=N$(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}}});function Jm(t){let{description:e,...r}=t;return r}function O$(t){let{body:e,...r}=t;return r}function D$(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 L$(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 Xm(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var yi,Qm=$(()=>{"use strict";W();di();pi();yi=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??(()=>lt({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let b=e.stageField?{stageField:e.stageField}:{},S=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},I=(e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(I){let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[A,M]=await Promise.all([v.length>0?r.listIssues({projectKey:e.projectKey,columns:v,...b,...S}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...b})]),K=new Map;for(let P of[...A,...M])K.set(P.id,P);o=[...K.values()]}else{let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:v,...b,...S})}}catch(b){this.log.warn(`[yt-sync] listIssues failed: ${b instanceof Error?b.message:String(b)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let b of o){if(s.add(b.id),a.has(b.status))continue;let S=await Xm(r,b.id,e.sinceMs,this.log);S&&i.set(b.id,S)}let c=[];for(let b of e.offBoardIssueIds){if(s.has(b))continue;let S=await Xm(r,b,e.sinceMs,this.log);if(S&&S.length>0&&i.set(b,S),e.requireAssignee||S&&S.length>0){let D=await L$(r,b,e.stageField,this.log);if(D)c.push(D);else if(S&&S.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(b=>!a.has(b.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(b=>({issue:b,comments:i.get(b.id)??[],attachments:u.get(b.id)??[]}));try{await ui(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let b of p)this.shippedAttachments.add(b)}catch(b){let S=b instanceof Error?b.message:String(b);this.abandonTick(`context task sync failed: ${S}`);return}let m=this.options.isSelfComment??(()=>!1),f=[],g=[];for(let[b,S]of i){let D=S.filter(v=>!m(v.id));if(D.length===0)continue;f.push({issueId:b,comments:D.map(O$)});let I=D.flatMap(v=>{let A=vr(v.body);return A?[{commentId:v.id,author:v.author,name:A.name,args:A.args,createdAt:v.createdAt}]:[]});I.length>0&&g.push({issueId:b,commands:I})}let y={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Jm),commentsBatch:f,...g.length>0?{commandsBatch:g}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Jm)}:{},observedAtMs:n};this.send(y);let k=f.reduce((b,S)=>b+S.comments.length,0),h=g.reduce((b,S)=>b+S.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${k} 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(f){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${f instanceof Error?f.message:String(f)}`);continue}let m=D$(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 ef,rmSync as M$}from"node:fs";import{join as Fr}from"node:path";import{simpleGit as U$}from"simple-git";import"ws";function wi(t,e={}){let r=e.log??{info:g=>console.log(g),warn:g=>console.warn(g)};r.info(`codepipe-cli v${Ne} (protocol ${et})`);let n=g=>e.onEvent?.(g),o=e.workspace;o?.contextDir&&Nd(o.contextDir,r);let i=Zm("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Zm("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,m=f();function f(){let g=Oo(t.hubUrl,t.cliToken),y=null,k=new hi(i,E=>{g.readyState===g.OPEN&&g.send(JSON.stringify(E))},r),h=new yi(s,E=>{g.readyState===g.OPEN&&g.send(JSON.stringify(E))},r,{contextDir:o?.contextDir??null,isSelfComment:E=>d.has(E)}),b=null,S=async()=>{try{let E={trackerProvider:ka(o?.contextDir??null)};try{let j=await Q(t.hubUrl,t.cliToken,t.projectId);E={...E,repos:j.repos,contextRepo:j.contextRepo}}catch(j){r.warn(`[readiness] could not fetch project summary for push checks: ${j instanceof Error?j.message:String(j)}`)}let R=await Bu(t.projectId,E);if(g.readyState!==g.OPEN)return;let T={type:"cli_readiness",projectId:t.projectId,ready:R.ready,checks:R.checks,creds:R.creds,secretNames:Xl(t.projectId),checkedAt:R.checkedAt};if(g.send(JSON.stringify(T)),R.ready)r.info("[readiness] ready");else{let j=R.checks.filter(x=>!x.ok).map(x=>`${x.name}(${x.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${j.join(", ")}`)}let N=qu(R.creds,u);if(N==="open"){u=!0;let j=Vu(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${j}`),Qt(j)}else N==="rearm"&&(u=!1)}catch(E){r.warn(`[readiness] check failed: ${E instanceof Error?E.message:String(E)}`)}},D=()=>{S(),b=setInterval(()=>void S(),a),typeof b.unref=="function"&&b.unref()},I=()=>{b&&(clearInterval(b),b=null)},v=150,A=new Map,M=E=>{let R=A.get(E);if(!R||(R.timer&&clearTimeout(R.timer),A.delete(E),R.events.length===0||g.readyState!==g.OPEN))return;let T={type:"run_activity",projectId:t.projectId,runId:E,events:R.events};g.send(JSON.stringify(T))},K=(E,R)=>{let T=A.get(E);if(T||(T={events:[],timer:null},A.set(E,T)),T.events.push(R),R.kind==="result"){M(E);return}T.timer||(T.timer=setTimeout(()=>M(E),v),T.timer.unref?.())},P=o?.contextDir?new Ho(o.contextDir,t.projectId,E=>{g.readyState===g.OPEN&&g.send(JSON.stringify(E))},r):null,w=async()=>{let E=o?.contextDir;if(!E)throw new Error("no context repo clone on this CLI");let R;try{R=(await Q(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let T=await np(E,t.projectId,R,r);return g.readyState===g.OPEN&&g.send(JSON.stringify(T)),T};return g.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let E=iu(t.projectId),R=H("ORIGIN")==="farm"?"farm":"local",T=H("FARM_ID"),N=t.accountEmail??E.email,j;try{let C=gp(t.projectId);C&&(j=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 x={type:"register",projectId:t.projectId,platformVersion:Ne,protocolVersion:et,accountId:E.accountId,accountLabel:E.label,origin:R,inFlightActionIds:[...p],...N?{accountEmail:N}:{},...R==="farm"&&T?{farmId:T}:{},...j?{sealPublicKey:j}:{}};g.send(JSON.stringify(x))}),g.on("message",async E=>{let R=E.toString("utf-8");if(R==="pong"||R==="ping")return;let T;try{T=JSON.parse(R)}catch{return}if(!T||typeof T!="object")return;let N=T.type;if(N==="registered"){let x=T;if(x.ok){if(r.info(`[ws] registered for project ${x.projectId}`),n({kind:"registered",projectId:x.projectId??t.projectId}),k.start(),P?.start(),D(),Ra(t,o,r),o?.contextDir)try{let C=zo(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,w().catch(()=>{})))}catch(C){r.warn(`[ctx] context-format detect failed (non-fatal): ${C instanceof Error?C.message:String(C)}`)}}else r.warn(`[ws] register rejected: ${x.reason??"unknown"}`),n({kind:"register_rejected",reason:x.reason??"unknown"}),c=!0,g.close();return}if(N==="hello"){let x=T;y=lo(x.protocolVersion);let C=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${x.platformVersion} (protocol ${x.protocolVersion}) \u2014 ${C}`),y||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${Ne}, protocol ${et}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Ta}`),n({kind:"incompatible",hubVersion:typeof x.platformVersion=="string"?x.platformVersion:null,hubProtocol:typeof x.protocolVersion=="number"?x.protocolVersion:null,updateCommand:Ta}));return}if(N==="tracking_targets"){k.setTargets(T.targets);return}if(N==="youtrack_sync_request"){h.setRequest(T);return}if(N==="youtrack_force_sync"){h.forceSync();return}if(N==="sync_local"){await G$(T,o,g,r);return}if(N==="provision_repo"){let x=T;r.info(`[repo] provision_repo: ${x.repo.name} (${x.repo.host}:${x.repo.owner}/${x.repo.repoName})`),await B$(t,o,x.repo,r),await Ra(t,o,r);return}if(N==="remove_repo"){let x=T;r.info(`[repo] remove_repo: ${x.repoName}${x.purge?" (purge)":""}`),await Ra(t,o,r),x.purge&&F$(t,o,x.repoName,r);return}if(N==="context_write"){await K$(T,o,g,r);return}if(N==="adr_promote"){await H$(T,o,g,r);return}if(N==="cred_update"){let x=T,C=G(t.projectId),L=C?.sealKey?await hp(t.projectId,x.kind,x.sealed,C.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},q={type:"cred_update_result",updateId:x.updateId,projectId:t.projectId,ok:L.ok,...L.detail?{detail:L.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(q)),L.ok?(r.info(`[cred] ${x.kind} replaced${L.detail?` \u2014 ${L.detail}`:""}`),S()):r.warn(`[cred] ${x.kind} replacement rejected: ${L.detail??"unknown"}`);return}if(N==="readiness_check"){r.info("[readiness] on-demand check requested"),S();return}if(N==="agent_login_start"){Wu(t,g,T,r,S);return}if(N==="move_to_farm"){let x=T;r.info(`[farm-move] request to move ${t.projectId} onto farm ${x.farmName} (${x.farmId})`);let C=await _m(t,x,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(N==="gh_runner_setup"){let x=T;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${x.runnerName} (${x.runnerId})`);let C=await Gm(t,x,r);g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C.ok?r.info(`[ghr] runners connected on ${x.runnerName}`):r.warn(`[ghr] setup failed: ${C.error??"see per-repo statuses"}`);return}if(N==="gh_runner_teardown"){let x=T;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${x.runnerName} (${x.runnerId})`);let C=await Km(t,x,r);g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C.ok?r.info(`[ghr] runners disconnected from ${x.runnerName}`):r.warn(`[ghr] teardown failed: ${C.error??"unknown error"}`);return}if(N==="tracker_fields_request"){let x=T,C={type:"tracker_fields_result",requestId:x.requestId,projectId:t.projectId,ok:!1},L=lt({contextDir:o?.contextDir??null});if(!L.ok)C.error=L.error;else try{C.fields=await L.provider.fetchStateFields(x.projectKey),C.ok=!0}catch(q){C.error=q instanceof Error?q.message:String(q)}g.readyState===g.OPEN&&g.send(JSON.stringify(C)),C.ok||r.warn(`[yt-fields] listing failed: ${C.error??"unknown"}`);return}if(N==="project_secret_update"||N==="project_secret_delete"){let x=T,C;if(x.type==="project_secret_update"){let q=G(t.projectId);C=q?.sealKey?Ym(t.projectId,x.name,x.sealed,q.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else C=qm(t.projectId,x.name);let L={type:"project_secret_update_result",updateId:x.updateId,projectId:t.projectId,ok:C.ok,...C.detail?{detail:C.detail}:{}};g.readyState===g.OPEN&&g.send(JSON.stringify(L)),C.ok?(r.info(`[secret] ${x.name} ${x.type==="project_secret_update"?"saved":"deleted"}`+(C.detail?` \u2014 ${C.detail}`:"")),S()):r.warn(`[secret] ${x.name} rejected: ${C.detail??"unknown"}`);return}if(N==="auto_apply_local"){let x=T;if(!o?.contextDir){r.warn(`[apply] auto_apply_local for ${x.claim.taskKey} \u2014 no workspace (headless), skipped; task stays in READY_TO_APPLY`);return}let C=await xd({hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId,root:o.root,contextDir:o.contextDir,repos:o.repos},x.claim,r).catch(L=>({ok:!1,message:L instanceof Error?L.message:String(L)}));C.ok?r.info(`[apply] ${x.claim.taskKey}: ${C.message}`):r.warn(`[apply] ${x.claim.taskKey}: ${C.message} \u2014 task stays in READY_TO_APPLY`),n({kind:"local_applied",taskKey:x.claim.taskKey,ok:C.ok,...C.ok?{branches:C.branches??[]}:{error:C.message}});return}if(N==="sandbox_keys"){let x=G(t.projectId);if(!x){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let C=Rr(t.projectId),L=up(T,x,C,r);for(let q of L)g.readyState===g.OPEN&&g.send(JSON.stringify(q));return}if(N!=="dispatch_action")return;let j=T;if(y===!1){let x=`refused: HUB protocol incompatible with CLI v${Ne} (protocol ${et})`;g.send(JSON.stringify({type:"action_result",actionId:j.actionId,status:"failed",error:x})),r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 REFUSED: ${x}`),r.warn(`[exec] update the CLI to clear this: ${Ta}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:!1,error:x});return}if(j.action.type==="local_apply"){p.add(j.actionId);try{let x;if(!o)x={status:"failed",error:"no local workspace on this CLI"};else{let L=await Cm(o,j.action.repos,r);if(x=L.ok?{status:"done",result:{repos:L.repos}}:{status:"failed",error:L.error},L.ok&&o.contextDir){let q=j.action.taskId.split(":")[1]??"";for(let Te of q?L.repos:[]){let fr=o.repos.find(dt=>dt.name===Te.repoName);if(!fr)continue;let{recordPipelineEvent:gr}=await Promise.resolve().then(()=>(ha(),ym));await gr({contextDir:o.contextDir,repoDir:Fr(o.root,fr.mountAs),repoName:Te.repoName,taskKey:q,commitSha:Te.commit}).catch(dt=>r.warn(`[model] task event for ${q} failed: ${dt instanceof Error?dt.message:String(dt)}`))}}}g.send(JSON.stringify({type:"action_result",actionId:j.actionId,...x}));let C=x.status!=="failed";C?r.info(`[exec] ${j.actionId} (local_apply) \u2192 done`):r.warn(`[exec] ${j.actionId} (local_apply) \u2192 FAILED: ${x.status==="failed"?x.error:"?"}`),n({kind:"action",actionId:j.actionId,actionType:"local_apply",ok:C,...x.status==="failed"?{error:x.error}:{}})}finally{p.delete(j.actionId)}return}p.add(j.actionId);try{let x=await Sm({action:j.action,repo:j.repo,trackerIssueId:j.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:P?()=>P.reportNow():void 0,refreshContextStatus:o?.contextDir?w:void 0,onRunActivity:K}).catch(q=>({status:"failed",error:q instanceof Error?q.message:String(q)}));j.action.type==="tracker_comment"&&x.status==="done"&&"result"in x&&typeof x.result?.commentId=="string"&&d.add(x.result.commentId),g.send(JSON.stringify({type:"action_result",actionId:j.actionId,...x}));let C=x.status!=="failed",L=!C&&"error"in x?x.error:void 0;C?r.info(`[exec] ${j.actionId} (${j.action.type}) \u2192 done`):r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 FAILED: ${L??"?"}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:C,...L?{error:L}:{}})}finally{p.delete(j.actionId)}}),g.on("close",(E,R)=>{let T=R?.toString("utf-8")??"";if(r.info(`[ws] closed code=${E}${T?` reason=${T}`:""}`),k.stop(),h.stop(),P?.stop(),I(),T==="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:E}),!c&&setTimeout(()=>{m=f()},2e3)}),g.on("error",E=>r.warn(`[ws] error: ${E.message}`)),g}return{stop(){c=!0,m.close()}}}async function Ra(t,e,r){try{let n=await Q(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Ln(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 B$(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?Fr(e.root,o):$e(t.projectId,r.name);if(ef(Fr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await U$().clone(An(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 F$(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Fr(e.root,o):$e(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!ef(Fr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{M$(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 G$(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=Fr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Td(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 K$(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 ke(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 H$(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 Fd(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 Zm(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}var Ta,Ca=$(()=>{"use strict";Re();W();su();Yu();zu();No();js();Rd();jd();Gd();Je();yt();Hs();op();zs();Ar();dp();yp();Tm();Em();Nm();Hm();we();Vm();Pr();oe();zm();Qm();pi();Ta="npm i -g @code-partner/codepipe@latest"});import{execFileSync as W$}from"node:child_process";import{mkdtempSync as Y$,mkdirSync as q$,readFileSync as tf,rmSync as V$,writeFileSync as z$}from"node:fs";import{tmpdir as J$}from"node:os";import{dirname as X$,join as rf}from"node:path";function nf(t="codepipe-context"){let e=Y$(rf(J$(),"codepipe-ssh-")),r=rf(e,"id_ed25519");try{return W$("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:tf(r,"utf-8"),publicKey:tf(`${r}.pub`,"utf-8").trim()}}finally{V$(e,{recursive:!0,force:!0})}}async function of(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 sf(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 af(t,e){q$(X$(t),{recursive:!0});let r=e.endsWith(`
623
629
  `)?e:e+`
624
- `;return o$(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var ta=k(()=>{"use strict"});import{existsSync as om,mkdirSync as im}from"node:fs";import{dirname as sm}from"node:path";import{simpleGit as jr}from"simple-git";function a$(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 c$(t,e){return e?.contextWrite?.token?{user:ao(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:Yt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function am(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 ti))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 ri(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await Q(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new ti(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=c$(hr(s.cloneUrl),r);if(a){let c=await l$({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 u$({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 l$(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=a$(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(om(`${r}/.git`)){let l=jr(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Rs(r);await l.reset(["--hard",`origin/${s}`]),Ts(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else im(sm(r),{recursive:!0}),await jr().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await cm(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 u$(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=nm(i,n),a=rm(e.cloneUrl),c=e.branch;try{if(om(`${r}/.git`)){let l=jr(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=Rs(r);await l.reset(["--hard",`origin/${c}`]),Ts(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else im(sm(r),{recursive:!0}),await jr().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await jr(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await cm(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 cm(t){let e=jr(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 ti,ra=k(()=>{"use strict";W();we();ft();ta();ti=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as d$}from"node:child_process";function p$(){try{return d$("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function um(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:p$(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var dm=k(()=>{"use strict"});import{homedir as _r}from"node:os";import{mkdirSync as m$,readFileSync as pm,writeFileSync as f$,existsSync as oa}from"node:fs";import{dirname as g$,join as Nt}from"node:path";function h$(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Ye(t){let e=H("SANDBOX_CONFIG");if(e)return e;let r=Nt(_r(),".codepipe","worker");return t?Nt(r,"profiles",t,"config.json"):Nt(r,"config.json")}function mm(){return Nt(_r(),".devpipe-sandbox","config.json")}function ni(){Vt(Nt(_r(),".devpipe"),Nt(_r(),".codepipe")),H("SANDBOX_CONFIG")||Vt(Nt(_r(),".devpipe-sandbox"),Nt(_r(),".codepipe-sandbox"))}function fm(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function ke(t){let e=Ye(t),r=null;return oa(e)?r=JSON.parse(pm(e,"utf-8")):!t&&!H("SANDBOX_CONFIG")&&oa(mm())&&(r=JSON.parse(pm(mm(),"utf-8"))),r?(r.planningLane=h$(),r):null}function gm(t,e){let r=Ye(e);m$(g$(r),{recursive:!0}),f$(r,JSON.stringify(t,null,2)+`
625
- `,{mode:384})}var oi=k(()=>{"use strict";xe();co();oa(".env")&&process.loadEnvFile(".env")});import y$ from"ws";var Nr,ia=k(()=>{"use strict";Nr=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 y$(e)}}});import{hostname as w$}from"node:os";async function sr(t){ni();let e=ke(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Ye(t.profile)}.`),process.exit(1));let r=t.name??w$(),n=um({projects:t.projects??[],llm:t.llm??null}),o=new Nr(t.hub.replace(/\/$/,"")),i=Fo(),s=Re(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});gm({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 ${Ye(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 hm=k(()=>{"use strict";Le();dm();oi();ia()});import{spawn as b$}from"node:child_process";function sa(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function $$(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 v$(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function ar(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function aa(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
626
- `}async function km(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new ht;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:sa(f,ym)})}else if(m==="tool_use"){let f=String(d.name??""),g=d.input?.file_path??d.input?.path,y=$$(g,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:f,...y?{file:y}:{}})}}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?sa(v$(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=b$(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"),wm)};e.signal?.addEventListener("abort",f,{once:!0});let g=null,y=()=>{g&&clearTimeout(g),g=setTimeout(()=>{d=!0,console.warn(`[claude:chat] idle for ${bm}ms \u2014 ending session`),u.kill("SIGTERM"),m=setTimeout(()=>u.kill("SIGKILL"),wm)},bm)},b=()=>{m&&clearTimeout(m),g&&clearTimeout(g),e.signal?.removeEventListener("abort",f)},h=!0,$=E=>{if(!(!h||u.stdin.destroyed))try{u.stdin.write(E)}catch{}};$(aa(e.prompt)),y(),(async()=>{try{for await(let E of e.interactive.inbox){if(p||!h)break;if(y(),E.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:sa(E.text,ym)}),$(aa(E.text));else{$(aa(k$)),h=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let S="",D=E=>{let v;try{v=JSON.parse(E)}catch{return}a(v)};u.stdout.on("data",E=>{i.push(E),y(),S+=E;let v;for(;(v=S.indexOf(`
627
- `))!==-1;){let A=S.slice(0,v).trim();S=S.slice(v+1),A&&D(A)}}),u.stderr.on("data",E=>{i.push(E);for(let v of E.split(`
628
- `)){let A=v.trim();A&&console.warn(`[claude:chat:stderr] ${A}`)}}),u.on("error",E=>{b(),l(E)}),u.on("close",E=>{if(b(),p){l(new ht);return}if(d){l(new Error("chat session ended: idle for too long without a reply"));return}S.trim()&&D(S.trim()),console.log(`[claude:chat] exit code=${E}`),c({artifactPaths:[],log:i.join(""),usage:x$(s)})})})}function x$(t){let e=Ht();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=ar(r.input_tokens),e.outputTokens=ar(r.output_tokens),e.cacheReadInputTokens=ar(r.cache_read_input_tokens),e.cacheCreationInputTokens=ar(r.cache_creation_input_tokens)),e.totalCostUsd=ar(t.total_cost_usd),e.numTurns=ar(t.num_turns),e.durationMs=ar(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var ym,wm,bm,k$,$m=k(()=>{"use strict";W();Or();ym=16e3,wm=5e3,bm=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),k$="\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 S$}from"node:child_process";import{existsSync as R$}from"node:fs";function C$(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function vm(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: ${Ot(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=P$(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=Sm(o.content);console.log(`[claude] tool_result (error)${i?`: ${Ot(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)} ${Ot(JSON.stringify(e),200)}`),e}function I$(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(Ot(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(Ot(r.trim().split(`
630
+ `;return z$(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var Ea=$(()=>{"use strict"});import{existsSync as cf,mkdirSync as lf}from"node:fs";import{dirname as uf}from"node:path";import{simpleGit as Gr}from"simple-git";function Q$(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 Z$(t,e){return e?.contextWrite?.token?{user:ko(t),secret:e.contextWrite.token}:t===Sn.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Sn.bitbucket?e?.bitbucket?.apiToken?{user:Vt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function df(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 bi(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await Q(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=Z$(Sr(s.cloneUrl),r);if(a){let c=await ev({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 tv({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 ev(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Q$(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(cf(`${r}/.git`)){let l=Gr(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Ls(r);await l.reset(["--hard",`origin/${s}`]),Ms(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else lf(uf(r),{recursive:!0}),await Gr().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await pf(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 tv(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=af(i,n),a=sf(e.cloneUrl),c=e.branch;try{if(cf(`${r}/.git`)){let l=Gr(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=Ls(r);await l.reset(["--hard",`origin/${c}`]),Ms(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else lf(uf(r),{recursive:!0}),await Gr().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Gr(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await pf(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 pf(t){let e=Gr(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,Ia=$(()=>{"use strict";W();we();yt();Ea();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 rv}from"node:child_process";function nv(){try{return rv("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function ff(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:nv(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var gf=$(()=>{"use strict"});import{homedir as Kr}from"node:os";import{mkdirSync as ov,readFileSync as hf,writeFileSync as iv,existsSync as Aa}from"node:fs";import{dirname as sv,join as Ot}from"node:path";function av(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Xe(t){let e=H("SANDBOX_CONFIG");if(e)return e;let r=Ot(Kr(),".codepipe","worker");return t?Ot(r,"profiles",t,"config.json"):Ot(r,"config.json")}function yf(){return Ot(Kr(),".devpipe-sandbox","config.json")}function $i(){zt(Ot(Kr(),".devpipe"),Ot(Kr(),".codepipe")),H("SANDBOX_CONFIG")||zt(Ot(Kr(),".devpipe-sandbox"),Ot(Kr(),".codepipe-sandbox"))}function wf(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function ve(t){let e=Xe(t),r=null;return Aa(e)?r=JSON.parse(hf(e,"utf-8")):!t&&!H("SANDBOX_CONFIG")&&Aa(yf())&&(r=JSON.parse(hf(yf(),"utf-8"))),r?(r.planningLane=av(),r):null}function kf(t,e){let r=Xe(e);ov(sv(r),{recursive:!0}),iv(r,JSON.stringify(t,null,2)+`
631
+ `,{mode:384})}var vi=$(()=>{"use strict";Re();bo();Aa(".env")&&process.loadEnvFile(".env")});import cv from"ws";var Hr,ja=$(()=>{"use strict";Hr=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new cv(e)}}});import{hostname as lv}from"node:os";async function lr(t){$i();let e=ve(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Xe(t.profile)}.`),process.exit(1));let r=t.name??lv(),n=ff({projects:t.projects??[],llm:t.llm??null}),o=new Hr(t.hub.replace(/\/$/,"")),i=Qo(),s=Ce(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});kf({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 ${Xe(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 bf=$(()=>{"use strict";Ue();gf();vi();ja()});import{spawn as uv}from"node:child_process";function _a(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function pv(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 mv(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function ur(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Na(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
632
+ `}async function Sf(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new kt;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:_a(f,$f)})}else if(m==="tool_use"){let f=String(d.name??""),g=d.input?.file_path??d.input?.path,y=pv(g,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:f,...y?{file:y}:{}})}}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?_a(mv(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=uv(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"),vf)};e.signal?.addEventListener("abort",f,{once:!0});let g=null,y=()=>{g&&clearTimeout(g),g=setTimeout(()=>{d=!0,console.warn(`[claude:chat] idle for ${xf}ms \u2014 ending session`),u.kill("SIGTERM"),m=setTimeout(()=>u.kill("SIGKILL"),vf)},xf)},k=()=>{m&&clearTimeout(m),g&&clearTimeout(g),e.signal?.removeEventListener("abort",f)},h=!0,b=I=>{if(!(!h||u.stdin.destroyed))try{u.stdin.write(I)}catch{}};b(Na(e.prompt)),y(),(async()=>{try{for await(let I of e.interactive.inbox){if(p||!h)break;if(y(),I.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:_a(I.text,$f)}),b(Na(I.text));else{b(Na(dv)),h=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let S="",D=I=>{let v;try{v=JSON.parse(I)}catch{return}a(v)};u.stdout.on("data",I=>{i.push(I),y(),S+=I;let v;for(;(v=S.indexOf(`
633
+ `))!==-1;){let A=S.slice(0,v).trim();S=S.slice(v+1),A&&D(A)}}),u.stderr.on("data",I=>{i.push(I);for(let v of I.split(`
634
+ `)){let A=v.trim();A&&console.warn(`[claude:chat:stderr] ${A}`)}}),u.on("error",I=>{k(),l(I)}),u.on("close",I=>{if(k(),p){l(new kt);return}if(d){l(new Error("chat session ended: idle for too long without a reply"));return}S.trim()&&D(S.trim()),console.log(`[claude:chat] exit code=${I}`),c({artifactPaths:[],log:i.join(""),usage:fv(s)})})})}function fv(t){let e=Wt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=ur(r.input_tokens),e.outputTokens=ur(r.output_tokens),e.cacheReadInputTokens=ur(r.cache_read_input_tokens),e.cacheCreationInputTokens=ur(r.cache_creation_input_tokens)),e.totalCostUsd=ur(t.total_cost_usd),e.numTurns=ur(t.num_turns),e.durationMs=ur(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var $f,vf,xf,dv,Tf=$(()=>{"use strict";W();Wr();$f=16e3,vf=5e3,xf=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),dv="\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 gv}from"node:child_process";import{existsSync as hv}from"node:fs";function wv(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Rf(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: ${Dt(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=$v(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=Ef(o.content);console.log(`[claude] tool_result (error)${i?`: ${Dt(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)} ${Dt(JSON.stringify(e),200)}`),e}function kv(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(Dt(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(Dt(r.trim().split(`
629
635
  `).slice(-5).join(`
630
- `),500)),n.join(" \u2014 ")}function E$(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 Sm(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function P$(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=${Ot(r,80)}`}return""}function Ot(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Te(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function A$(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Te(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Te(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 j$(t,e,r,n){let o=Ht(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=Te(i.input_tokens),o.outputTokens=Te(i.output_tokens),o.cacheReadInputTokens=Te(i.cache_read_input_tokens),o.cacheCreationInputTokens=Te(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Te(t?.total_cost_usd),o.numTurns=t&&Te(t.num_turns)>0?Te(t.num_turns):r,o.durationMs=Te(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function _$(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:Ot(c,xm)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=N$(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?Ot(Sm(s.content),xm):"";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 N$(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 Dr,ht,T$,Dn,xm,Or=k(()=>{"use strict";W();$m();Dr=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},ht=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},T$=5e3;Dn=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return km(this.binary,e);if(e.signal?.aborted)throw new ht;let r=["-p",C$(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 g=A$(f.rate_limit_info);g&&(!l||g.utilization>l.utilization)&&(l=g);return}if(f.type==="assistant"){let g=f.message;typeof g?.model=="string"&&(c=g.model);let y=g?.usage;y&&(a+=1,s.input+=Te(y.input_tokens),s.output+=Te(y.output_tokens),s.cacheRead+=Te(y.cache_read_input_tokens),s.cacheCreate+=Te(y.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of _$(f,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((f,g)=>{let y=S$(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 b=!1,h=null,$=()=>{b=!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")},T$)};e.signal?.addEventListener("abort",$,{once:!0});let S=()=>{h&&clearTimeout(h),e.signal?.removeEventListener("abort",$)},D="";y.stdout.on("data",E=>{n.push(E),D+=E;let v;for(;(v=D.indexOf(`
631
- `))!==-1;){let A=D.slice(0,v).trim();if(D=D.slice(v+1),A){let M=vm(A);u(M),M&&m(M)}}}),y.stderr.on("data",E=>{n.push(E),o.push(E);for(let v of E.split(`
632
- `)){let A=v.trim();A&&console.warn(`[claude:stderr] ${A}`)}}),y.on("error",E=>{S(),g(E)}),y.on("close",E=>{if(S(),b){g(new ht);return}if(D.trim()){let A=vm(D.trim());u(A),A&&m(A)}let v=i?.is_error===!0;if(E!==0||v){let A=typeof i?.api_error_status=="number"?i.api_error_status:void 0,M=typeof i?.subtype=="string"?i.subtype:void 0,K=typeof i?.result=="string"?i.result:void 0;g(new Dr(I$(E,i,o.join("")),{code:E,apiErrorStatus:A,subtype:M,resultText:K,retryAfterMs:E$(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:j$(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("/")&&R$(n))}};xm=200});import{mkdirSync as O$,writeFileSync as Lr}from"node:fs";import{dirname as D$,join as Mr}from"node:path";function Rm(t,e,r){let n=Mr(t,e);O$(D$(n),{recursive:!0}),Lr(n,r)}function L$(t,e,r){return`# ${t} \u2014 Estimate
636
+ `),500)),n.join(" \u2014 ")}function bv(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 Ef(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function $v(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=${Dt(r,80)}`}return""}function Dt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Ee(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function vv(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Ee(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Ee(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 xv(t,e,r,n){let o=Wt(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=Ee(i.input_tokens),o.outputTokens=Ee(i.output_tokens),o.cacheReadInputTokens=Ee(i.cache_read_input_tokens),o.cacheCreationInputTokens=Ee(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Ee(t?.total_cost_usd),o.numTurns=t&&Ee(t.num_turns)>0?Ee(t.num_turns):r,o.durationMs=Ee(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function Sv(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:Dt(c,Cf)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=Tv(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?Dt(Ef(s.content),Cf):"";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 Tv(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 Yr,kt,yv,Yn,Cf,Wr=$(()=>{"use strict";W();Tf();Yr=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},kt=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},yv=5e3;Yn=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Sf(this.binary,e);if(e.signal?.aborted)throw new kt;let r=["-p",wv(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 g=vv(f.rate_limit_info);g&&(!l||g.utilization>l.utilization)&&(l=g);return}if(f.type==="assistant"){let g=f.message;typeof g?.model=="string"&&(c=g.model);let y=g?.usage;y&&(a+=1,s.input+=Ee(y.input_tokens),s.output+=Ee(y.output_tokens),s.cacheRead+=Ee(y.cache_read_input_tokens),s.cacheCreate+=Ee(y.cache_creation_input_tokens))}}},p=e.role,d=e.onActivity,m=f=>{if(d)for(let g of Sv(f,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((f,g)=>{let y=gv(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{},CLAUDE_CODE_DISABLE_BACKGROUND_TASKS:"1",BASH_DEFAULT_TIMEOUT_MS:"600000",BASH_MAX_TIMEOUT_MS:"1800000"}});y.stdout.setEncoding("utf-8"),y.stderr.setEncoding("utf-8");let k=!1,h=null,b=()=>{k=!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")},yv)};e.signal?.addEventListener("abort",b,{once:!0});let S=()=>{h&&clearTimeout(h),e.signal?.removeEventListener("abort",b)},D="";y.stdout.on("data",I=>{n.push(I),D+=I;let v;for(;(v=D.indexOf(`
637
+ `))!==-1;){let A=D.slice(0,v).trim();if(D=D.slice(v+1),A){let M=Rf(A);u(M),M&&m(M)}}}),y.stderr.on("data",I=>{n.push(I),o.push(I);for(let v of I.split(`
638
+ `)){let A=v.trim();A&&console.warn(`[claude:stderr] ${A}`)}}),y.on("error",I=>{S(),g(I)}),y.on("close",I=>{if(S(),k){g(new kt);return}if(D.trim()){let A=Rf(D.trim());u(A),A&&m(A)}let v=i?.is_error===!0;if(I!==0||v){let A=typeof i?.api_error_status=="number"?i.api_error_status:void 0,M=typeof i?.subtype=="string"?i.subtype:void 0,K=typeof i?.result=="string"?i.result:void 0;g(new Yr(kv(I,i,o.join("")),{code:I,apiErrorStatus:A,subtype:M,resultText:K,retryAfterMs:bv(i)}));return}console.log("[claude] exit code=0"),f({artifactPaths:[],log:n.join(""),usage:xv(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("/")&&hv(n))}};Cf=200});import{mkdirSync as Rv,writeFileSync as qr}from"node:fs";import{dirname as Cv,join as Vr}from"node:path";function If(t,e,r){let n=Vr(t,e);Rv(Cv(n),{recursive:!0}),qr(n,r)}function Ev(t,e,r){return`# ${t} \u2014 Estimate
633
639
 
634
640
  **Title:** ${e}
635
641
 
@@ -650,7 +656,7 @@ production-grade estimates.)
650
656
  ${r.split(`
651
657
  `).slice(0,8).join(`
652
658
  `).trim()||"(empty)"}
653
- `}function M$(t,e,r,n){let o=n?`
659
+ `}function Iv(t,e,r,n){let o=n?`
654
660
  ## Reviewer rework instruction
655
661
 
656
662
  > ${n.split(`
@@ -679,10 +685,10 @@ TBD (mock runner does not yet inspect project code).
679
685
  ${r.split(`
680
686
  `).slice(0,8).join(`
681
687
  `).trim()||"(empty)"}
682
- `}function U$(t){return`# ${t} \u2014 Open questions
688
+ `}function Pv(t){return`# ${t} \u2014 Open questions
683
689
 
684
690
  (none \u2014 mock runner did not surface ambiguities.)
685
- `}function B$(t,e,r){let n=r?` (rework: ${r.split(`
691
+ `}function Av(t,e,r){let n=r?` (rework: ${r.split(`
686
692
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
687
693
  index 0000000..1111111 100644
688
694
  --- a/CHANGELOG.md
@@ -693,7 +699,7 @@ index 0000000..1111111 100644
693
699
  +- mock-runner placeholder change for slice 5 testing.
694
700
  +
695
701
  # Changelog
696
- `}function F$(t,e,r){return`# ${t} \u2014 Diff summary
702
+ `}function jv(t,e,r){return`# ${t} \u2014 Diff summary
697
703
 
698
704
  **Title:** ${e}
699
705
  ${r?`
@@ -704,120 +710,116 @@ ${r?`
704
710
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
705
711
 
706
712
  (Mock-runner output. Replace with claude-headless for production patches.)
707
- `}var Ln,ca=k(()=>{"use strict";W();Or();Ln=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=L$(n,o,i);Lr(Mr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Lr(Mr(e.workspaceDir,"SOLUTION.md"),M$(n,o,i,a)),s.push("SOLUTION.md"),Lr(Mr(e.workspaceDir,"QUESTIONS.md"),U$(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Rm(e.workspaceDir,"changes/sample.patch",B$(n,o,a)),s.push("changes/sample.patch"),Rm(e.workspaceDir,"diff-summary.md",F$(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Lr(Mr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
708
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:Ht()}}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 ht;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 Lr(Mr(e.workspaceDir,"DRAFT.md"),`${o}
713
+ `}var qn,Oa=$(()=>{"use strict";W();Wr();qn=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=Ev(n,o,i);qr(Vr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;qr(Vr(e.workspaceDir,"SOLUTION.md"),Iv(n,o,i,a)),s.push("SOLUTION.md"),qr(Vr(e.workspaceDir,"QUESTIONS.md"),Pv(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;If(e.workspaceDir,"changes/sample.patch",Av(n,o,a)),s.push("changes/sample.patch"),If(e.workspaceDir,"diff-summary.md",jv(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(qr(Vr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
714
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:Wt()}}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 kt;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 qr(Vr(e.workspaceDir,"DRAFT.md"),`${o}
709
715
 
710
716
  \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).
711
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Ht()}}}});function Tm(t){switch(t){case"mock":return new Ln;case"claude-headless":return new Dn;default:return null}}function Cm(t,e){let r=e&&e.trim().length>0?e.trim():Ze;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var Im=k(()=>{"use strict";W();Or();ca();Or();ca()});function Am(t=process.env){return{maxAttempts:ii(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:ii(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:ii(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:ii(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function W$(t){if(t instanceof Dr){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return K$.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&H$.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:G$.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Em.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 Em.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function jm(t){if(t instanceof Dr){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Pm.test(n)}let e=t instanceof Error?t.message:String(t);return Pm.test(e)}function q$(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 _m(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=W$(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=q$(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 ii(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var G$,Em,K$,H$,Pm,Nm=k(()=>{"use strict";Or();G$=new Set([429,500,502,503,529]),Em=/(\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,K$=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,H$=new Set(["error_max_turns"]);Pm=/(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 Y$,rmSync as V$,writeFileSync as Om}from"node:fs";import{tmpdir as z$}from"node:os";import{join as la}from"node:path";function si(t){return`[url "https://${t}/"]
717
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:Wt()}}}});function Pf(t){switch(t){case"mock":return new qn;case"claude-headless":return new Yn;default:return null}}function Af(t,e){let r=e&&e.trim().length>0?e.trim():nt;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var jf=$(()=>{"use strict";W();Wr();Oa();Wr();Oa()});function Of(t=process.env){return{maxAttempts:xi(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:xi(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:xi(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:xi(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function Dv(t){if(t instanceof Yr){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return Nv.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&Ov.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:_v.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:_f.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 _f.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Df(t){if(t instanceof Yr){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Nf.test(n)}let e=t instanceof Error?t.message:String(t);return Nf.test(e)}function Lv(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 Lf(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=Dv(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=Lv(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 xi(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}var _v,_f,Nv,Ov,Nf,Mf=$(()=>{"use strict";Wr();_v=new Set([429,500,502,503,529]),_f=/(\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,Nv=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,Ov=new Set(["error_max_turns"]);Nf=/(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 Mv,rmSync as Uv,writeFileSync as Uf}from"node:fs";import{tmpdir as Bv}from"node:os";import{join as Da}from"node:path";function Si(t){return`[url "https://${t}/"]
712
718
  insteadOf = git@${t}:
713
719
  insteadOf = ssh://git@${t}/
714
- `}function Dm(t,e){if(t.length===0)return null;let r=Y$(la(z$(),"devpipe-gitcreds-")),n=la(r,"credentials"),o=la(r,"gitconfig");return Om(n,t.join(`
720
+ `}function Bf(t,e){if(t.length===0)return null;let r=Mv(Da(Bv(),"devpipe-gitcreds-")),n=Da(r,"credentials"),o=Da(r,"gitconfig");return Uf(n,t.join(`
715
721
  `)+`
716
- `,{mode:384}),Om(o,`[credential]
722
+ `,{mode:384}),Uf(o,`[credential]
717
723
  helper = store --file=${n}
718
- `+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{V$(r,{recursive:!0,force:!0})}catch{}}}}function ua(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(J$)),t.bitbucket?.apiToken&&(e.push(`https://${Yt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(X$)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Q$)),Dm(e,r)}function Lm(t,e){if(t.contextWrite?.token){let r=hr(e)??"github.com",n=ao(r);return Dm([`https://${n}:${t.contextWrite.token}@${r}`],[si(r)])}return ua(t)}var J$,X$,Q$,Mm=k(()=>{"use strict";W();J$=si("github.com"),X$=si("bitbucket.org"),Q$=si("gitlab.com")});import{spawn as Bm}from"node:child_process";import{existsSync as ai,mkdirSync as Mn,readFileSync as Z$,rmSync as da,symlinkSync as ev}from"node:fs";import{homedir as tv}from"node:os";import{dirname as Br,join as Dt}from"node:path";function Fm(t){let e=Dt(tv(),".codepipe-sandbox","repos");return t?Dt(e,t):e}function Gm(t,e){let n=(Ur.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Ur.get(t)===o&&Ur.delete(t)},()=>{Ur.get(t)===o&&Ur.delete(t)});return Ur.set(t,o),n}function Um(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 rv(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 Km(t,e,r,n,o){let i=async c=>{await ee(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ee(t,["reset","--hard",`origin/${c}`],o),await ee(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!Um(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{ai(t)&&da(t,{recursive:!0,force:!0}),Mn(Br(t),{recursive:!0});try{return await ee(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Um(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),ai(t)&&da(t,{recursive:!0,force:!0}),Mn(Br(t),{recursive:!0}),await ee(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(ai(Dt(t,".git")))try{return await s()}catch(c){if(!rv(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 Hm(t){await ee(t.workspacePath,["reset","--hard",t.baseSha]),await ee(t.workspacePath,["clean","-fdx"])}async function Wm(t,e){let r=t.workspacePath;await ee(r,["add","-A"]);let n=(await be(r,["write-tree"])).trim(),o=(await be(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Fr,GIT_AUTHOR_EMAIL:Gr,GIT_COMMITTER_NAME:Fr,GIT_COMMITTER_EMAIL:Gr};return(await be(r,["commit-tree",n,"-m",e],i)).trim()}async function qm(t,e,r,n,o){try{await ee(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw hr(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 Ym(t,e){return be(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Vm(t,e,r,n,o){await ee(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ee(t.workspacePath,["checkout","--force",r])}async function zm(t,e,r,n,o,i){let s=t.workspacePath;await ee(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await be(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=>be(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await be(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ee(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 ee(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:Fr,GIT_AUTHOR_EMAIL:Gr,GIT_COMMITTER_NAME:Fr,GIT_COMMITTER_EMAIL:Gr},u=(await be(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await be(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ee(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ee(s,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await be(s,["diff","--name-only","--diff-filter=U"])).split(`
719
- `).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await ee(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 pa(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Fr,GIT_AUTHOR_EMAIL:Gr,GIT_COMMITTER_NAME:Fr,GIT_COMMITTER_EMAIL:Gr};(await be(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ee(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 ee(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ee(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await be(n,["diff","--name-only","--diff-filter=U"])).split(`
720
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await be(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 ee(t,e,r){return new Promise((n,o)=>{let i=Bm("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}):
721
- ${s.join("").trim()||"(no stderr)"}`))})})}function be(t,e,r){return new Promise((n,o)=>{let i=Bm("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}):
722
- ${a.join("").trim()||"(no stderr)"}`))})})}function Jm(t,e){ai(t)&&da(t,{recursive:!0,force:!0}),Mn(Br(t),{recursive:!0}),ev(e,t,"dir")}async function Xm(t,e,r){await ee(t,["worktree","prune"]).catch(()=>{}),Mn(Br(r),{recursive:!0}),await ee(t,["worktree","add","--detach",r,`origin/${e}`])}async function nv(t,e,r){Mn(Br(r),{recursive:!0}),await ee(Br(r),["clone","--quiet","--no-checkout",t,r]),await ee(r,["checkout","--force","--detach",e])}async function Qm(t,e,r,n="worktree",o,i){return r.length===0?[]:Gm(e,async()=>{let s=[];for(let a of r){let c=Dt(Fm(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await Km(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 be(c,["rev-parse","HEAD"])).trim(),p=Dt(t,"code",a.name);n==="direct"?(Jm(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await nv(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await Xm(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 Zm(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return Gm(e,async()=>{let a=Dt(Fm(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await Km(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=Dt(t,"context");n==="direct"?(Jm(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Xm(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await be(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function ef(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ee(r,["add","-A",...n]).catch(()=>{});let o;try{o=await be(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
723
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Z$(Dt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var Ur,Fr,Gr,tf=k(()=>{"use strict";W();Ur=new Map;Fr="CodePipe Agent",Gr="codepipe@codepartner.ee"});import{readFileSync as ov}from"node:fs";import{join as iv}from"node:path";function rf(t){let e=iv(t,Un),r;try{r=ov(e,"utf-8")}catch{throw new Lt(`BUILD produced no ${Un} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Lt(`${Un} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Lt(`${Un} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Lt(`${Un}: "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"?sv(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 sv(t){let e=Buffer.from(t,"utf-8");return e.length<=ma?t:`\u2026 [${e.length-ma} bytes elided] \u2026
724
- `+e.subarray(e.length-ma).toString("utf-8")}var ma,Lt,Un,nf=k(()=>{"use strict";ma=8*1024,Lt=class extends Error{},Un="meta/build-result.json"});import{readFileSync as av}from"node:fs";import{join as cv}from"node:path";function sf(t){let e=cv(t,Kr),r;try{r=av(e,"utf-8")}catch{throw new yt(`code review produced no ${Kr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new yt(`${Kr} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new yt(`${Kr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new yt(`${Kr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?of(o.remarks,lv):"";if(!i&&s.trim().length===0)throw new yt(`${Kr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?of(o.summary,uv):"";return{approved:i,remarks:s,summary:a}}function of(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
725
- \u2026 [${r.length-e} bytes elided]`}var lv,uv,yt,Kr,af=k(()=>{"use strict";lv=16*1024,uv=4*1024,yt=class extends Error{},Kr="meta/review-result.json"});import{readFileSync as dv,statSync as pv}from"node:fs";import{join as cf}from"node:path";function bv(t){return t.startsWith("meta/")||wv.has(t)}function kv(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 $v(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function lf(t,e,r){let n=r?.maxBytes??mv,o=r?.totalBytes??fv,i=r?.maxCount??gv,s=e.map((f,g)=>{let y=null;try{y=pv(cf(t,f)).size}catch{}return{path:f,index:g,size:y}}),a=[...s].sort((f,g)=>{let y=b=>bv(b.path)?0:1;return y(f)!==y(g)?y(f)-y(g):(f.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((f,g)=>f.index-g.index).map(f=>f.path),u=new Array(s.length),p=[],d=0;for(let f of c){let g=null;if(f.size!==null&&f.size<=n&&d+f.size<=o)try{g=dv(cf(t,f.path))}catch{}if(g!==null){d+=g.length,u[f.index]={path:f.path,contentBase64:g.toString("base64")};continue}let y=f.size===null?$v(f.path):kv(f.path,f.size,n,o),b=Buffer.from(y,"utf-8");d+=b.length,u[f.index]={path:f.path,contentBase64:b.toString("base64")},p.push({path:f.path,bytes:f.size??0})}let m=u.filter(f=>f!==void 0);if(l.length>0){let f=l.slice(0,yv),g=`# Artifacts omitted from upload
724
+ `+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{Uv(r,{recursive:!0,force:!0})}catch{}}}}function La(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Fv)),t.bitbucket?.apiToken&&(e.push(`https://${Vt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Gv)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Kv)),Bf(e,r)}function Ff(t,e){if(t.contextWrite?.token){let r=Sr(e)??"github.com",n=ko(r);return Bf([`https://${n}:${t.contextWrite.token}@${r}`],[Si(r)])}return La(t)}var Fv,Gv,Kv,Gf=$(()=>{"use strict";W();Fv=Si("github.com"),Gv=Si("bitbucket.org"),Kv=Si("gitlab.com")});import{spawn as Hf}from"node:child_process";import{existsSync as Ti,mkdirSync as Vn,readFileSync as Hv,rmSync as Ma,symlinkSync as Wv}from"node:fs";import{homedir as Yv}from"node:os";import{dirname as Jr,join as Lt}from"node:path";function Wf(t){let e=Lt(Yv(),".codepipe-sandbox","repos");return t?Lt(e,t):e}function Yf(t,e){let n=(zr.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{zr.get(t)===o&&zr.delete(t)},()=>{zr.get(t)===o&&zr.delete(t)});return zr.set(t,o),n}function Kf(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 qv(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 qf(t,e,r,n,o){let i=async c=>{await ee(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await ee(t,["reset","--hard",`origin/${c}`],o),await ee(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!Kf(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Ti(t)&&Ma(t,{recursive:!0,force:!0}),Vn(Jr(t),{recursive:!0});try{return await ee(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Kf(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Ti(t)&&Ma(t,{recursive:!0,force:!0}),Vn(Jr(t),{recursive:!0}),await ee(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Ti(Lt(t,".git")))try{return await s()}catch(c){if(!qv(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 Vf(t){await ee(t.workspacePath,["reset","--hard",t.baseSha]),await ee(t.workspacePath,["clean","-fdx"])}async function zf(t,e){let r=t.workspacePath;await ee(r,["add","-A"]);let n=(await be(r,["write-tree"])).trim(),o=(await be(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Xr,GIT_AUTHOR_EMAIL:Qr,GIT_COMMITTER_NAME:Xr,GIT_COMMITTER_EMAIL:Qr};return(await be(r,["commit-tree",n,"-m",e],i)).trim()}async function Jf(t,e,r,n,o){try{await ee(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Sr(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 Xf(t,e){return be(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Qf(t,e,r,n,o){await ee(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await ee(t.workspacePath,["checkout","--force",r])}async function Zf(t,e,r,n,o,i){let s=t.workspacePath;await ee(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await be(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=>be(s,["rev-parse","-q","--verify",`${f}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await be(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ee(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 ee(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:Xr,GIT_AUTHOR_EMAIL:Qr,GIT_COMMITTER_NAME:Xr,GIT_COMMITTER_EMAIL:Qr},u=(await be(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await be(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await ee(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await ee(s,["cherry-pick","--no-commit",p],l)}catch(f){d=f instanceof Error?f.message:String(f)}let m=(await be(s,["diff","--name-only","--diff-filter=U"])).split(`
725
+ `).map(f=>f.trim()).filter(f=>f.length>0);if(d&&m.length===0)throw await ee(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 Ua(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Xr,GIT_AUTHOR_EMAIL:Qr,GIT_COMMITTER_NAME:Xr,GIT_COMMITTER_EMAIL:Qr};(await be(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await ee(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 ee(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await ee(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await be(n,["diff","--name-only","--diff-filter=U"])).split(`
726
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await be(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 ee(t,e,r){return new Promise((n,o)=>{let i=Hf("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}):
727
+ ${s.join("").trim()||"(no stderr)"}`))})})}function be(t,e,r){return new Promise((n,o)=>{let i=Hf("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}):
728
+ ${a.join("").trim()||"(no stderr)"}`))})})}function eg(t,e){Ti(t)&&Ma(t,{recursive:!0,force:!0}),Vn(Jr(t),{recursive:!0}),Wv(e,t,"dir")}async function tg(t,e,r){await ee(t,["worktree","prune"]).catch(()=>{}),Vn(Jr(r),{recursive:!0}),await ee(t,["worktree","add","--detach",r,`origin/${e}`])}async function Vv(t,e,r){Vn(Jr(r),{recursive:!0}),await ee(Jr(r),["clone","--quiet","--no-checkout",t,r]),await ee(r,["checkout","--force","--detach",e])}async function rg(t,e,r,n="worktree",o,i){return r.length===0?[]:Yf(e,async()=>{let s=[];for(let a of r){let c=Lt(Wf(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await qf(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 be(c,["rev-parse","HEAD"])).trim(),p=Lt(t,"code",a.name);n==="direct"?(eg(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await Vv(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await tg(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 ng(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return Yf(e,async()=>{let a=Lt(Wf(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await qf(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=Lt(t,"context");n==="direct"?(eg(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await tg(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await be(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function og(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await ee(r,["add","-A",...n]).catch(()=>{});let o;try{o=await be(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
729
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Hv(Lt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var zr,Xr,Qr,ig=$(()=>{"use strict";W();zr=new Map;Xr="CodePipe Agent",Qr="codepipe@codepartner.ee"});import{readFileSync as zv}from"node:fs";import{join as Jv}from"node:path";function sg(t){let e=Jv(t,zn),r;try{r=zv(e,"utf-8")}catch{throw new Mt(`BUILD produced no ${zn} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Mt(`${zn} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Mt(`${zn} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Mt(`${zn}: "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"?Xv(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 Xv(t){let e=Buffer.from(t,"utf-8");return e.length<=Ba?t:`\u2026 [${e.length-Ba} bytes elided] \u2026
730
+ `+e.subarray(e.length-Ba).toString("utf-8")}var Ba,Mt,zn,ag=$(()=>{"use strict";Ba=8*1024,Mt=class extends Error{},zn="meta/build-result.json"});import{readFileSync as Qv}from"node:fs";import{join as Zv}from"node:path";function lg(t){let e=Zv(t,Zr),r;try{r=Qv(e,"utf-8")}catch{throw new bt(`code review produced no ${Zr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(c){throw new bt(`${Zr} is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(!n||typeof n!="object")throw new bt(`${Zr} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new bt(`${Zr}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?cg(o.remarks,ex):"";if(!i&&s.trim().length===0)throw new bt(`${Zr}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?cg(o.summary,tx):"";return{approved:i,remarks:s,summary:a}}function cg(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
731
+ \u2026 [${r.length-e} bytes elided]`}var ex,tx,bt,Zr,ug=$(()=>{"use strict";ex=16*1024,tx=4*1024,bt=class extends Error{},Zr="meta/review-result.json"});import{readFileSync as rx,statSync as nx}from"node:fs";import{join as dg}from"node:path";function ux(t){return t.startsWith("meta/")||lx.has(t)}function dx(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 px(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function pg(t,e,r){let n=r?.maxBytes??ox,o=r?.totalBytes??ix,i=r?.maxCount??sx,s=e.map((f,g)=>{let y=null;try{y=nx(dg(t,f)).size}catch{}return{path:f,index:g,size:y}}),a=[...s].sort((f,g)=>{let y=k=>ux(k.path)?0:1;return y(f)!==y(g)?y(f)-y(g):(f.size??0)-(g.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((f,g)=>f.index-g.index).map(f=>f.path),u=new Array(s.length),p=[],d=0;for(let f of c){let g=null;if(f.size!==null&&f.size<=n&&d+f.size<=o)try{g=rx(dg(t,f.path))}catch{}if(g!==null){d+=g.length,u[f.index]={path:f.path,contentBase64:g.toString("base64")};continue}let y=f.size===null?px(f.path):dx(f.path,f.size,n,o),k=Buffer.from(y,"utf-8");d+=k.length,u[f.index]={path:f.path,contentBase64:k.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,cx),g=`# Artifacts omitted from upload
726
732
 
727
733
  ${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.
728
734
 
729
735
  `+f.map(y=>`- ${y}
730
736
  `).join("")+(l.length>f.length?`
731
737
  \u2026and ${l.length-f.length} more.
732
- `:"");m.push({path:hv,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var mv,fv,gv,hv,yv,wv,uf=k(()=>{"use strict";mv=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),fv=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),gv=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),hv="artifacts-omitted.md",yv=500,wv=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 vv,mkdtempSync as xv,readFileSync as Sv,readdirSync as pf,rmSync as df}from"node:fs";import{tmpdir as Rv}from"node:os";import{join as ci,relative as Tv}from"node:path";function mf(t){let e=xv(ci(Rv(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>df(e,{recursive:!0,force:!0}),listFiles:()=>ff(e,e),readFile:r=>Sv(ci(e,r),"utf-8"),clean:()=>{for(let r of pf(e))Iv.has(r)||df(ci(e,r),{recursive:!0,force:!0})}}}function ff(t,e){let r=[];for(let n of pf(e)){let o=ci(e,n),i=vv(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Cv.has(n))continue;r.push(...ff(t,o))}else r.push(Tv(t,o))}return r}var Cv,Iv,gf=k(()=>{"use strict";Cv=new Set(["code","context","scratch"]),Iv=new Set(["code","context"])});import{mkdirSync as Ev,readFileSync as hf,readdirSync as Pv,writeFileSync as Av}from"node:fs";import{homedir as jv}from"node:os";import{dirname as _v,join as Hr}from"node:path";function Ov(t){let e=Buffer.from(t,"utf-8");if(e.length<=li)return t;let r=Math.floor(li/4),n=li-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}
738
+ `:"");m.push({path:ax,contentBase64:Buffer.from(g,"utf-8").toString("base64")})}return{artifacts:m,omitted:p,dropped:l}}var ox,ix,sx,ax,cx,lx,mg=$(()=>{"use strict";ox=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),ix=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),sx=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),ax="artifacts-omitted.md",cx=500,lx=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 mx,mkdtempSync as fx,readFileSync as gx,readdirSync as gg,rmSync as fg}from"node:fs";import{tmpdir as hx}from"node:os";import{join as Ri,relative as yx}from"node:path";function hg(t){let e=fx(Ri(hx(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>fg(e,{recursive:!0,force:!0}),listFiles:()=>yg(e,e),readFile:r=>gx(Ri(e,r),"utf-8"),clean:()=>{for(let r of gg(e))kx.has(r)||fg(Ri(e,r),{recursive:!0,force:!0})}}}function yg(t,e){let r=[];for(let n of gg(e)){let o=Ri(e,n),i=mx(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&wx.has(n))continue;r.push(...yg(t,o))}else r.push(yx(t,o))}return r}var wx,kx,wg=$(()=>{"use strict";wx=new Set(["code","context","scratch"]),kx=new Set(["code","context"])});import{mkdirSync as bx,readFileSync as kg,readdirSync as $x,writeFileSync as vx}from"node:fs";import{homedir as xx}from"node:os";import{dirname as Sx,join as en}from"node:path";function Rx(t){let e=Buffer.from(t,"utf-8");if(e.length<=Ci)return t;let r=Math.floor(Ci/4),n=Ci-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}
733
739
 
734
- \u2026 [${s} bytes elided \u2014 log capped at ${li} bytes for upload] \u2026
740
+ \u2026 [${s} bytes elided \u2014 log capped at ${Ci} bytes for upload] \u2026
735
741
 
736
- ${i}`}function Dv(){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 Bn(t={}){ni();let e=ke(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=fm(t.profile,e.sandboxId,!!H("SANDBOX_CONFIG")),s=Hr(jv(),".codepipe","logs"),a=ho("SANDBOX_LOG",i,s);if(a.enabled){let P=new kr(a);yo(P),console.log(`[log] file logging \u2192 ${P.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${je} (protocol ${Xe})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Tm(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=Am();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new Nr(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,y=!1,b=()=>{let P=u.openControlSocket();return f=P,P.on("open",()=>{console.log("[ws] connected");let w={type:"sandbox_hello",platformVersion:je,protocolVersion:Xe};P.send(JSON.stringify(w))}),P.on("message",w=>{let I=w.toString("utf-8"),T=null;try{let R=JSON.parse(I);R&&typeof R=="object"&&(T=R)}catch{}if(T&&T.type==="hello"){let R=T;g=to(R.protocolVersion);let N=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${R.platformVersion} (protocol ${R.protocolVersion}) \u2014 ${N}`),g&&(y=!1);return}if(T&&T.type==="pause_job"){let R=typeof T.jobId=="string"?T.jobId:"",N=R?m.get(R):void 0;N?(console.warn(`[ws] pause_job ${R} \u2014 aborting agent`),N.paused=!0,N.abort.abort()):console.log(`[ws] pause_job ${R} \u2014 not a running job, ignoring`),R&&P.send(JSON.stringify({type:"job_paused",jobId:R}));return}if(T&&(T.type==="chat_user_message"||T.type==="chat_finalize")){let R=typeof T.jobId=="string"?T.jobId:"",N=R?m.get(R):void 0;if(N?.chatInbox)if(T.type==="chat_user_message"){let j=typeof T.text=="string"?T.text:"";j.trim()&&N.chatInbox.push({kind:"user",text:j})}else N.chatInbox.finalize();else console.log(`[ws] ${String(T.type)} ${R} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${I}`)}),P.on("close",(w,I)=>{console.log(`[ws] closed code=${w} reason=${I?.toString()||""}`),f===P&&(f=null),!p&&setTimeout(b,2e3)}),P.on("error",w=>console.warn(`[ws] error: ${w.message}`)),P},h=b(),$=async P=>{for(;!p;){if(g===!1){y||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${je}, protocol ${Xe}) \u2014 not claiming jobs until versions align.`),y=!0),await new Promise(w=>setTimeout(w,5e3));continue}try{let w=await u.claim(d.signal,P);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:${P}] ${w.status} \u2014 backoff 5s`),await new Promise(T=>setTimeout(T,5e3));continue}let I=await w.json();await S(u,I)}catch(w){if(d.signal.aborted)break;let I=w instanceof Error?w.message:String(w);console.warn(`[claim:${P}] error: ${I} \u2014 backoff 5s`),await new Promise(T=>setTimeout(T,5e3))}}};async function S(P,w){let I={abort:new AbortController,paused:!1};w.role==="chat"&&(I.chatInbox=Dv()),m.set(w.jobId,I);let T=!1,R=null,N=null,j=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),x=async()=>{try{await P.heartbeat(w.jobId)==="claim_lost"&&(T=!0,console.warn(`[job] ${w.jobId} claim lost \u2014 HUB sweeper took it`))}catch(Y){let Z=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${w.jobId} heartbeat error: ${Z}`)}};x();let C=setInterval(()=>{x()},j),L=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(E(w.prompt," \u2502 "));let z=[],ze=null,Si=400,Qn=25,Ri=500,O=()=>{if(ze&&(clearTimeout(ze),ze=null),z.length===0)return;let Y=z.splice(0,z.length),Z=f;if(!Z||Z.readyState!==Z.OPEN)return;let ct={type:"agent_activity",jobId:w.jobId,taskId:w.taskId,projectId:w.projectId,role:w.role,phase:w.phase,events:Y};try{Z.send(JSON.stringify(ct))}catch{}},ae=Y=>{z.push(Y),z.length>Ri&&z.shift(),z.length>=Qn?O():ze||(ze=setTimeout(O,Si))},Ae=w.role==="analysis"&&w.taskId.startsWith("draft::")?w.taskId.slice(7):null,Ue=new Set,kt=null;try{if(!c){T||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:L,finishedAt:new Date().toISOString()});return}if(!Cm(o,w.provider??null)){T||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${w.provider??"claude"}"`},startedAt:L,finishedAt:new Date().toISOString()});return}let Y=mf(w.jobId);console.log(`[job] ${w.jobId} workspace=${Y.dir}`);let Z=D(w,r);R=Z.gitCreds,N=Z.contextGitCreds;let ct=R?.env,Za=Z.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Z.claudeOauthToken}:void 0,lt=[],nn=null,Ti=null;try{let B=w.role==="build"?"clone":"worktree";lt=await Qm(Y.dir,w.projectId,w.projectRepos,B,ct,n);let F=await Zm(Y.dir,w.projectId,w.contextRepo,"worktree",ct,n);Ti=F,nn=F?.workspacePath??null}catch(B){let F=B instanceof Error?B.message:String(B);console.warn(`[job] ${w.jobId} materialize failed: ${F}`),T||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${F}`},startedAt:L,finishedAt:new Date().toISOString()}),Y.dispose();return}let ec=async()=>{if(!w.deliveries||w.deliveries.length===0)return[];let B=w.contextRepo?.cloneUrl;if(!B||!ct)throw new Error(B?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let F=[];for(let J of w.deliveries){let V=lt.find(de=>de.name===J.name);if(V){if(w.role==="implement"&&J.baseSha&&J.baseSha!==V.baseSha){let de=await zm(V,J.deliveryRef,J.deliverySha,J.baseSha,B,ct);console.log(`[job] ${w.jobId} ${V.name}: base moved ${J.baseSha.slice(0,10)} \u2192 ${V.baseSha.slice(0,10)} \u2014 re-applied delivery ${J.deliverySha.slice(0,10)} (${de.length} conflicted file(s))`),de.length>0&&F.push(`- **${V.name}**:`,...de.map(on=>` - \`${on}\``));continue}await Vm(V,J.deliveryRef,J.deliverySha,B,ct),console.log(`[job] ${w.jobId} ${V.name}: checked out delivery ${J.deliverySha.slice(0,10)} for ${w.role}`)}}return F},Ci=[];if(w.role==="build"||w.role==="implement"||w.role==="code-review")try{Ci=await ec()}catch(B){let F=B instanceof Error?B.message:String(B);console.warn(`[job] ${w.jobId} delivery checkout failed: ${F}`),T||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${F}`},startedAt:L,finishedAt:new Date().toISOString()}),Y.dispose();return}let Ii=w.role==="resolve-conflict"?w.metadata?.taskBranchByRepo??{}:{},tc="";if(w.role==="resolve-conflict"){if(!lt.some(B=>Ii[B.name])){let B="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} ${B}`),T||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:B},startedAt:L,finishedAt:new Date().toISOString()}),Y.dispose();return}try{let B=[];for(let F of lt){let J=Ii[F.name];if(!J)continue;let V=await pa(F,J,ct);console.log(`[job] ${w.jobId} ${F.name}: merged ${J} into ${F.ref} \u2014 ${V.length} conflicted file(s)`),V.length>0?B.push(`- **${F.name}**:`,...V.map(de=>` - \`${de}\``)):B.push(`- **${F.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}tc=`
742
+ ${i}`}function Cx(){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 Jn(t={}){$i();let e=ve(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=wf(t.profile,e.sandboxId,!!H("SANDBOX_CONFIG")),s=en(xx(),".codepipe","logs"),a=Co("SANDBOX_LOG",i,s);if(a.enabled){let P=new Er(a);Eo(P),console.log(`[log] file logging \u2192 ${P.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${Ne} (protocol ${et})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=Pf(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=Of();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new Hr(e.hubUrl,e.token),p=!1,d=new AbortController,m=new Map,f=null,g=null,y=!1,k=()=>{let P=u.openControlSocket();return f=P,P.on("open",()=>{console.log("[ws] connected");let w={type:"sandbox_hello",platformVersion:Ne,protocolVersion:et};P.send(JSON.stringify(w))}),P.on("message",w=>{let E=w.toString("utf-8"),R=null;try{let T=JSON.parse(E);T&&typeof T=="object"&&(R=T)}catch{}if(R&&R.type==="hello"){let T=R;g=lo(T.protocolVersion);let N=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${T.platformVersion} (protocol ${T.protocolVersion}) \u2014 ${N}`),g&&(y=!1);return}if(R&&R.type==="pause_job"){let T=typeof R.jobId=="string"?R.jobId:"",N=T?m.get(T):void 0;N?(console.warn(`[ws] pause_job ${T} \u2014 aborting agent`),N.paused=!0,N.abort.abort()):console.log(`[ws] pause_job ${T} \u2014 not a running job, ignoring`),T&&P.send(JSON.stringify({type:"job_paused",jobId:T}));return}if(R&&(R.type==="chat_user_message"||R.type==="chat_finalize")){let T=typeof R.jobId=="string"?R.jobId:"",N=T?m.get(T):void 0;if(N?.chatInbox)if(R.type==="chat_user_message"){let j=typeof R.text=="string"?R.text:"";j.trim()&&N.chatInbox.push({kind:"user",text:j})}else N.chatInbox.finalize();else console.log(`[ws] ${String(R.type)} ${T} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${E}`)}),P.on("close",(w,E)=>{console.log(`[ws] closed code=${w} reason=${E?.toString()||""}`),f===P&&(f=null),!p&&setTimeout(k,2e3)}),P.on("error",w=>console.warn(`[ws] error: ${w.message}`)),P},h=k(),b=async P=>{for(;!p;){if(g===!1){y||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${Ne}, protocol ${et}) \u2014 not claiming jobs until versions align.`),y=!0),await new Promise(w=>setTimeout(w,5e3));continue}try{let w=await u.claim(d.signal,P);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:${P}] ${w.status} \u2014 backoff 5s`),await new Promise(R=>setTimeout(R,5e3));continue}let E=await w.json();await S(u,E)}catch(w){if(d.signal.aborted)break;let E=w instanceof Error?w.message:String(w);console.warn(`[claim:${P}] error: ${E} \u2014 backoff 5s`),await new Promise(R=>setTimeout(R,5e3))}}};async function S(P,w){let E={abort:new AbortController,paused:!1};w.role==="chat"&&(E.chatInbox=Cx()),m.set(w.jobId,E);let R=!1,T=null,N=null,j=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),x=async()=>{try{await P.heartbeat(w.jobId)==="claim_lost"&&(R=!0,console.warn(`[job] ${w.jobId} claim lost \u2014 HUB sweeper took it`))}catch(V){let Z=V instanceof Error?V.message:String(V);console.warn(`[job] ${w.jobId} heartbeat error: ${Z}`)}};x();let C=setInterval(()=>{x()},j),L=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(I(w.prompt," \u2502 "));let q=[],Te=null,fr=400,gr=25,dt=500,O=()=>{if(Te&&(clearTimeout(Te),Te=null),q.length===0)return;let V=q.splice(0,q.length),Z=f;if(!Z||Z.readyState!==Z.OPEN)return;let pt={type:"agent_activity",jobId:w.jobId,taskId:w.taskId,projectId:w.projectId,role:w.role,phase:w.phase,events:V};try{Z.send(JSON.stringify(pt))}catch{}},ae=V=>{q.push(V),q.length>dt&&q.shift(),q.length>=gr?O():Te||(Te=setTimeout(O,fr))},_e=w.role==="analysis"&&w.taskId.startsWith("draft::")?w.taskId.slice(7):null,Fe=new Set,vt=null;try{if(!c){R||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:L,finishedAt:new Date().toISOString()});return}if(!Af(o,w.provider??null)){R||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${w.provider??"claude"}"`},startedAt:L,finishedAt:new Date().toISOString()});return}let V=hg(w.jobId);console.log(`[job] ${w.jobId} workspace=${V.dir}`);let Z=D(w,r);T=Z.gitCreds,N=Z.contextGitCreds;let pt=T?.env,yc=Z.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:Z.claudeOauthToken}:void 0,mt=[],fn=null,Ui=null;try{let B=w.role==="build"?"clone":"worktree";mt=await rg(V.dir,w.projectId,w.projectRepos,B,pt,n);let F=await ng(V.dir,w.projectId,w.contextRepo,"worktree",pt,n);Ui=F,fn=F?.workspacePath??null}catch(B){let F=B instanceof Error?B.message:String(B);console.warn(`[job] ${w.jobId} materialize failed: ${F}`),R||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${F}`},startedAt:L,finishedAt:new Date().toISOString()}),V.dispose();return}let wc=async()=>{if(!w.deliveries||w.deliveries.length===0)return[];let B=w.contextRepo?.cloneUrl;if(!B||!pt)throw new Error(B?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let F=[];for(let J of w.deliveries){let z=mt.find(pe=>pe.name===J.name);if(z){if(w.role==="implement"&&J.baseSha&&J.baseSha!==z.baseSha){let pe=await Zf(z,J.deliveryRef,J.deliverySha,J.baseSha,B,pt);console.log(`[job] ${w.jobId} ${z.name}: base moved ${J.baseSha.slice(0,10)} \u2192 ${z.baseSha.slice(0,10)} \u2014 re-applied delivery ${J.deliverySha.slice(0,10)} (${pe.length} conflicted file(s))`),pe.length>0&&F.push(`- **${z.name}**:`,...pe.map(gn=>` - \`${gn}\``));continue}await Qf(z,J.deliveryRef,J.deliverySha,B,pt),console.log(`[job] ${w.jobId} ${z.name}: checked out delivery ${J.deliverySha.slice(0,10)} for ${w.role}`)}}return F},Bi=[];if(w.role==="build"||w.role==="implement"||w.role==="code-review")try{Bi=await wc()}catch(B){let F=B instanceof Error?B.message:String(B);console.warn(`[job] ${w.jobId} delivery checkout failed: ${F}`),R||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${F}`},startedAt:L,finishedAt:new Date().toISOString()}),V.dispose();return}let Fi=w.role==="resolve-conflict"?w.metadata?.taskBranchByRepo??{}:{},kc="";if(w.role==="resolve-conflict"){if(!mt.some(B=>Fi[B.name])){let B="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} ${B}`),R||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:B},startedAt:L,finishedAt:new Date().toISOString()}),V.dispose();return}try{let B=[];for(let F of mt){let J=Fi[F.name];if(!J)continue;let z=await Ua(F,J,pt);console.log(`[job] ${w.jobId} ${F.name}: merged ${J} into ${F.ref} \u2014 ${z.length} conflicted file(s)`),z.length>0?B.push(`- **${F.name}**:`,...z.map(pe=>` - \`${pe}\``)):B.push(`- **${F.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}kc=`
737
743
 
738
744
  ## Conflicts to resolve
739
745
 
740
746
  `+(B.length>0?B.join(`
741
747
  `):"(no task branches to merge)")+`
742
- `}catch(B){let F=B instanceof Error?B.message:String(B);console.warn(`[job] ${w.jobId} conflict merge failed: ${F}`),T||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${F}`},startedAt:L,finishedAt:new Date().toISOString()}),Y.dispose();return}}let Nh=Ci.length>0?`
748
+ `}catch(B){let F=B instanceof Error?B.message:String(B);console.warn(`[job] ${w.jobId} conflict merge failed: ${F}`),R||await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${F}`},startedAt:L,finishedAt:new Date().toISOString()}),V.dispose();return}}let iy=Bi.length>0?`
743
749
 
744
750
  ## Base branch moved \u2014 conflicts to resolve
745
751
 
746
752
  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:
747
753
 
748
- `+Ci.join(`
754
+ `+Bi.join(`
749
755
  `)+`
750
- `:"",Oh=A(v(w.prompt,lt,nn),nn,w.taskId)+tc+Nh,Ei=[...lt.map(B=>B.workspacePath),...nn?[nn]:[]];Ei.length>0&&console.log(`[job] ${w.jobId} --add-dir: ${Ei.join(", ")}`),Ae&&(kt=setInterval(()=>{let F=f;if(!F||F.readyState!==F.OPEN)return;let J;try{J=Pv(Hr(Y.dir,"drafts")).filter(V=>V.endsWith(".json")).sort()}catch{return}for(let V of J){if(Ue.has(V))continue;if(Ue.size>=ml)break;let de;try{let Be=JSON.parse(hf(Hr(Y.dir,"drafts",V),"utf-8")),dr=typeof Be.localRef=="string"?Be.localRef:"",Zn=typeof Be.title=="string"?Be.title:"",Pi=typeof Be.body=="string"?Be.body:"";if(!dr||!Zn)continue;de={localRef:dr,title:Zn,body:Pi,...Be.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Be.links)?{links:Be.links}:{}}}catch{continue}Ue.add(V);let on={type:"child_draft",jobId:w.jobId,projectId:w.projectId,draftId:Ae,child:de};try{F.send(JSON.stringify(on))}catch{}}},1500));try{let B={workspaceDir:Y.dir,role:w.role,prompt:Oh,addDirs:Ei,metadata:w.metadata??{},...w.model?{model:w.model}:{},...Za?{env:Za}:{},signal:I.abort.signal,onActivity:ae},F=I.chatInbox?await c.run({...B,interactive:{inbox:I.chatInbox.iterable}}):await _m(c,B,{jobId:w.jobId,policy:l,onBeforeRetry:async()=>{Y.clean();for(let re of lt)try{await Hm(re);let pe=Ii[re.name];w.role==="resolve-conflict"&&pe&&await pa(re,pe,ct)}catch(pe){let sn=pe instanceof Error?pe.message:String(pe);console.warn(`[job] ${w.jobId} worktree reset failed (${re.name}): ${sn}`)}try{await ec()}catch(re){let pe=re instanceof Error?re.message:String(re);console.warn(`[job] ${w.jobId} delivery re-checkout failed: ${pe}`)}},aborted:()=>T||I.paused}),J=[];if(Nv.has(w.role)&&lt.length>0){let re=w.metadata??{},pe=typeof re.commitMessage=="string"?re.commitMessage:`${w.taskId}: changes`,sn=w.contextRepo?.cloneUrl,nc=N?.env;if(!sn||!nc)throw new Error("delivery requested but "+(sn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Dh=w.taskId.includes(":")?w.taskId.slice(w.taskId.indexOf(":")+1):w.taskId;for(let ut of lt){let an=await Wm(ut,pe);if(!an){console.log(`[job] ${w.jobId} ${ut.name}: no changes \u2014 no delivery`);continue}let Ai=`codepipe/deliveries/${Dh}/${w.jobId}/${ut.name}`;await qm(ut,an,Ai,sn,nc),J.push({name:ut.name,deliveryRef:Ai,deliverySha:an,baseSha:ut.baseSha}),console.log(`[job] ${w.jobId} ${ut.name}: delivered ${an.slice(0,10)} \u2192 ${Ai}`);let oc=await Ym(ut,an);if(oc.trim().length>0){let Lh=Hr("display",`${ut.name}.diff`),ic=Hr(Y.dir,Lh);Ev(_v(ic),{recursive:!0}),Av(ic,oc)}}}if(w.role==="resolve-conflict"&&J.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 V;w.role==="build"&&(V=rf(Y.dir),console.log(`[job] ${w.jobId} build verdict: ok=${V.ok}`+(V.failedStep?` failedStep=${V.failedStep}`:"")));let de;w.role==="code-review"&&(de=sf(Y.dir),console.log(`[job] ${w.jobId} review verdict: approved=${de.approved}`));let on=F.artifactPaths.length>0?F.artifactPaths:Y.listFiles(),Be=Array.from(new Set(on)),dr;if(Ti)try{let re=w.role==="index"?["adr/SOURCES.md"]:w.role==="backfill"?["adr"]:[],pe=await ef(Ti,re);pe.length>0&&(dr=pe,console.log(`[job] ${w.jobId} captured ${pe.length} knowledge file(s) for Context Repo`))}catch(re){let pe=re instanceof Error?re.message:String(re);console.warn(`[job] ${w.jobId} knowledge capture failed (non-fatal): ${pe}`)}let{artifacts:Zn,omitted:Pi,dropped:rc}=lf(Y.dir,Be);for(let re of Pi)console.warn(`[job] ${w.jobId} artifact ${re.path} (${re.bytes} bytes) exceeded upload budget \u2014 content omitted`);rc.length>0&&console.warn(`[job] ${w.jobId} artifact listing truncated: ${rc.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let eo={jobId:w.jobId,status:"succeeded",artifacts:Zn,...dr?{contextWrites:dr}:{},...J.length>0?{deliveries:J}:{},log:Ov(F.log),startedAt:L,finishedAt:new Date().toISOString(),usage:F.usage,...F.rateLimit?{rateLimit:F.rateLimit}:{},...V?{build:V}:{},...de?{review:de}:{}};if(T||I.paused)console.warn(`[job] ${w.jobId} skipping result upload \u2014 ${I.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await P.submitResult(eo),console.log(`[job] ${w.jobId} done \u2014 uploaded ${eo.artifacts.length} artifact(s):`);for(let re of eo.artifacts){let pe=Buffer.from(re.contentBase64,"base64").length;console.log(` \xB7 ${re.path} (${pe} bytes)`)}eo.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(B){let F=B instanceof Error?B.message:String(B);if(I.paused)console.log(`[job] ${w.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(T)console.warn(`[job] ${w.jobId} failed after claim lost (${F}) \u2014 skipping result upload`);else{let J=jm(B),V=B instanceof Lt,de=B instanceof yt;console.warn(J?`[job] ${w.jobId} failed: ${F} (Claude auth \u2014 token invalid/expired)`:V?`[job] ${w.jobId} failed: ${F} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:de?`[job] ${w.jobId} failed: ${F} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${w.jobId} failed: ${F}`),await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:F},startedAt:L,finishedAt:new Date().toISOString(),...J?{authError:!0}:{},...V?{buildInconclusive:!0}:{},...de?{reviewInconclusive:!0}:{}})}}finally{Y.dispose()}}finally{clearInterval(C),kt&&clearInterval(kt),O(),I.chatInbox?.close(),m.delete(w.jobId),R?.cleanup(),N?.cleanup()}}function D(P,w){if(!P.credBundle)return{gitCreds:null,contextGitCreds:null};if(!w)return console.warn(`[job] ${P.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let I;try{I=JSON.parse(Er(w,P.credBundle).toString("utf-8"))}catch(j){return console.warn(`[job] ${P.jobId} failed to open credBundle: ${j instanceof Error?j.message:String(j)}`),{gitCreds:null,contextGitCreds:null}}let T=ua(I);T&&console.log(`[job] ${P.jobId} cred bundle opened \u2014 git creds configured`);let R=Lm(I,P.contextRepo.cloneUrl),N={gitCreds:T,contextGitCreds:R};return I.claudeOauthToken&&(N.claudeOauthToken=I.claudeOauthToken),N}function E(P,w){return P.split(`
751
- `).map(I=>w+I).join(`
752
- `)}function v(P,w,I){let T=w[0]?.workspacePath??"";return P.replace(/\{\{codeDir\}\}/g,T).replace(/\{\{codeRoot\}\}/g,T?T.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,I??"")}function A(P,w,I){let T=P,R=I.includes("::")?"":I.split(":",2)[1]??"",N=j=>{if(!w||!R)return"";try{return hf(Hr(w,"tasks",R,j),"utf-8").trim()}catch{return""}};if(T.includes("{{solutionMd}}")){let j=N("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";T=T.replace(/\{\{solutionMd\}\}/g,()=>j)}if(T.includes("{{taskDescription}}")){let j=N("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";T=T.replace(/\{\{taskDescription\}\}/g,()=>j)}return T}let M=P=>{if(p)return;p=!0,console.log(`
753
- [${P}] shutting down`),d.abort();let w=[...m.keys()];for(let R of m.values())R.abort.abort();let I=new AbortController,T=setTimeout(()=>I.abort(),3e3);(async()=>(await Promise.all(w.map(async R=>{try{await u.releaseJob(R,`sandbox ${P}`,I.signal),console.log(`[${P}] released job ${R}`)}catch(N){let j=N instanceof Error?N.message:String(N);console.warn(`[${P}] release failed: ${j} (sweeper will reclaim)`)}})),clearTimeout(T),h.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>M("SIGINT")),process.on("SIGTERM",()=>M("SIGTERM"));let K=[$("implementation")];e.planningLane!==!1?K.push($("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(K)}var li,Nv,yf=k(()=>{"use strict";W();Le();Qi();Im();Nm();xe();oi();Mm();ia();tf();nf();af();uf();gf();li=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Nv=new Set(["implement","resolve-conflict"])});var Wr=k(()=>{"use strict";hm();yf();oi()});import{cancel as Lv,isCancel as bf,log as Ve,password as Mv,text as Uv}from"@clack/prompts";function Bv(t){return bf(t)&&(Lv("aborted"),process.exit(1)),typeof t=="string"?t:""}function Fv(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function Gv(t){let e=us({redirectUri:ls,challenge:t.challenge,state:t.state});Ve.message(`Open this URL, approve the access, and paste the code shown:
754
- ${e}`);let r=await Uv({message:"Authorization code \u2014 blank to skip"});if(bf(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=Tu(r,t.state);return await ds({code:n,verifier:t.verifier,state:t.state,redirectUri:ls})}catch(n){return Ve.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function Kv(t){if(Ji()?.claude?.oauthToken&&!t.farm)return Ve.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;Ve.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=vo(),n;try{n=await Cu({...r,openUrl:Xt,log:i=>Ve.message(i)})}catch(i){Ve.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await Gv(r);if(s===null)return null;n=s}let o=await Pt(n.oauthToken);return o==="invalid"?(Ve.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(Ve.success(`Claude: logged in \u2014 ${Fv(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function Hv(t){Ve.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?`
755
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=Bv(await Mv({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||Ve.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):(Ve.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 kf,$f=k(()=>{"use strict";xo();vr();oe();ms();kf={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:Kv,promptManual:Hv,validate:Pt}});function vf(t){return kf}async function xf(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Sf=k(()=>{"use strict";$f()});async function Yr(t,e,r){return e.host==="github"?qv(t,e,r):e.host==="gitlab"?Zv(t,e,r):tx(t,e,r)}async function Rf(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 Ut(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Tf(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 Mt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Cf(e.gitlabToken,t):o}}return e.bitbucket?(await qr(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await If(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 Tf(t,e){let r=!1;try{r=(await Ut(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 Cf(t,e){let r=!1;try{r=(await Mt(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 If(t,e){let r=!1;try{r=(await qr(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 Ut(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(Wv+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 qv(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 Yv(n,e,r),i=await zv(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Ir(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Jv(n,o.owner,o.name,a.path,i)||await Xv(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 Yv(t,e,r){let n=await Ut(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 Tf(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Vv(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 Ut(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 Vv(t,e){let{status:r,data:n}=await Ut(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function zv(t,e,r){let{data:n}=await Ut(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Jv(t,e,r,n,o){let{status:i,data:s}=await Ut(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Xv(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 Ut(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Mt(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(Qv+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 Zv(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 Mt(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 Cf(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Mt(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 Mt(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 Mt(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=Ir(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await Mt(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 Mt(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 qr(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(ex+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 tx(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 qr(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 If(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 qr(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=Ir(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await qr(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 qr(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 Wv,Qv,ex,ui=k(()=>{"use strict";ir();Wv="https://api.github.com";Qv="https://gitlab.com/api/v4";ex="https://api.bitbucket.org/2.0"});function Me(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=rx[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 rx,di=k(()=>{"use strict";rx={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as nx}from"node:crypto";import{existsSync as Ef,mkdirSync as ox,readFileSync as Pf,readdirSync as ix,rmSync as pi,writeFileSync as sx}from"node:fs";import{homedir as ax}from"node:os";import{dirname as cx,join as fa}from"node:path";function Af(){return fa(ax(),".codepipe","init-drafts")}function ga(t){let e=nx("sha256").update(t).digest("hex").slice(0,16);return fa(Af(),`${e}.json`)}function jf(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=lx)}function _f(t){let e=ga(t);if(!Ef(e))return null;try{let r=JSON.parse(Pf(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:jf(r.savedAt)?(pi(e,{force:!0}),null):r}catch{return null}}function ha(t){pi(ga(t),{force:!0})}function Nf(){let t=Af();if(Ef(t))for(let e of ix(t)){let r=fa(t,e);try{let n=JSON.parse(Pf(r,"utf-8"));jf(n.savedAt)&&pi(r,{force:!0})}catch{pi(r,{force:!0})}}}var lx,Vr,Of=k(()=>{"use strict";lx=24*60*60*1e3;Vr=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(){ha(this.cwd)}persist(){let e=ga(this.cwd);ox(cx(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};sx(e,JSON.stringify(r,null,2)+`
756
- `,{mode:384})}}});function Df(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 Lf(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 Mf=k(()=>{"use strict"});import{existsSync as ux}from"node:fs";import{join as dx}from"node:path";import{simpleGit as px}from"simple-git";function hx(t){let e=t.split("/");return e[e.length-1]??t}function Uf(t){if(t.filter(r=>!fx.test(hx(r))).length>mx)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(gx.has(n))return!0}return!1}async function yx(t){try{let r=(await px(t).raw(["ls-files"])).split(`
757
- `).map(n=>n.trim()).filter(Boolean);return Uf(r)}catch{return!1}}async function wx(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)?Uf(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Bf(t,e){for(let r of t)try{let n=e.localRoot!=null?dx(e.localRoot,r.mountAs??r.name):null;if(n&&ux(n)?await yx(n):await wx(r,e.tokens))return!0}catch{}return!1}var mx,fx,gx,Ff=k(()=>{"use strict";mx=3,fx=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,gx=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Gf}from"node:fs";import{join as Kf}from"node:path";import{simpleGit as Hf}from"simple-git";async function Gn(t,e,r={}){let n=r.log??bx,o=[];for(let i of e){let s=Kf(t,i.mountAs),a=yl(i);if(!Gf(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 Hf().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=Fn(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(!Gf(Kf(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=Hf(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!kx(l,a)){n.warn(`${i.mountAs}/ origin (${Fn(l)||"none"}) != expected (${Fn(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:Fn(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=Fn(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 kx(t,e){return Wf(t)===Wf(e)}function Wf(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Fn(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function qf(t={}){let e=ge();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 Gn(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 bx,mi=k(()=>{"use strict";tt();bx={info:t=>console.log(t),warn:t=>console.warn(t)}});import{spawn as Vf}from"node:child_process";import{existsSync as Yf}from"node:fs";import{homedir as $x,hostname as vx}from"node:os";import{join as fi}from"node:path";async function xx(t,e,r){let n=ke(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Ye(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 Du(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 ${Ye(e)} still holds its token.
758
- 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`),Ol(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function Sx(t,e,r){let n=ke(e)!==null;if(!await xx(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 To(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof U&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof U&&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 U?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 sr({hub:t.hubUrl,token:o,name:r.name??`${vx()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function Rx(t,e){let r=ke(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=Re(r.sealPublicKey);if(!G(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=fo(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 ya(t,e,r){await Sx(t,e,r),Rx(t.projectId,e)}function Tx(t){return[...t?["--profile",t]:[],"worker","start"]}function Cx(t){let e={...t};for(let r of Xi)delete e[r];return e}function wa(t){let e=Vf(process.execPath,[t.entry,...Tx(t.profile)],{stdio:["ignore","pipe","pipe"],env:Cx(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
759
- `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function Ix(t,e){let r=process.cwd(),n=fi(r,et);if(uo(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Yf(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 Q(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 $a(r);if(!hl(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=G(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await ri({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=fi($x(),".codepipe",e?fi("profiles",e,"context-config"):"context-config");if(No(c.contextDir,l,a),!Yf(fi(c.contextDir,"project.yaml"))){Tr(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};xn(c.contextDir,it(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function ba(t){let{cfg:e,profile:r}=mo(t.profile);await Ix(e,r),await ya(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let g=y=>b=>{for(let h of b.toString("utf-8").split(`
756
+ `:"",sy=A(v(w.prompt,mt,fn),fn,w.taskId)+kc+iy,Gi=[...mt.map(B=>B.workspacePath),...fn?[fn]:[]];Gi.length>0&&console.log(`[job] ${w.jobId} --add-dir: ${Gi.join(", ")}`),_e&&(vt=setInterval(()=>{let F=f;if(!F||F.readyState!==F.OPEN)return;let J;try{J=$x(en(V.dir,"drafts")).filter(z=>z.endsWith(".json")).sort()}catch{return}for(let z of J){if(Fe.has(z))continue;if(Fe.size>=Pl)break;let pe;try{let Ge=JSON.parse(kg(en(V.dir,"drafts",z),"utf-8")),hr=typeof Ge.localRef=="string"?Ge.localRef:"",ao=typeof Ge.title=="string"?Ge.title:"",Ki=typeof Ge.body=="string"?Ge.body:"";if(!hr||!ao)continue;pe={localRef:hr,title:ao,body:Ki,...Ge.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Ge.links)?{links:Ge.links}:{}}}catch{continue}Fe.add(z);let gn={type:"child_draft",jobId:w.jobId,projectId:w.projectId,draftId:_e,child:pe};try{F.send(JSON.stringify(gn))}catch{}}},1500));try{let B={workspaceDir:V.dir,role:w.role,prompt:sy,addDirs:Gi,metadata:w.metadata??{},...w.model?{model:w.model}:{},...yc?{env:yc}:{},signal:E.abort.signal,onActivity:ae},F=E.chatInbox?await c.run({...B,interactive:{inbox:E.chatInbox.iterable}}):await Lf(c,B,{jobId:w.jobId,policy:l,onBeforeRetry:async()=>{V.clean();for(let re of mt)try{await Vf(re);let me=Fi[re.name];w.role==="resolve-conflict"&&me&&await Ua(re,me,pt)}catch(me){let hn=me instanceof Error?me.message:String(me);console.warn(`[job] ${w.jobId} worktree reset failed (${re.name}): ${hn}`)}try{await wc()}catch(re){let me=re instanceof Error?re.message:String(re);console.warn(`[job] ${w.jobId} delivery re-checkout failed: ${me}`)}},aborted:()=>R||E.paused}),J=[];if(Tx.has(w.role)&&mt.length>0){let re=w.metadata??{},me=typeof re.commitMessage=="string"?re.commitMessage:`${w.taskId}: changes`,hn=w.contextRepo?.cloneUrl,$c=N?.env;if(!hn||!$c)throw new Error("delivery requested but "+(hn?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let ay=w.taskId.includes(":")?w.taskId.slice(w.taskId.indexOf(":")+1):w.taskId;for(let ft of mt){let yn=await zf(ft,me);if(!yn){console.log(`[job] ${w.jobId} ${ft.name}: no changes \u2014 no delivery`);continue}let Hi=`codepipe/deliveries/${ay}/${w.jobId}/${ft.name}`;await Jf(ft,yn,Hi,hn,$c),J.push({name:ft.name,deliveryRef:Hi,deliverySha:yn,baseSha:ft.baseSha}),console.log(`[job] ${w.jobId} ${ft.name}: delivered ${yn.slice(0,10)} \u2192 ${Hi}`);let vc=await Xf(ft,yn);if(vc.trim().length>0){let cy=en("display",`${ft.name}.diff`),xc=en(V.dir,cy);bx(Sx(xc),{recursive:!0}),vx(xc,vc)}}}if(w.role==="resolve-conflict"&&J.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 z;w.role==="build"&&(z=sg(V.dir),console.log(`[job] ${w.jobId} build verdict: ok=${z.ok}`+(z.failedStep?` failedStep=${z.failedStep}`:"")));let pe;w.role==="code-review"&&(pe=lg(V.dir),console.log(`[job] ${w.jobId} review verdict: approved=${pe.approved}`));let gn=F.artifactPaths.length>0?F.artifactPaths:V.listFiles(),Ge=Array.from(new Set(gn)),hr;if(Ui)try{let re=w.role==="index"?["adr/SOURCES.md"]:w.role==="backfill"?["adr"]:[],me=await og(Ui,re);me.length>0&&(hr=me,console.log(`[job] ${w.jobId} captured ${me.length} knowledge file(s) for Context Repo`))}catch(re){let me=re instanceof Error?re.message:String(re);console.warn(`[job] ${w.jobId} knowledge capture failed (non-fatal): ${me}`)}let{artifacts:ao,omitted:Ki,dropped:bc}=pg(V.dir,Ge);for(let re of Ki)console.warn(`[job] ${w.jobId} artifact ${re.path} (${re.bytes} bytes) exceeded upload budget \u2014 content omitted`);bc.length>0&&console.warn(`[job] ${w.jobId} artifact listing truncated: ${bc.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let co={jobId:w.jobId,status:"succeeded",artifacts:ao,...hr?{contextWrites:hr}:{},...J.length>0?{deliveries:J}:{},log:Rx(F.log),startedAt:L,finishedAt:new Date().toISOString(),usage:F.usage,...F.rateLimit?{rateLimit:F.rateLimit}:{},...z?{build:z}:{},...pe?{review:pe}:{}};if(R||E.paused)console.warn(`[job] ${w.jobId} skipping result upload \u2014 ${E.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await P.submitResult(co),console.log(`[job] ${w.jobId} done \u2014 uploaded ${co.artifacts.length} artifact(s):`);for(let re of co.artifacts){let me=Buffer.from(re.contentBase64,"base64").length;console.log(` \xB7 ${re.path} (${me} bytes)`)}co.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(B){let F=B instanceof Error?B.message:String(B);if(E.paused)console.log(`[job] ${w.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(R)console.warn(`[job] ${w.jobId} failed after claim lost (${F}) \u2014 skipping result upload`);else{let J=Df(B),z=B instanceof Mt,pe=B instanceof bt;console.warn(J?`[job] ${w.jobId} failed: ${F} (Claude auth \u2014 token invalid/expired)`:z?`[job] ${w.jobId} failed: ${F} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:pe?`[job] ${w.jobId} failed: ${F} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${w.jobId} failed: ${F}`),await P.submitResult({jobId:w.jobId,status:"failed",artifacts:[],error:{message:F},startedAt:L,finishedAt:new Date().toISOString(),...J?{authError:!0}:{},...z?{buildInconclusive:!0}:{},...pe?{reviewInconclusive:!0}:{}})}}finally{V.dispose()}}finally{clearInterval(C),vt&&clearInterval(vt),O(),E.chatInbox?.close(),m.delete(w.jobId),T?.cleanup(),N?.cleanup()}}function D(P,w){if(!P.credBundle)return{gitCreds:null,contextGitCreds:null};if(!w)return console.warn(`[job] ${P.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let E;try{E=JSON.parse(Lr(w,P.credBundle).toString("utf-8"))}catch(j){return console.warn(`[job] ${P.jobId} failed to open credBundle: ${j instanceof Error?j.message:String(j)}`),{gitCreds:null,contextGitCreds:null}}let R=La(E);R&&console.log(`[job] ${P.jobId} cred bundle opened \u2014 git creds configured`);let T=Ff(E,P.contextRepo.cloneUrl),N={gitCreds:R,contextGitCreds:T};return E.claudeOauthToken&&(N.claudeOauthToken=E.claudeOauthToken),N}function I(P,w){return P.split(`
757
+ `).map(E=>w+E).join(`
758
+ `)}function v(P,w,E){let R=w[0]?.workspacePath??"";return P.replace(/\{\{codeDir\}\}/g,R).replace(/\{\{codeRoot\}\}/g,R?R.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,E??"")}function A(P,w,E){let R=P,T=E.includes("::")?"":E.split(":",2)[1]??"",N=j=>{if(!w||!T)return"";try{return kg(en(w,"tasks",T,j),"utf-8").trim()}catch{return""}};if(R.includes("{{solutionMd}}")){let j=N("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";R=R.replace(/\{\{solutionMd\}\}/g,()=>j)}if(R.includes("{{taskDescription}}")){let j=N("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";R=R.replace(/\{\{taskDescription\}\}/g,()=>j)}return R}let M=P=>{if(p)return;p=!0,console.log(`
759
+ [${P}] shutting down`),d.abort();let w=[...m.keys()];for(let T of m.values())T.abort.abort();let E=new AbortController,R=setTimeout(()=>E.abort(),3e3);(async()=>(await Promise.all(w.map(async T=>{try{await u.releaseJob(T,`sandbox ${P}`,E.signal),console.log(`[${P}] released job ${T}`)}catch(N){let j=N instanceof Error?N.message:String(N);console.warn(`[${P}] release failed: ${j} (sweeper will reclaim)`)}})),clearTimeout(R),h.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>M("SIGINT")),process.on("SIGTERM",()=>M("SIGTERM"));let K=[b("implementation")];e.planningLane!==!1?K.push(b("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(K)}var Ci,Tx,bg=$(()=>{"use strict";W();Ue();us();jf();Mf();Re();vi();Gf();ja();ig();ag();ug();mg();wg();Ci=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Tx=new Set(["implement","resolve-conflict"])});var tn=$(()=>{"use strict";bf();bg();vi()});import{cancel as Ex,isCancel as vg,log as Qe,password as Ix,text as Px}from"@clack/prompts";function Ax(t){return vg(t)&&(Ex("aborted"),process.exit(1)),typeof t=="string"?t:""}function jx(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function _x(t){let e=vs({redirectUri:$s,challenge:t.challenge,state:t.state});Qe.message(`Open this URL, approve the access, and paste the code shown:
760
+ ${e}`);let r=await Px({message:"Authorization code \u2014 blank to skip"});if(vg(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=Ku(r,t.state);return await xs({code:n,verifier:t.verifier,state:t.state,redirectUri:$s})}catch(n){return Qe.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function Nx(t){if(cs()?.claude?.oauthToken&&!t.farm)return Qe.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;Qe.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=_o(),n;try{n=await Hu({...r,openUrl:Qt,log:i=>Qe.message(i)})}catch(i){Qe.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await _x(r);if(s===null)return null;n=s}let o=await At(n.oauthToken);return o==="invalid"?(Qe.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(Qe.success(`Claude: logged in \u2014 ${jx(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function Ox(t){Qe.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?`
761
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=Ax(await Ix({message:"Claude OAuth token \u2014 blank to skip"})).trim();return e?(e.startsWith("sk-ant-")||Qe.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):(Qe.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 xg,Sg=$(()=>{"use strict";No();Pr();oe();Ts();xg={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:Nx,promptManual:Ox,validate:At}});function Tg(t){return xg}async function Rg(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Cg=$(()=>{"use strict";Sg()});async function nn(t,e,r){return e.host==="github"?Lx(t,e,r):e.host==="gitlab"?Hx(t,e,r):Yx(t,e,r)}async function Eg(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 Bt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ig(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 Ut(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Pg(e.gitlabToken,t):o}}return e.bitbucket?(await rn(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ag(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 Ig(t,e){let r=!1;try{r=(await Bt(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 Pg(t,e){let r=!1;try{r=(await Ut(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 Ag(t,e){let r=!1;try{r=(await rn(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 Bt(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(Dx+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 Lx(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 Mx(n,e,r),i=await Bx(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Dr(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Fx(n,o.owner,o.name,a.path,i)||await Gx(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 Mx(t,e,r){let n=await Bt(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 Ig(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Ux(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 Bt(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 Ux(t,e){let{status:r,data:n}=await Bt(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Bx(t,e,r){let{data:n}=await Bt(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Fx(t,e,r,n,o){let{status:i,data:s}=await Bt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Gx(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 Bt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Ut(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(Kx+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 Hx(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 Ut(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 Pg(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Ut(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 Ut(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 Ut(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=Dr(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let m=(await Ut(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 Ut(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 rn(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(Wx+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 Yx(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 rn(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 Ag(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 rn(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=Dr(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await rn(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 rn(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 Dx,Kx,Wx,Ei=$(()=>{"use strict";ar();Dx="https://api.github.com";Kx="https://gitlab.com/api/v4";Wx="https://api.bitbucket.org/2.0"});function Be(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=qx[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 qx,Ii=$(()=>{"use strict";qx={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as Vx}from"node:crypto";import{existsSync as jg,mkdirSync as zx,readFileSync as _g,readdirSync as Jx,rmSync as Pi,writeFileSync as Xx}from"node:fs";import{homedir as Qx}from"node:os";import{dirname as Zx,join as Fa}from"node:path";function Ng(){return Fa(Qx(),".codepipe","init-drafts")}function Ga(t){let e=Vx("sha256").update(t).digest("hex").slice(0,16);return Fa(Ng(),`${e}.json`)}function Og(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=eS)}function Dg(t){let e=Ga(t);if(!jg(e))return null;try{let r=JSON.parse(_g(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Og(r.savedAt)?(Pi(e,{force:!0}),null):r}catch{return null}}function Ka(t){Pi(Ga(t),{force:!0})}function Lg(){let t=Ng();if(jg(t))for(let e of Jx(t)){let r=Fa(t,e);try{let n=JSON.parse(_g(r,"utf-8"));Og(n.savedAt)&&Pi(r,{force:!0})}catch{Pi(r,{force:!0})}}}var eS,on,Mg=$(()=>{"use strict";eS=24*60*60*1e3;on=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(){Ka(this.cwd)}persist(){let e=Ga(this.cwd);zx(Zx(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Xx(e,JSON.stringify(r,null,2)+`
762
+ `,{mode:384})}}});function Ug(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 Bg(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 Fg=$(()=>{"use strict"});import{existsSync as tS}from"node:fs";import{join as rS}from"node:path";import{simpleGit as nS}from"simple-git";function aS(t){let e=t.split("/");return e[e.length-1]??t}function Gg(t){if(t.filter(r=>!iS.test(aS(r))).length>oS)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(sS.has(n))return!0}return!1}async function cS(t){try{let r=(await nS(t).raw(["ls-files"])).split(`
763
+ `).map(n=>n.trim()).filter(Boolean);return Gg(r)}catch{return!1}}async function lS(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)?Gg(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Kg(t,e){for(let r of t)try{let n=e.localRoot!=null?rS(e.localRoot,r.mountAs??r.name):null;if(n&&tS(n)?await cS(n):await lS(r,e.tokens))return!0}catch{}return!1}var oS,iS,sS,Hg=$(()=>{"use strict";oS=3,iS=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,sS=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Wg}from"node:fs";import{join as Yg}from"node:path";import{simpleGit as qg}from"simple-git";async function Qn(t,e,r={}){let n=r.log??uS,o=[];for(let i of e){let s=Yg(t,i.mountAs),a=Nl(i);if(!Wg(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 qg().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=Xn(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(!Wg(Yg(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=qg(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!dS(l,a)){n.warn(`${i.mountAs}/ origin (${Xn(l)||"none"}) != expected (${Xn(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:Xn(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=Xn(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 dS(t,e){return Vg(t)===Vg(e)}function Vg(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function Xn(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function zg(t={}){let e=ye();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 Qn(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 uS,Ai=$(()=>{"use strict";it();uS={info:t=>console.log(t),warn:t=>console.warn(t)}});import{spawn as Xg}from"node:child_process";import{existsSync as Jg}from"node:fs";import{homedir as pS,hostname as mS}from"node:os";import{join as ji}from"node:path";async function fS(t,e,r){let n=ve(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Xe(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 Zu(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 ${Xe(e)} still holds its token.
764
+ 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`),Ql(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function gS(t,e,r){let n=ve(e)!==null;if(!await fS(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 Lo(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof U&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof U&&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 U?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 lr({hub:t.hubUrl,token:o,name:r.name??`${mS()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function hS(t,e){let r=ve(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=Ce(r.sealPublicKey);if(!G(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=To(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 Ha(t,e,r){await gS(t,e,r),hS(t.projectId,e)}function yS(t){return[...t?["--profile",t]:[],"worker","start"]}function wS(t){let e={...t};for(let r of ls)delete e[r];return e}function Wa(t){let e=Xg(process.execPath,[t.entry,...yS(t.profile)],{stdio:["ignore","pipe","pipe"],env:wS(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
765
+ `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function kS(t,e){let r=process.cwd(),n=ji(r,ot);if(vo(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Jg(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 Q(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 Va(r);if(!_l(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=G(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await bi({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=ji(pS(),".codepipe",e?ji("profiles",e,"context-config"):"context-config");if(Wo(c.contextDir,l,a),!Jg(ji(c.contextDir,"project.yaml"))){Nr(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};_n(c.contextDir,ct(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 Ya(t){let{cfg:e,profile:r}=So(t.profile);await kS(e,r),await Ha(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(m,f)=>{let g=y=>k=>{for(let h of k.toString("utf-8").split(`
760
766
  `))h.length>0&&y.write(`${f} ${h}
761
- `)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},i=(m,f)=>{let g=Vf(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,m),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=wa({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
767
+ `)};m.stdout?.on("data",g(process.stdout)),m.stderr?.on("data",g(process.stderr))},i=(m,f)=>{let g=Xg(process.execPath,[n,...f],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,m),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=Wa({entry:n,profile:r,onLine:m=>process.stdout.write(`[worker] ${m}
762
768
  `)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=m=>{if(!l){l=!0,console.log(`
763
- [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(y,b)=>g({name:m,code:y??(b?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var ka=k(()=>{"use strict";Le();Wr();Ie();ft();ra();ir();we();oe();tt();Kn()});var ng={};sc(ng,{replCommand:()=>Ra});import{existsSync as eg,mkdirSync as Ex,readFileSync as Px,writeFileSync as Ax}from"node:fs";import{homedir as jx}from"node:os";import{dirname as _x,join as tg}from"node:path";import*as zr from"node:readline";async function Ra(t={}){let e=ge();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=G(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)),fn(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=nr(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
769
+ [up] ${m} \u2014 stopping both roles`);for(let{child:f}of c)f.exitCode===null&&f.kill(m);setTimeout(()=>{for(let{name:f,child:g}of c)g.exitCode===null&&(console.warn(`[up] ${f} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:m,child:f})=>new Promise(g=>{f.on("exit",(y,k)=>g({name:m,code:y??(k?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 qa=$(()=>{"use strict";Ue();tn();Pe();yt();Ia();ar();we();oe();it();Zn()});var sh={};Wi(sh,{replCommand:()=>Qa});import{existsSync as nh,mkdirSync as bS,readFileSync as $S,writeFileSync as vS}from"node:fs";import{homedir as xS}from"node:os";import{dirname as SS,join as oh}from"node:path";import*as sn from"node:readline";async function Qa(t={}){let e=ye();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=G(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)),Tn(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=ir(e.contextDir),o=Object.keys(n);o.length>0&&console.log(`
764
770
  \u26A0 unfinished local apply: ${o.map(a=>`${a} (${n[a].repos.map(c=>c.mountAs).join(", ")})`).join("; ")}
765
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=zr.createInterface({input:process.stdin,output:process.stdout,completer:Nx,history:eS(),removeHistoryDuplicates:!0}),s={ws:e,secrets:r,connection:"connecting",rl:i,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Vu(a=>Ft(s,a)),s.daemon=ei({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>Ft(s,a),warn:a=>Ft(s,a)},onEvent:a=>Vx(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 ya(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=wa({entry:c,profile:t.profile,onLine:u=>Ft(s,`[worker] ${u}`)});l.on("exit",(u,p)=>{s.workerExited=!0,!Sa&&Bt(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.`)}xa(s),i.prompt(),i.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await Ox(s,c)){Zf(s);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}s.unread=0,xa(s),i.prompt()}),i.on("close",()=>{Zf(s)})}function Nx(t){let e=zf.filter(r=>r.startsWith(t));return[e.length?e:zf,t]}async function Ox(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return Dx(),!1;case"/status":return await Lx(t),!1;case"/tasks":return await Mx(t,n),!1;case"/task":return await Ux(t,n),!1;case"/sync":return await Bx(t),!1;case"/logs":return zx(t,n),!1;case"/monitor":return Jx(t),!1;case"/apply":return await Xf(t,n,"apply"),!1;case"/unstash":return await Xf(t,n,"unstash"),!1;case"/applied":return await Fx(t,n),!1;case"/abort":return await Gx(t,n),!1;case"/approve":return await Qf(t,n,"approve"),!1;case"/merge":return await Qf(t,n,"merge"),!1;case"/login":return Hx(t,n),!1;case"/secret":return Wx(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Dx(){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(`
766
- `))}async function Lx(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=eg(tg(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function Mx(t,e){let r=Xx(e,"--phase");try{let n=await Bu(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){Hn(n)}}async function Ux(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Fu(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){Hn(n)}}async function Bx(t){let e=await Gn(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 Xf(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await id(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function Fx(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=nr(t.ws.contextDir)[r],i=Qx(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?Kx(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 Gu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);bs(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Hn(c)}}async function Qf(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Hu(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Hn(o)}}async function Gx(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=Zx(e,"--reason")||"local apply aborted";await ad(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await Ku(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Hn(o)}}function Kx(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Hx(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},X(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 Wx(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(`
767
- `)}`:" (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}qx(t.secrets,n,i),X(t.secrets),fn(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}Yx(t.secrets,n),X(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function qx(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 Yx(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 Vx(t,e){switch(e.kind){case"connected":t.connection="connecting",Ft(t,"[hub] connected");break;case"registered":t.connection="registered",Ft(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Bt(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Ft(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Bt(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Bt(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?Ft(t,`[hub] action ${e.actionType} done`):Bt(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?Bt(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):Bt(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function Ft(t,e){t.logBuffer.push(e),t.logBuffer.length>rg&&t.logBuffer.shift(),t.follow&&Bt(t,e)}function zx(t,e){let r=e[0];if(r==="follow"||r==="on"){va(t,!0);return}if(r==="off"){va(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(rg,Number(r)||Jf)):Jf,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 Jx(t){va(t,!t.follow)}function va(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Bt(t,e){zr.cursorTo(process.stdout,0),zr.clearLine(process.stdout,0),process.stdout.write(e+`
768
- `),t.unread+=1,xa(t),t.rl.prompt(!0)}function xa(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function Zf(t){if(Sa)return;Sa=!0,tS(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
771
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let i=sn.createInterface({input:process.stdin,output:process.stdout,completer:TS,history:WS(),removeHistoryDuplicates:!0}),s={ws:e,secrets:r,connection:"connecting",rl:i,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};dd(a=>Gt(s,a)),s.daemon=wi({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:a=>Gt(s,a),warn:a=>Gt(s,a)},onEvent:a=>US(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 Ha(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=Wa({entry:c,profile:t.profile,onLine:u=>Gt(s,`[worker] ${u}`)});l.on("exit",(u,p)=>{s.workerExited=!0,!Xa&&Ft(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.`)}Ja(s),i.prompt(),i.on("line",async a=>{let c=a.trim();if(c.length>0)try{if(await RS(s,c)){rh(s);return}}catch(l){console.error(l instanceof Error?l.message:String(l))}s.unread=0,Ja(s),i.prompt()}),i.on("close",()=>{rh(s)})}function TS(t){let e=Qg.filter(r=>r.startsWith(t));return[e.length?e:Qg,t]}async function RS(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return CS(),!1;case"/status":return await ES(t),!1;case"/tasks":return await IS(t,n),!1;case"/task":return await PS(t,n),!1;case"/sync":return await AS(t),!1;case"/logs":return BS(t,n),!1;case"/monitor":return FS(t),!1;case"/apply":return await eh(t,n,"apply"),!1;case"/unstash":return await eh(t,n,"unstash"),!1;case"/applied":return await jS(t,n),!1;case"/abort":return await _S(t,n),!1;case"/approve":return await th(t,n,"approve"),!1;case"/merge":return await th(t,n,"merge"),!1;case"/login":return OS(t,n),!1;case"/secret":return DS(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function CS(){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(`
772
+ `))}async function ES(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=nh(oh(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function IS(t,e){let r=GS(e,"--phase");try{let n=await nd(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){eo(n)}}async function PS(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await od(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){eo(n)}}async function AS(t){let e=await Qn(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 eh(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await vd(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function jS(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=ir(t.ws.contextDir)[r],i=KS(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?NS(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 id(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);As(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){eo(c)}}async function th(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await ad(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){eo(o)}}async function _S(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=HS(e,"--reason")||"local apply aborted";await Sd(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await sd(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){eo(o)}}function NS(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function OS(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},X(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 DS(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(`
773
+ `)}`:" (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}LS(t.secrets,n,i),X(t.secrets),Tn(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}MS(t.secrets,n),X(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function LS(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 MS(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 US(t,e){switch(e.kind){case"connected":t.connection="connecting",Gt(t,"[hub] connected");break;case"registered":t.connection="registered",Gt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Ft(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Gt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Ft(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Ft(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?Gt(t,`[hub] action ${e.actionType} done`):Ft(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break;case"local_applied":e.ok?Ft(t,`[apply] ${e.taskKey}: branch ${(e.branches??[]).join(", ")} created locally (your checkout is untouched) \u2014 review, push, then: /applied ${e.taskKey} --pr <url>`):Ft(t,`[apply] ${e.taskKey}: auto-apply failed \u2014 task stays in READY_TO_APPLY: ${e.error??"?"}`);break}}function Gt(t,e){t.logBuffer.push(e),t.logBuffer.length>ih&&t.logBuffer.shift(),t.follow&&Ft(t,e)}function BS(t,e){let r=e[0];if(r==="follow"||r==="on"){za(t,!0);return}if(r==="off"){za(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(ih,Number(r)||Zg)):Zg,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 FS(t){za(t,!t.follow)}function za(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Ft(t,e){sn.cursorTo(process.stdout,0),sn.clearLine(process.stdout,0),process.stdout.write(e+`
774
+ `),t.unread+=1,Ja(t),t.rl.prompt(!0)}function Ja(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}function rh(t){if(Xa)return;Xa=!0,YS(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
769
775
  bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
770
- 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 Xx(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Qx(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 Zx(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Hn(t){t instanceof U?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function eS(){if(!eg(gi))return[];try{return Px(gi,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function tS(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{Ex(_x(gi),{recursive:!0}),Ax(gi,r.slice().reverse().join(`
776
+ 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 GS(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function KS(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 HS(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function eo(t){t instanceof U?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function WS(){if(!nh(_i))return[];try{return $S(_i,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function YS(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{bS(SS(_i),{recursive:!0}),vS(_i,r.slice().reverse().join(`
771
777
  `)+`
772
- `)}catch{}}var gi,zf,rg,Jf,Sa,Ta=k(()=>{"use strict";ea();we();Co();oe();tt();mi();ka();ks();gi=tg(jx(),".codepipe","history"),zf=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],rg=500,Jf=40;Sa=!1});import{existsSync as og,readFileSync as rS,readdirSync as nS}from"node:fs";import{join as ig}from"node:path";import{simpleGit as oS}from"simple-git";import{parse as iS}from"yaml";function sS(t){let e=new Map,r=ig(t,Oi);if(!og(r))return e;let n;try{n=iS(rS(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 aS(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return mr({modelFormatVersion:2,repos:e})}function sg(t,e){let r=ig(t,e);if(!og(r))return[];let n=[];for(let o of nS(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...sg(t,i)):n.push(i)}return n}async function Ca(t,e){let r=[],n=0;for(let l of e){r.push(...l.files);let u=`model/derived/structure/${l.repo}`;for(let p of sg(t,u))l.emittedShardPaths.has(p)||(r.push({path:p,content:"",deleted:!0}),n++)}let o=sS(t);for(let l of e)o.set(l.repo,{builtFromCommit:l.headCommit,counts:l.counts});r.push({path:Oi,content:aS(o)});let i=oS(t),s=(await i.revparse(["HEAD"]).catch(()=>"")).trim(),a=`model: build ${e.map(l=>`${l.repo}@${l.headCommit.slice(0,10)}`).join(", ")}`;return await Ee(t,r,a),{committed:(await i.revparse(["HEAD"]).catch(()=>"")).trim()!==s,filesWritten:r.filter(l=>!l.deleted).length,filesDeleted:n}}var ag=k(()=>{"use strict";W();ot()});import{simpleGit as cS}from"simple-git";async function lg(t,e,r){let o=await cS(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
773
- `))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 yi(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=he(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=he(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function ug(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let b of n){let h=new Set;for(let E of b.files){let v=o.get(E)??E;!i.has(v)||s(v)||h.add(v)}if(h.size<2||h.size>a.commitFileCap)continue;let $=Math.max(0,r-b.timeSec),S=Math.pow(.5,$/c),D=[...h].sort();for(let E of D)l.set(E,(l.get(E)??0)+S);for(let E=0;E<D.length;E++)for(let v=E+1;v<D.length;v++){let A=`${D[E]}\0${D[v]}`;u.set(A,(u.get(A)??0)+S),p.set(A,(p.get(A)??0)+1)}}let d=[],m=a.jaccardMinPct/100;for(let[b,h]of u){if((p.get(b)??0)<a.supportMin)continue;let[$,S]=b.split("\0"),D=(l.get($)??0)+(l.get(S)??0)-h,E=D>0?h/D:0;E<m||d.push({a:$,b:S,weight:Math.round(E*cg)/cg})}let f=new Map;for(let b of d)for(let h of[b.a,b.b])f.has(h)||f.set(h,[]),f.get(h).push(b);let g=new Map;for(let[,b]of f)b.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(([,b])=>b===2).map(([b])=>b).map(b=>({kind:"correlates",from:ye("code",e,b.a),to:ye("code",e,b.b),weight:b.weight})).sort((b,h)=>b.from<h.from?-1:b.from>h.from?1:b.to<h.to?-1:1)}var hi,cg,Ia=k(()=>{"use strict";W();hi=["package-lock.json","pnpm-lock.yaml","yarn.lock"];cg=1e4});import{createHash as lS}from"node:crypto";function dS(t,e,r,n){for(let o=0;;o++){let s=`e_${lS("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function dg(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(v=>v.entityId)),d=new Set,m=[],f=new Map,g=(v,A)=>{d.add(A),f.set(A,v.entityId),m.push(v)},y=[];for(let v of u)l.has(v.currentKey)&&!d.has(v.currentKey)?g({...v,status:"active",lastSeen:r},v.currentKey):y.push(v);let b=[],h=[];for(let v of y){let A=he(v.currentKey),M=A?i.get(A.path):void 0;if(A&&M){let K=ye(A.level,e,M.finalPath);if(l.has(K)&&!d.has(K)){b.push({entity:v,newKey:K,untilCommit:M.commit}),d.add(K);continue}}h.push(v)}let $=[];if(s){let v=new Map;for(let M of c){if(d.has(M))continue;let K=he(M);if(K?.level!=="code")continue;let P=a.get(K.path);P&&v.set(P,v.has(P)?null:M)}let A=new Map;for(let M of h){let K=he(M.currentKey);if(K?.level!=="code")continue;let P=s.get(K.path);P&&A.set(P,A.has(P)?null:M)}for(let M of h){let K=he(M.currentKey),P=K?.level==="code"?s.get(K.path):void 0,w=P?v.get(P):void 0;P&&w&&A.get(P)===M&&!d.has(w)?(b.push({entity:M,newKey:w,untilCommit:r}),d.add(w)):$.push(M)}}else $.push(...h);let S=new Map;for(let v of b){let A=he(v.entity.currentKey),M=he(v.newKey);if(A?.level!=="code"||!M)continue;let K=A.path,P=M.path;for(let w=K.lastIndexOf("/");w>0;w=K.lastIndexOf("/",w-1)){let I=K.slice(0,w),T=K.slice(w+1);if(!P.endsWith(`/${T}`))continue;let R=P.slice(0,P.length-T.length-1);if(R===I)continue;let N=`${I}\0${R}`,j=S.get(N);S.set(N,{count:(j?.count??0)+1,commit:j&&j.commit>v.untilCommit?j.commit:v.untilCommit})}}let D=[...S.entries()].filter(([,v])=>v.count>=uS).map(([v,A])=>{let[M,K]=v.split("\0");return{from:M,to:K,commit:A.commit}}).sort((v,A)=>A.from.length-v.from.length||(v.from<A.from?-1:1)),E=[];for(let v of $){let A=he(v.currentKey),M=!1;if(A?.level==="component")for(let K of D){let P=null;if(A.path===K.from?P=K.to:A.path.startsWith(`${K.from}/`)&&(P=K.to+A.path.slice(K.from.length)),P===null)continue;let w=ye("component",e,P);l.has(w)&&!d.has(w)&&(b.push({entity:v,newKey:w,untilCommit:K.commit}),d.add(w),M=!0);break}M||E.push(v)}for(let v of b.sort((A,M)=>A.newKey<M.newKey?-1:1))g({...v.entity,currentKey:v.newKey,aliases:[...v.entity.aliases??[],{key:v.entity.currentKey,until:v.untilCommit}],status:"active",lastSeen:r},v.newKey);for(let v of E)m.push({...v,status:"orphaned"});for(let v of c){if(d.has(v))continue;let A=dS(e,v,r,p);p.add(A),g({entityId:A,currentKey:v,firstSeen:n,lastSeen:r,status:"active"},v)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:m},byKey:f}}var uS,pg=k(()=>{"use strict";W();uS=5});import{simpleGit as pS}from"simple-git";async function mg(t,e,r){let n=pS(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
774
- `).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 fg(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 gg=k(()=>{"use strict"});function wi(t){return ye("container",t,mS)}function hg(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function yg(t,e,r,n){let o=[],i=u=>{let p=ye("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:hg(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,fS)}},s=(u,p)=>{let d=ye("component",t,u),m=n.get(d);return{key:d,level:"component",label:hg(u),...m?{entityId:m}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let m=r.filesByDir.get(d)??[],f=r.childDirs.get(d)??[],g=[p,...m.map(i)],y=[...m.map(b=>({kind:"contains",from:p.key,to:ye("code",t,b.path)})),...f.map(b=>({kind:"contains",from:p.key,to:ye("component",t,b)}))];c(u,g,y)},c=(u,p,d)=>{let m={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},f=yc(m);if(!f.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${f.errors.join("; ")}`);o.push({path:gc(t,u),content:xc(m)})},l={key:wi(t),level:"container",label:t,...n.get(wi(t))?{entityId:n.get(wi(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 wg(t,e){let r=[wi(t)];for(let n of e.components)r.push(ye("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(ye("code",t,o.path));return r.sort()}var mS,fS,bg=k(()=>{"use strict";W();mS=".";fS=12});import{simpleGit as $g}from"simple-git";function Wn(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 xg(t,e="HEAD"){let r=$g(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 Ea(t,n)}}async function Ea(t,e){let n=await $g(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 kg(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function Sg(t,e){let r=[...t].sort((f,g)=>f.path<g.path?-1:f.path>g.path?1:0),n=new Map,o=new Map;for(let f of r){let g=kg(f.path);n.has(g)||n.set(g,[]),n.get(g).push(f);let y=g;for(;y!=="";){let b=kg(y);o.has(b)||o.set(b,new Set),o.get(b).add(y),y=b}}let i=f=>[...o.get(f)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let f=l.shift(),g=(n.get(f)??[]).length+i(f).length;if(g<=s)s-=g,c.add(f),l.push(...i(f));else{if(f==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(f)}}let u=[],p=new Map,d=new Map,m=0;for(let f of[...c].sort()){let g=n.get(f)??[];p.set(f,g),d.set(f,i(f)),m+=g.length,f!==""&&u.push(f)}for(let f of a)u.push(f);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:m}}}var vg,Pa=k(()=>{"use strict";vg=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as Rg,readFileSync as Tg}from"node:fs";import{join as Cg}from"node:path";import{simpleGit as gS}from"simple-git";import{parse as Ig}from"yaml";function Aa(t){let e={ignore:vg,containerNodeCap:hS,cochange:{...dt},issueKeyPattern:null},r=Cg(t,"regimen.yaml");if(!Rg(r))return e;let n;try{n=Ig(Tg(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}}function yS(t,e){let r=Cg(t,no(e));if(!Rg(r))return null;let n=Ig(Tg(r,"utf-8")),o=wc(n);if(!o.ok)throw new Error(`model: ${no(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Eg(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await xg(r),s=Wn(o.ignore),a=i.files.filter(h=>!s(h.path)),c=Sg(a,o.containerNodeCap),l=yS(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await gS(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=fg(await mg(r,l.builtFromCommit,i.commit)),p=new Map((await Ea(r,l.builtFromCommit)).map(S=>[S.path,S.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])),m=dg({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:wg(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),f=yg(e,i.commit,c,m.byKey),g=Wn([...o.ignore,...hi]),y=ug({repo:e,headTimeSec:i.commitTimeSec,filesets:await lg(r,i.commit,o.cochange.windowCommits),pathToCurrent:yi(m.table),currentPaths:new Set(a.map(h=>h.path)),ignored:g,settings:o.cochange}),b=[{path:no(e),content:Sc(m.table)},...f.files.map(h=>({path:h.path,content:h.content})),{path:fc(e),content:hc({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:y})}];return{repo:e,headCommit:i.commit,files:b,emittedShardPaths:new Set(f.files.map(h=>h.path)),counts:{...f.counts,correlates:y.length},identityTable:m.table,entityByKey:m.byKey}}var hS,Pg=k(()=>{"use strict";W();Ia();pg();gg();bg();Pa();hS=1500});import{existsSync as ja,readFileSync as _a}from"node:fs";import{join as Na}from"node:path";import{simpleGit as jg}from"simple-git";import{parse as Oa}from"yaml";function Ng(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(wS.source,"g")}function Og(t){let e=Na(t,"project.yaml");if(ja(e))try{let o=Oa(_a(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=Na(t,"tracker","config.yaml");if(ja(r))try{let o=Oa(_a(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function Dg(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 bS(t,e,r){let o=await jg(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
775
- `))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=Da.exec(u)??_g.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:Dg(c[3]),churn:l+u})}return i}async function kS(t,e){let n=await jg(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
776
- `)){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:Dg(s[3]),churn:a+c})}return o}function $S(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(Da,"").trim();else if(c.prNumber!==null)u=`PR-${c.prNumber}`,p=c.subject.replace(Da,"").replace(_g,"").replace(/^from\s+/,"").trim()||c.subject;else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let m=new Map;for(let y of c.files){let b=o.get(y.path)??y.path;s(b)||m.set(b,(m.get(b)??0)+y.churn)}if(m.size===0)continue;let g=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(g.title=p),g.commits.push(c.sha);for(let[y,b]of m){let h=ye("code",e,y),$=g.files.find(S=>S.key===h);if($)$.churn=($.churn??0)+b;else{let S=i.get(h);g.files.push({key:h,...S?{entityId:S}:{},churn:b})}}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 Ag(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 Lg(t){let e=await bS(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 kS(t.repoDir,r.sha))}return $S({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored})}function Mg(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?Ag(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=Ag(vS(t,i),s);if(!a){o++;continue}n.push({path:Di(i),content:Rc(a)})}return{files:n,skippedPipeline:o}}function vS(t,e){let r=Na(t,Di(e));if(!ja(r))return null;try{let n=bc(Oa(_a(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var wS,Da,_g,Ug=k(()=>{"use strict";W();wS=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Da=/\(#(\d+)\)\s*$/,_g=/^Merge pull request #(\d+)\b/});var Wg={};sc(Wg,{bootstrapWorkspaceModel:()=>Hg,modelBootstrapCommand:()=>Ba,modelBuildCommand:()=>Ua});import{existsSync as xS}from"node:fs";import{join as Bg}from"node:path";import{cancel as SS,intro as Fg,log as Ma,outro as La}from"@clack/prompts";function qn(t){SS(t),process.exit(1)}function Gg(t,e){let r=t.spec.repos.filter(o=>!e||o.name===e);r.length===0&&qn(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:Bg(t.root,o.mountAs);if(!xS(Bg(i,".git"))){Ma.warn(`${o.name}: no local clone at ${i} \u2014 skipped (run \`codepipe clone\` first)`);continue}n.push({name:o.name,dir:i})}return n.length===0&&qn("nothing to do \u2014 no repo clones found"),n}async function Kg(t,e,r){let n=[];for(let o of e)try{let i=await Eg({repo:o.name,repoDir:o.dir,contextDir:t.contextDir,settings:r});n.push(i),Ma.info(`${o.name}: ${i.counts.code} files, ${i.counts.component} components, ${i.counts.correlates} co-change edges @ ${i.headCommit.slice(0,10)}`)}catch(i){qn(`${o.name}: ${i instanceof Error?i.message:String(i)}`)}return n}async function Ua(t){Fg("codepipe model build");let e=ge();e||qn("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");let r=Aa(e.contextDir),n=await Kg(e,Gg(e,t.repo),r),o=await Ca(e.contextDir,n);o.committed?La(`model updated: ${o.filesWritten} files written, ${o.filesDeleted} stale removed`):La("model already up to date (no changes)")}async function Ba(t){Fg("codepipe model bootstrap");let e=ge();e||qn("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)"),await Hg(e,t.repo,{onLog:r=>Ma.info(r)}),La("bootstrap complete")}async function Hg(t,e,r){let n=Aa(t.contextDir),o=Gg(t,e),i=await Kg(t,o,n);await Ca(t.contextDir,i);let s=Og(t.contextDir),a=Ng(n.issueKeyPattern,s),c=Wn([...n.ignore,...hi]),l=[];for(let d of i){let m=o.find(g=>g.name===d.repo),f=await Lg({repo:d.repo,repoDir:m.dir,headCommit:d.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:a,pathToCurrent:yi(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}=Mg(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`),{events:u.length}}var Fa=k(()=>{"use strict";ot();ag();Pg();Ug();Ia();Pa();tt()});import{existsSync as Jr,mkdirSync as Yg,readFileSync as Vg,readdirSync as RS,writeFileSync as zg}from"node:fs";import{join as cr,resolve as Jg}from"node:path";import{setTimeout as Ga}from"node:timers/promises";import{cancel as TS,confirm as Xr,intro as Xg,isCancel as Wa,log as _,multiselect as CS,outro as Ka,password as Yn,select as bt,spinner as qa,text as le}from"@clack/prompts";import{simpleGit as ki}from"simple-git";function ne(t){TS(t),process.exit(1)}function $e(t){return Wa(t)&&ne("aborted"),t}function te(t){return Wa(t)&&ne("aborted"),typeof t=="string"?t:""}async function Qg(t={}){Xg("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Nf();let r=_f(e),n,o=!1;r&&Object.keys(r.answers).length>0?$e(await Xr({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(_.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Vr(e,r),o=!0):(ha(e),n=new Vr(e)):n=new Vr(e);let i=t.force===!0?null:await $a(e),s=await n.ask("target",async()=>$e(await bt({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?_.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||eh(e,t.force===!0));let c=await n.ask("hubUrl",async()=>te(await le({message:"HUB URL",placeholder:Je,initialValue:H("HUB_URL")??Je,validate:O=>O.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Qr()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>Zr(c,l)),d=null;s==="farm"&&(d=await IS(c,u));let m=a?PS(a.parsed.repoName):"",f=await n.ask("projectId",async()=>te(await le({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:O=>qt.test(O.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>te(await le({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:O=>O.trim().length>0?void 0:"required"})).trim()),y=await n.ask("automationLevel",async()=>$e(await bt({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"}))),b=s==="farm"?"auto":await n.ask("applyMode",async()=>$e(await bt({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),h=await n.ask("trackerProvider",async()=>$e(await bt({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"}))),$=h==="internal",S=null,D,E=!0;if($){let O,ae=qa();ae.start("checking task-key prefixes on your account\u2026");try{O=await Lu(c,u,{excludeProjectId:f}),ae.stop("prefixes checked")}catch{ae.stop("could not reach the HUB",1),ne("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 Ae=al(sl(g),O);D=await n.ask("trackerPrefix",async()=>te(await le({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:Ae,initialValue:Ae,validate:Ue=>{let kt=Ue.trim();if(!gr.test(kt))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(O.has(kt.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else S=await n.ask("youtrack",()=>ah()),D=await n.ask("youtrackProjectKey",async()=>te(await le({message:"YouTrack project key",placeholder:"DEV",validate:O=>O.trim().length>0?void 0:"required"})).trim()),E=await n.ask("youtrackWrites",async()=>$e(await Xr({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let v=n.get("tokens")??{},A=()=>n.set("tokens",v),M=await n.ask("repos",()=>_S(v,l,a,{onCred:A,initial:n.get("reposPartial")??[],onProgress:O=>n.set("reposPartial",O)}));n.delete("reposPartial");let K=await NS(await n.ask("contextRepo",()=>oh(f,M,v,l)),f,M,v,l,A,O=>n.set("contextRepo",O)),{spec:P,mode:w}=K,I;$||(_.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),I=await n.ask("assigneeLogin",async()=>te(await le({message:"your YouTrack login (the assignee value)",...S?.login?{initialValue:S.login}:{},validate:O=>O.trim().length>0?void 0:"required"})).trim()));let T=await n.ask("llmProvider",async()=>{for(;;){if($e(await bt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";_.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),R=T==="claude"?await n.ask("claudeToken",()=>xf(vf("claude"),{farm:s==="farm"})):"",N;if(R){let O=await Su(R);if(O){let ae=jc(O);ae&&(N=ae,_.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${ae} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let j={projectId:f,name:g,automationLevel:y,repos:M,trackerProvider:h,youtrackProjectKey:D};_.step(`${w==="attach"?"attaching to":"provisioning"} Context Repo ${P.owner}/${P.name} (${P.host})\u2026`);let x;try{x=await Yr(j,P,{...ih(v),youtrackWrites:E,...S?{trackerUrl:S.url}:{},mode:w,log:{info:O=>_.message(O),warn:O=>_.warn(O)}})}catch(O){ne(`Context Repo provisioning failed: ${O instanceof Error?O.message:String(O)}`)}j.contextRepo=x,_.success(`Context Repo ready: ${x.owner}/${x.name}@${x.branch}`),_.step(`registering project on ${c}\u2026`);let C;try{C=await At(c,u,j)}catch(O){if(O instanceof U&&O.status===409){_.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{C=await Q(c,u,f)}catch(ae){throw ae instanceof U&&ne(`HUB \u2192 ${ae.status} ${ae.message}`),ae}}else if(O instanceof U&&O.status===401)n.delete("cliToken"),ne("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(O instanceof U)ne(`HUB \u2192 ${O.status} ${O.message}`);else throw O}let L=C.contextRepo??x;_.success(`project ${C.projectId} ready (${C.provisioningStatus})`);let z=await US(L),ze=S?{url:S.url,token:S.token}:void 0;if(s==="farm"){let O=d,ae={...v,...z?{contextWrite:z}:{},...R?{claude:{oauthToken:R}}:{},...ze?{youtrack:ze}:{}},Ae=v.github?.token;if(L.host==="github"&&Ae)try{let Z=em(`devpipe-${f}`);await tm(L,Ae,Z.publicKey,`devpipe-${f}`),ae.contextSsh={privateKey:Z.privateKey},_.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(Z){_.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 Ue={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:ae,contextRepo:L,projectConfig:it(j,E,S?.url,I||void 0,"auto",T,N)},kt=gt(O.farm.publicKey,JSON.stringify(Ue));_.step(`handing project ${f} to farm ${O.farm.name}\u2026`);let Y;try{Y=await Ro(c,u,O.farm.farmId,{projectId:f,sealedBundle:kt})}catch(Z){throw Z instanceof U&&ne(Z.status===409?`farm ${O.farm.name} is offline \u2014 start it and re-run.`:Z.status===504?`farm ${O.farm.name} did not respond in time.`:`HUB \u2192 ${Z.status} ${Z.message}`),Z}Y.ok||ne(`farm rejected provisioning: ${Y.error??"unknown error"}`),await Ha(c,u,f,L,Ae,C.repos,null,v),n.clear(),Ka(`done. project ${f} is now hosted on farm ${O.farm.name} (daemon ${Y.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}sh(v),await th(e,L.cloneUrl,L.branch),nh(e),a&&await jS(e);{let O=cr(e,et);Tr(O);let ae=it(j,E,S?.url,I||void 0,b,T,N),Ae=xn(O,ae);Ae.length>0&&_.success(`local project config \u2192 .codepipe/{${Ae.join(", ")}}`),or(f,ae,{info:Ue=>_.message(Ue),warn:Ue=>_.warn(Ue)})}await rh(e,C.repos);let Si={hubUrl:c,cliToken:u,projectId:f,...v,...z?{contextWrite:z}:{},...R?{claude:{oauthToken:R}}:{},...ze?{youtrack:ze}:{}};X(Si),mt({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),_.success(`secrets \u2192 ${rt(f)}`),await Ha(c,u,f,L,v.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,C.repos,e,v),n.clear();let Qn=`${c}/?project=${encodeURIComponent(f)}`;Xt(Qn),Ka(`done. your project on the dashboard (sign in there to work with it):
777
- ${Qn}
778
- 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:Ri}=await Promise.resolve().then(()=>(Ta(),ng));await Ri({})}async function Ha(t,e,r,n,o,i=[],s=null,a={}){let c=await Lf(n,o),l=!1;if(!c)try{l=await Bf(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Df({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await CS({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(Wa(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let m=ge(s);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(Fa(),Wg)),g=await f(m,void 0,{onLog:y=>_.message(y)});_.success(`project map ready: ${g.events} task events mined from history`)}catch(m){_.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 yn(t,e,r,{reindex:!1,backfill:!0});_.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){_.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 yn(t,e,r,{reindex:u.reindex});_.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){_.warn(`could not start indexing: ${m instanceof Error?m.message:String(m)}. You can retry later \u2014 registration is not affected.`)}}async function IS(t,e){let r;try{r=await _u(t,e)}catch(c){throw c instanceof U&&ne(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&ne("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=$e(await bt({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=Xo(i.farmId,i.publicKey)}catch(c){ne(c instanceof Error?c.message:String(c))}return $e(await Xr({message:`confirm farm ${i.name} cred-channel fingerprint:
778
+ `)}catch{}}var _i,Qg,ih,Zg,Xa,Za=$(()=>{"use strict";Ca();we();Mo();oe();it();Ai();qa();js();_i=oh(xS(),".codepipe","history"),Qg=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],ih=500,Zg=40;Xa=!1});import{existsSync as ah,readFileSync as qS,readdirSync as VS}from"node:fs";import{join as ch}from"node:path";import{simpleGit as zS}from"simple-git";import{parse as JS}from"yaml";function XS(t){let e=new Map,r=ch(t,zi);if(!ah(r))return e;let n;try{n=JS(qS(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 QS(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return $r({modelFormatVersion:2,repos:e})}function lh(t,e){let r=ch(t,e);if(!ah(r))return[];let n=[];for(let o of VS(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...lh(t,i)):n.push(i)}return n}async function ec(t,e,r={}){let n=[],o=0;for(let p of e){n.push(...p.files);let d=`model/derived/structure/${p.repo}`;for(let m of lh(t,d))p.emittedShardPaths.has(m)||(n.push({path:m,content:"",deleted:!0}),o++)}let i=XS(t);for(let p of e)i.set(p.repo,{builtFromCommit:p.headCommit,counts:p.counts});n.push({path:zi,content:QS(i)});let s=mm(ai(t),r.halfLifeDays??He.halfLifeDays);n.push({path:wr,content:ci(s)});let a=zS(t),c=(await a.revparse(["HEAD"]).catch(()=>"")).trim(),l=`model: build ${e.map(p=>`${p.repo}@${p.headCommit.slice(0,10)}`).join(", ")}`;return await ke(t,n,l),{committed:(await a.revparse(["HEAD"]).catch(()=>"")).trim()!==c,filesWritten:n.filter(p=>!p.deleted).length,filesDeleted:o}}var uh=$(()=>{"use strict";W();pa();Je()});var hh={};Wi(hh,{bootstrapWorkspaceModel:()=>gh,modelBootstrapCommand:()=>oc,modelBuildCommand:()=>nc});import{existsSync as ZS}from"node:fs";import{join as dh}from"node:path";import{cancel as eT,intro as ph,log as rc,outro as tc}from"@clack/prompts";function to(t){eT(t),process.exit(1)}function mh(t,e){let r=t.spec.repos.filter(o=>!e||o.name===e);r.length===0&&to(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:dh(t.root,o.mountAs);if(!ZS(dh(i,".git"))){rc.warn(`${o.name}: no local clone at ${i} \u2014 skipped (run \`codepipe clone\` first)`);continue}n.push({name:o.name,dir:i})}return n.length===0&&to("nothing to do \u2014 no repo clones found"),n}async function fh(t,e,r){let n=[];for(let o of e)try{let i=await am({repo:o.name,repoDir:o.dir,contextDir:t.contextDir,settings:r});n.push(i),rc.info(`${o.name}: ${i.counts.code} files, ${i.counts.component} components, ${i.counts.correlates} co-change edges @ ${i.headCommit.slice(0,10)}`)}catch(i){to(`${o.name}: ${i instanceof Error?i.message:String(i)}`)}return n}async function nc(t){ph("codepipe model build");let e=ye();e||to("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");let r=Fn(e.contextDir),n=await fh(e,mh(e,t.repo),r),o=await ec(e.contextDir,n,{halfLifeDays:r.cochange.halfLifeDays});o.committed?tc(`model updated: ${o.filesWritten} files written, ${o.filesDeleted} stale removed`):tc("model already up to date (no changes)")}async function oc(t){ph("codepipe model bootstrap");let e=ye();e||to("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)"),await gh(e,t.repo,{onLog:r=>rc.info(r)}),tc("bootstrap complete")}async function gh(t,e,r){let n=Fn(t.contextDir),o=mh(t,e),i=await fh(t,o,n),s=Dp(t.contextDir),a=Op(n.issueKeyPattern,s),c=cr([...n.ignore,...Ur]),l=[];for(let d of i){let m=o.find(g=>g.name===d.repo),f=await Mp({repo:d.repo,repoDir:m.dir,headCommit:d.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:a,pathToCurrent:ni(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}=Up(t.contextDir,l);return p>0&&r.onLog(`${p} events already recorded by the live pipeline \u2014 left untouched`),u.length>0&&await ke(t.contextDir,u,`model: bootstrap ${u.length} task events from history`),await ec(t.contextDir,i,{halfLifeDays:n.cochange.halfLifeDays}),{events:u.length}}var ic=$(()=>{"use strict";Je();uh();ua();aa();oi();si();it()});import{existsSync as an,mkdirSync as wh,readFileSync as kh,readdirSync as tT,writeFileSync as bh}from"node:fs";import{join as dr,resolve as $h}from"node:path";import{setTimeout as sc}from"node:timers/promises";import{cancel as rT,confirm as cn,intro as vh,isCancel as lc,log as _,multiselect as nT,outro as ac,password as ro,select as $t,spinner as uc,text as ue}from"@clack/prompts";import{simpleGit as Oi}from"simple-git";function ne(t){rT(t),process.exit(1)}function xe(t){return lc(t)&&ne("aborted"),t}function te(t){return lc(t)&&ne("aborted"),typeof t=="string"?t:""}async function xh(t={}){vh("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Lg();let r=Dg(e),n,o=!1;r&&Object.keys(r.answers).length>0?xe(await cn({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(_.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new on(e,r),o=!0):(Ka(e),n=new on(e)):n=new on(e);let i=t.force===!0?null:await Va(e),s=await n.ask("target",async()=>xe(await $t({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?_.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||Th(e,t.force===!0));let c=await n.ask("hubUrl",async()=>te(await ue({message:"HUB URL",placeholder:Ze,initialValue:H("HUB_URL")??Ze,validate:O=>O.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>ln()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>un(c,l)),d=null;s==="farm"&&(d=await oT(c,u));let m=a?sT(a.parsed.repoName):"",f=await n.ask("projectId",async()=>te(await ue({message:"project id (slug)",placeholder:m||"acme",...m?{initialValue:m}:{},validate:O=>qt.test(O.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await n.ask("projectName",async()=>te(await ue({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:O=>O.trim().length>0?void 0:"required"})).trim()),y=await n.ask("automationLevel",async()=>xe(await $t({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),k=s==="farm"?"auto":await n.ask("applyMode",async()=>xe(await $t({message:"how do approved changes reach your repo?",options:[{value:"auto",label:"auto \u2014 CodePipe pushes the branch and opens a PR"},{value:"local",label:"local \u2014 changes wait; you pull them into your checkout via the CLI REPL (/apply or /unstash), no push/PR"}],initialValue:"auto"}))),h=await n.ask("trackerProvider",async()=>xe(await $t({message:"task tracker",options:[{value:"internal",label:"built-in \u2014 CodePipe tracks tasks itself (no external tracker needed)"},{value:"youtrack",label:"YouTrack \u2014 connect an existing YouTrack project"}],initialValue:"internal"}))),b=h==="internal",S=null,D,I=!0;if(b){let O,ae=uc();ae.start("checking task-key prefixes on your account\u2026");try{O=await ed(c,u,{excludeProjectId:f}),ae.stop("prefixes checked")}catch{ae.stop("could not reach the HUB",1),ne("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 _e=Sl(xl(g),O);D=await n.ask("trackerPrefix",async()=>te(await ue({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:_e,initialValue:_e,validate:Fe=>{let vt=Fe.trim();if(!xr.test(vt))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if(O.has(vt.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else S=await n.ask("youtrack",()=>jh()),D=await n.ask("youtrackProjectKey",async()=>te(await ue({message:"YouTrack project key",placeholder:"DEV",validate:O=>O.trim().length>0?void 0:"required"})).trim()),I=await n.ask("youtrackWrites",async()=>xe(await cn({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let v=n.get("tokens")??{},A=()=>n.set("tokens",v),M=await n.ask("repos",()=>lT(v,l,a,{onCred:A,initial:n.get("reposPartial")??[],onProgress:O=>n.set("reposPartial",O)}));n.delete("reposPartial");let K=await uT(await n.ask("contextRepo",()=>Ih(f,M,v,l)),f,M,v,l,A,O=>n.set("contextRepo",O)),{spec:P,mode:w}=K,E;b||(_.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),E=await n.ask("assigneeLogin",async()=>te(await ue({message:"your YouTrack login (the assignee value)",...S?.login?{initialValue:S.login}:{},validate:O=>O.trim().length>0?void 0:"required"})).trim()));let R=await n.ask("llmProvider",async()=>{for(;;){if(xe(await $t({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";_.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),T=R==="claude"?await n.ask("claudeToken",()=>Rg(Tg("claude"),{farm:s==="farm"})):"",N;if(T){let O=await Fu(T);if(O){let ae=zc(O);ae&&(N=ae,_.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${ae} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let j={projectId:f,name:g,automationLevel:y,repos:M,trackerProvider:h,youtrackProjectKey:D};_.step(`${w==="attach"?"attaching to":"provisioning"} Context Repo ${P.owner}/${P.name} (${P.host})\u2026`);let x;try{x=await nn(j,P,{...Ph(v),youtrackWrites:I,...S?{trackerUrl:S.url}:{},mode:w,log:{info:O=>_.message(O),warn:O=>_.warn(O)}})}catch(O){ne(`Context Repo provisioning failed: ${O instanceof Error?O.message:String(O)}`)}j.contextRepo=x,_.success(`Context Repo ready: ${x.owner}/${x.name}@${x.branch}`),_.step(`registering project on ${c}\u2026`);let C;try{C=await jt(c,u,j)}catch(O){if(O instanceof U&&O.status===409){_.warn(`project ${f} already exists on HUB \u2014 reusing it`);try{C=await Q(c,u,f)}catch(ae){throw ae instanceof U&&ne(`HUB \u2192 ${ae.status} ${ae.message}`),ae}}else if(O instanceof U&&O.status===401)n.delete("cliToken"),ne("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(O instanceof U)ne(`HUB \u2192 ${O.status} ${O.message}`);else throw O}let L=C.contextRepo??x;_.success(`project ${C.projectId} ready (${C.provisioningStatus})`);let q=await gT(L),Te=S?{url:S.url,token:S.token}:void 0;if(s==="farm"){let O=d,ae={...v,...q?{contextWrite:q}:{},...T?{claude:{oauthToken:T}}:{},...Te?{youtrack:Te}:{}},_e=v.github?.token;if(L.host==="github"&&_e)try{let Z=nf(`devpipe-${f}`);await of(L,_e,Z.publicKey,`devpipe-${f}`),ae.contextSsh={privateKey:Z.privateKey},_.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(Z){_.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 Fe={projectId:f,config:{hubUrl:c,cliToken:u,projectId:f},secrets:ae,contextRepo:L,projectConfig:ct(j,I,S?.url,E||void 0,"auto",R,N)},vt=wt(O.farm.publicKey,JSON.stringify(Fe));_.step(`handing project ${f} to farm ${O.farm.name}\u2026`);let V;try{V=await Do(c,u,O.farm.farmId,{projectId:f,sealedBundle:vt})}catch(Z){throw Z instanceof U&&ne(Z.status===409?`farm ${O.farm.name} is offline \u2014 start it and re-run.`:Z.status===504?`farm ${O.farm.name} did not respond in time.`:`HUB \u2192 ${Z.status} ${Z.message}`),Z}V.ok||ne(`farm rejected provisioning: ${V.error??"unknown error"}`),await cc(c,u,f,L,_e,C.repos,null,v),n.clear(),ac(`done. project ${f} is now hosted on farm ${O.farm.name} (daemon ${V.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}Ah(v),await Rh(e,L.cloneUrl,L.branch),Eh(e),a&&await cT(e);{let O=dr(e,ot);Nr(O);let ae=ct(j,I,S?.url,E||void 0,k,R,N),_e=_n(O,ae);_e.length>0&&_.success(`local project config \u2192 .codepipe/{${_e.join(", ")}}`),sr(f,ae,{info:Fe=>_.message(Fe),warn:Fe=>_.warn(Fe)})}await Ch(e,C.repos);let fr={hubUrl:c,cliToken:u,projectId:f,...v,...q?{contextWrite:q}:{},...T?{claude:{oauthToken:T}}:{},...Te?{youtrack:Te}:{}};X(fr),ht({hubUrl:c,cliToken:u,projectId:f,accountEmail:p},f),_.success(`secrets \u2192 ${st(f)}`),await cc(c,u,f,L,v.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,C.repos,e,v),n.clear();let gr=`${c}/?project=${encodeURIComponent(f)}`;Qt(gr),ac(`done. your project on the dashboard (sign in there to work with it):
779
+ ${gr}
780
+ 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:dt}=await Promise.resolve().then(()=>(Za(),sh));await dt({})}async function cc(t,e,r,n,o,i=[],s=null,a={}){let c=await Bg(n,o),l=!1;if(!c)try{l=await Kg(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Ug({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await nT({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(lc(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let m=ye(s);if(!m)throw new Error("workspace not found");let{bootstrapWorkspaceModel:f}=await Promise.resolve().then(()=>(ic(),hh)),g=await f(m,void 0,{onLog:y=>_.message(y)});_.success(`project map ready: ${g.events} task events mined from history`)}catch(m){_.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 En(t,e,r,{reindex:!1,backfill:!0});_.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){_.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 En(t,e,r,{reindex:u.reindex});_.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){_.warn(`could not start indexing: ${m instanceof Error?m.message:String(m)}. You can retry later \u2014 registration is not affected.`)}}async function oT(t,e){let r;try{r=await Ju(t,e)}catch(c){throw c instanceof U&&ne(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&ne("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=xe(await $t({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=gi(i.farmId,i.publicKey)}catch(c){ne(c instanceof Error?c.message:String(c))}return xe(await cn({message:`confirm farm ${i.name} cred-channel fingerprint:
779
781
  ${s}
780
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||ne("farm fingerprint not confirmed \u2014 aborting."),Jo(i.farmId,s),{farm:i,fingerprint:s}}async function Zg(t){Xg(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();eh(e,t.force===!0);let r=te(await le({message:"HUB URL",initialValue:H("HUB_URL")??Je,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Qr(),{cliToken:o,accountEmail:i}=await Zr(r,n);_.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await Q(r,o,t.projectId)}catch(d){throw d instanceof U&&ne(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||ne(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await ah(),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 bi(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}sh(l),await th(e,s.contextRepo.cloneUrl,s.contextRepo.branch),nh(e);{let d=cr(e,et);Tr(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=it(m,!0,c?.url,void 0,"auto",s.llmProvider??Ze),g=xn(d,f);g.length>0&&_.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),or(t.projectId,f,{info:y=>_.message(y),warn:y=>_.warn(y)})}await rh(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};X(p),mt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),_.success(`secrets \u2192 ${rt(t.projectId)}`),await Ha(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),Ka("done.")}function eh(t,e){if(!Jr(t)){Yg(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=RS(t).filter(o=>!r.has(o));n.length!==0&&(e||ne(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function $a(t){if(!Jr(cr(t,".git")))return null;try{let r=(await ki(t).remote(["get-url","origin"])||"").toString().trim(),n=r?Me(r):null;return n?{parsed:n,defaultBranch:await ES(t)}:null}catch{return null}}async function ES(t){let e=ki(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 PS(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return qt.test(e)?e:""}function AS(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function jS(t){let e=cr(t,".gitignore"),r=Jr(e)?Vg(e,"utf-8"):"";if(AS(r))return;if(!$e(await Xr({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){_.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
782
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||ne("farm fingerprint not confirmed \u2014 aborting."),fi(i.farmId,s),{farm:i,fingerprint:s}}async function Sh(t){vh(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Th(e,t.force===!0);let r=te(await ue({message:"HUB URL",initialValue:H("HUB_URL")??Ze,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await ln(),{cliToken:o,accountEmail:i}=await un(r,n);_.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await Q(r,o,t.projectId)}catch(d){throw d instanceof U&&ne(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||ne(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await jh(),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 Ni(d,l,m?.owner??s.contextRepo.owner,n,m?.repoName)}Ah(l),await Rh(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Eh(e);{let d=dr(e,ot);Nr(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=ct(m,!0,c?.url,void 0,"auto",s.llmProvider??nt),g=_n(d,f);g.length>0&&_.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),sr(t.projectId,f,{info:y=>_.message(y),warn:y=>_.warn(y)})}await Ch(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};X(p),ht({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),_.success(`secrets \u2192 ${st(t.projectId)}`),await cc(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),ac("done.")}function Th(t,e){if(!an(t)){wh(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=tT(t).filter(o=>!r.has(o));n.length!==0&&(e||ne(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Va(t){if(!an(dr(t,".git")))return null;try{let r=(await Oi(t).remote(["get-url","origin"])||"").toString().trim(),n=r?Be(r):null;return n?{parsed:n,defaultBranch:await iT(t)}:null}catch{return null}}async function iT(t){let e=Oi(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 sT(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return qt.test(e)?e:""}function aT(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function cT(t){let e=dr(t,".gitignore"),r=an(e)?kh(e,"utf-8"):"";if(aT(r))return;if(!xe(await cn({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){_.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
781
783
  `)?"":`
782
- `;zg(e,r+o+`
784
+ `;bh(e,r+o+`
783
785
  # codepipe workspace (added by \`codepipe init\`)
784
786
  .codepipe/
785
- `),_.success(`.codepipe/ added to ${Jg(e)}`)}async function Qr(){let t="";try{t=(await ki().raw(["config","--global","user.email"])||"").trim()}catch{}return te(await le({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Zr(t,e){_.step(`connecting account ${e}`);let r;try{r=await Mu(t,e)}catch(s){throw s instanceof hn&&ne(`${e} is not authorized on this HUB yet.
787
+ `),_.success(`.codepipe/ added to ${$h(e)}`)}async function ln(){let t="";try{t=(await Oi().raw(["config","--global","user.email"])||"").trim()}catch{}return te(await ue({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function un(t,e){_.step(`connecting account ${e}`);let r;try{r=await td(t,e)}catch(s){throw s instanceof Cn&&ne(`${e} is not authorized on this HUB yet.
786
788
  Sign up at ${t} (registration form on the login screen),
787
789
  wait for the operator to approve it by email, then re-run
788
- \`codepipe init\` with the same email.`),s}r.accountCreated&&_.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&_.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Xt(r.authorizeUrl),_.message(`a browser tab was opened to confirm this CLI:
790
+ \`codepipe init\` with the same email.`),s}r.accountCreated&&_.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&_.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Qt(r.authorizeUrl),_.message(`a browser tab was opened to confirm this CLI:
789
791
  ${r.authorizeUrl}
790
792
  `+(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
791
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&_.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),_.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 Uu(t,r.requestId)}catch(a){_.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Ga(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&_.message(`connected as ${a} (the account confirmed in the browser).`),_.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&ne("the HUB rejected this account"),s.status==="expired"&&ne("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,_.message(`email confirmed. waiting for the operator to approve your account\u2026
792
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Ga(5e3);continue}await Ga(2e3)}ne("bootstrap timed out")}async function th(t,e,r){let n=cr(t,et);if(Jr(cr(n,".git"))){_.message(`${n} already cloned \u2014 skipping`);return}Jr(n)&&ne(`${n} exists but is not a git repo \u2014 remove it and re-run`),Yg(n,{recursive:!0}),_.step(`cloning Context Repo \u2192 ${n}`);try{await ki().clone(e,n,["--branch",r]),_.success(`cloned ${e}`)}catch(o){ne(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function rh(t,e){if(e.length===0)return;_.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 Gn(t,r,{log:{info:o=>_.message(o),warn:o=>_.warn(o)}});for(let o of n)_.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function nh(t){let e=cr(t,et,".gitignore"),r="";if(Jr(e)&&(r=Vg(e,"utf-8")),qg.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
793
+ otherwise use the emailed link the page offers.`))),r.approvalRequired&&_.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),_.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 rd(t,r.requestId)}catch(a){_.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await sc(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&_.message(`connected as ${a} (the account confirmed in the browser).`),_.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&ne("the HUB rejected this account"),s.status==="expired"&&ne("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,_.message(`email confirmed. waiting for the operator to approve your account\u2026
794
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await sc(5e3);continue}await sc(2e3)}ne("bootstrap timed out")}async function Rh(t,e,r){let n=dr(t,ot);if(an(dr(n,".git"))){_.message(`${n} already cloned \u2014 skipping`);return}an(n)&&ne(`${n} exists but is not a git repo \u2014 remove it and re-run`),wh(n,{recursive:!0}),_.step(`cloning Context Repo \u2192 ${n}`);try{await Oi().clone(e,n,["--branch",r]),_.success(`cloned ${e}`)}catch(o){ne(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function Ch(t,e){if(e.length===0)return;_.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 Qn(t,r,{log:{info:o=>_.message(o),warn:o=>_.warn(o)}});for(let o of n)_.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function Eh(t){let e=dr(t,ot,".gitignore"),r="";if(an(e)&&(r=kh(e,"utf-8")),yh.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
793
795
  `)||r.length===0?"":`
794
- `,i=qg.join(`
796
+ `,i=yh.join(`
795
797
  `)+`
796
- `;zg(e,r+o+(r?`
797
- `:"")+i),_.message(`appended runtime entries to ${Jg(e)}`)}async function _S(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;_.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await bi(s.host,t,s.owner,e,s.repoName),i?.();let c=te(await le({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=te(await le({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(;$e(await Xr({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=te(await le({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||Me(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=Me(a);_.message(`${c.host}: ${c.owner}/${c.repoName}`),await bi(c.host,t,c.owner,e,c.repoName),i?.();let l=te(await le({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=te(await le({message:"default branch (optional)",placeholder:"main"})).trim(),p=te(await le({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 oh(t,e,r,n){_.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=$e(await bt({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"&&_.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=te(await le({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:pt(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!Me(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=Me(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await OS(),l=te(await le({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=te(await le({message:"Context Repo name",placeholder:pt(t),initialValue:pt(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function ih(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??br()}}async function NS(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await bi(c.host,n,c.owner,o),i?.();let u=qa();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await Rf(c,ih(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=$e(await bt({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"&&ne("aborted"),d==="create")return a={spec:c,mode:"create"},s(a),a;a=await oh(e,r,n,o),s(a)}}async function OS(){return $e(await bt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Vn(t,e){let r=qa();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 sh(t){In(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),En(t.gitlab?.token??process.env.GITLAB_TOKEN),Pn(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function bi(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await DS(r);i?e.github=i:_.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await LS(r,n,o);i?e.bitbucket=i:_.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 MS();i?e.gitlab=i:_.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function DS(t){for(;;){let e=te(await Yn({message:`GitHub PAT \u2014 blank to skip
798
+ `;bh(e,r+o+(r?`
799
+ `:"")+i),_.message(`appended runtime entries to ${$h(e)}`)}async function lT(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;_.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Ni(s.host,t,s.owner,e,s.repoName),i?.();let c=te(await ue({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=te(await ue({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(;xe(await cn({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=te(await ue({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||Be(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=Be(a);_.message(`${c.host}: ${c.owner}/${c.repoName}`),await Ni(c.host,t,c.owner,e,c.repoName),i?.();let l=te(await ue({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=te(await ue({message:"default branch (optional)",placeholder:"main"})).trim(),p=te(await ue({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 Ih(t,e,r,n){_.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=xe(await $t({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"&&_.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=te(await ue({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:gt(t),validate:u=>{let p=(u??"").trim();if(!p)return"required";if(!Be(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=Be(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await dT(),l=te(await ue({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=te(await ue({message:"Context Repo name",placeholder:gt(t),initialValue:gt(t),validate:p=>p.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function Ph(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??Cr()}}async function uT(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Ni(c.host,n,c.owner,o),i?.();let u=uc();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let p=await Eg(c,Ph(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=xe(await $t({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"&&ne("aborted"),d==="create")return a={spec:c,mode:"create"},s(a),a;a=await Ih(e,r,n,o),s(a)}}async function dT(){return xe(await $t({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function no(t,e){let r=uc();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 Ah(t){Mn(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Un(t.gitlab?.token??process.env.GITLAB_TOKEN),Bn(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Ni(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await pT(r);i?e.github=i:_.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await mT(r,n,o);i?e.bitbucket=i:_.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 fT();i?e.gitlab=i:_.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function pT(t){for(;;){let e=te(await ro({message:`GitHub PAT \u2014 blank to skip
798
800
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
799
801
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
800
802
  if org: approve token in org Settings \u2192 Personal access tokens.
801
803
  (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
802
- set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Vn("GitHub",()=>St(e,t?{owner:t}:void 0)))return{token:e};_.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function LS(t,e,r){for(_.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
804
+ set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await no("GitHub",()=>Tt(e,t?{owner:t}:void 0)))return{token:e};_.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function mT(t,e,r){for(_.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
803
805
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
804
806
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
805
807
  read:repository:bitbucket + write:repository:bitbucket +
806
808
  read:pullrequest:bitbucket + write:pullrequest:bitbucket
807
809
  \u2014 write scopes do NOT include read: pick BOTH scopes of each pair
808
810
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
809
- The token is shown ONCE \u2014 copy it right away.`);;){let n=te(await le({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=te(await Yn({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){_.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Vn("Bitbucket",async()=>{let i=await Rt(n,o,t);if(t&&r){let s=await $o(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};_.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function MS(){for(;;){let t=te(await Yn({message:`GitLab PAT \u2014 blank to skip
810
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Vn("GitLab",()=>Tt(t))){let e=await ql(t);return e&&_.warn(e),{token:t}}_.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function US(t){if($e(await Xr({message:`Issue a separate context-write token (scoped to the Context Repo only)?
811
+ The token is shown ONCE \u2014 copy it right away.`);;){let n=te(await ue({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=te(await ro({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){_.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await no("Bitbucket",async()=>{let i=await Rt(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};_.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function fT(){for(;;){let t=te(await ro({message:`GitLab PAT \u2014 blank to skip
812
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await no("GitLab",()=>Ct(t))){let e=await lu(t);return e&&_.warn(e),{token:t}}_.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function gT(t){if(xe(await cn({message:`Issue a separate context-write token (scoped to the Context Repo only)?
811
813
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
812
814
  credential. A scoped token hardens setups where the SANDBOX runs outside
813
815
  your trusted network.`,initialValue:!1})))for(t.host==="github"?_.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
814
816
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
815
817
  required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):_.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
816
- (${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=te(await Yn({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Vn("contextWrite",()=>BS(r,t)))return{token:r};_.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function BS(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 ah(){for(;;){let t=te(await le({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=te(await Yn({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Vn("YouTrack",()=>Et({baseUrl:t,token:e}))){let r=await su({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}_.warn("re-enter the YouTrack URL / token.")}}var qg,Kn=k(()=>{"use strict";xe();W();Le();Sf();xo();Ie();ft();ir();vr();ui();ta();di();Ct();Jt();Of();we();Mf();Ff();zs();Go();oe();mi();tt();qg=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});W();xe();Ie();import{Command as bR}from"commander";co();import{homedir as vl}from"node:os";import{join as xl}from"node:path";function Sl(){Vt(xl(vl(),".devpipe"),xl(vl(),".codepipe"))}Ie();oe();async function Ll(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=Ke(e);r&&!t.force&&(console.error(`already configured at ${yr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");mt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...G(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};X(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${yr(e)}`)}Qi();Ie();ea();we();oe();ft();ra();tt();Go();import{homedir as na}from"node:os";import{join as On}from"node:path";async function lm(t={profile:void 0}){let{cfg:e,profile:r}=mo(t.profile),n=G(e.projectId);n&&fn(n),In(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),En(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Pn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=On(na(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=ho("CLI_LOG",i,o);if(s.enabled){let d=new kr(s);yo(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=uo(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=On(na(),".codepipe",r?On("profiles",r,"context"):"context");if(await hs(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await am(()=>ri({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 hs(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=On(na(),".codepipe",r?On("profiles",r,"context-config"):"context-config");No(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=ei(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(`
817
- [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}Wr();Ie();we();async function wf(t={profile:void 0}){let e=Ne(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=So(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await Q(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ke(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`)")}Kn();import{readFileSync as FS}from"node:fs";W();Ie();ft();ui();ir();Ct();Jt();we();oe();function ce(t){throw new Error(t)}function fe(t,e){return(typeof t!="string"||t.trim().length===0)&&ce(`config: '${e}' must be a non-empty string`),t.trim()}function zn(t,e){if(t==null)return;typeof t!="string"&&ce(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function GS(t){(!t||typeof t!="object")&&ce("config: expected a JSON object");let e=t,r=fe(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ce("config: 'hubUrl' must start with http(s)://");let n=fe(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&ce("config: 'project' is required");let i=o,s=fe(i.id,"project.id");qt.test(s)||ce("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=fe(i.name,"project.name"),c=fe(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ce("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ce("config: 'project.repos' must be an array");let u=l.map((h,$)=>{(!h||typeof h!="object")&&ce(`config: project.repos[${$}] must be an object`);let S=h,D=fe(S.host,`project.repos[${$}].host`);D!=="github"&&D!=="bitbucket"&&D!=="gitlab"&&ce(`config: project.repos[${$}].host must be 'github', 'bitbucket' or 'gitlab'`);let E={name:fe(S.name,`project.repos[${$}].name`),host:D,owner:fe(S.owner,`project.repos[${$}].owner`),repoName:fe(S.repoName,`project.repos[${$}].repoName`)},v=zn(S.defaultBranch,`project.repos[${$}].defaultBranch`);v&&(E.defaultBranch=v);let A=zn(S.mountAs,`project.repos[${$}].mountAs`);return A&&(E.mountAs=A),E}),p=i.contextRepo;(!p||typeof p!="object")&&ce("config: 'project.contextRepo' is required");let d=p,m=zn(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&ce("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:fe(d.owner,"project.contextRepo.owner"),name:zn(d.name,"project.contextRepo.name")??pt(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},y=zn(i.youtrackProjectKey,"project.youtrackProjectKey");if(y&&(g.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&ce("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ce("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let h=fe(i.llmProvider,"project.llmProvider");h==="codex"&&ce(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),h!=="claude"&&ce("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=h}let b=e.secrets;if(b!==void 0){(typeof b!="object"||b===null)&&ce("config: 'secrets' must be an object");let h=b,$={};if(h.github){let S=h.github;$.github={token:fe(S.token,"secrets.github.token")}}if(h.bitbucket){let S=h.bitbucket;$.bitbucket={email:fe(S.email,"secrets.bitbucket.email"),apiToken:fe(S.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let S=h.gitlab;$.gitlab={token:fe(S.token,"secrets.gitlab.token")}}if(h.youtrack){let S=h.youtrack;$.youtrack={url:fe(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:fe(S.token,"secrets.youtrack.token")}}if(h.contextWrite){let S=h.contextWrite;$.contextWrite={token:fe(S.token,"secrets.contextWrite.token")}}g.secrets=$}return g}async function KS(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function HS(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await St(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 Rt(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await $o(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 Tt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Et({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function ch(t){let e=!t.configPath||t.configPath==="-"?await KS():FS(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){ce(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=GS(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 HS(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 Yr(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??br(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){ce(`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 At(o,i,a)}catch(d){if(d instanceof U&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await Q(o,i,s.id);else if(d instanceof U)ce(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(X(p),mt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${rt(s.id)}`),or(s.id,it(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??Ze),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await yn(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`)}Ie();oe();import{cancel as lh,intro as uh,isCancel as dh,log as Ya,outro as WS,password as ph}from"@clack/prompts";async function qS(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function mh(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await qS(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){uh("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ya.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await ph({message:"Claude OAuth token"});dh(i)&&(lh("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Dl({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${go()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ne(t.profile);if(!e){uh(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ya.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await ph({message:"Claude OAuth token"});dh(i)&&(lh("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=G(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},X(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Ya.success("Claude OAuth token saved."),WS("It will be sealed into job bundles when a SANDBOX (re)connects."))}Fa();W();Ie();ft();ui();ir();di();we();oe();import{cancel as YS,confirm as VS,intro as zS,isCancel as fh,log as ve,outro as JS,select as gh,text as Gt}from"@clack/prompts";function hh(t){YS(t),process.exit(1)}function en(t){return fh(t)&&hh("aborted"),t}function Jn(t){return fh(t)&&hh("aborted"),typeof t=="string"?t:""}async function XS(t,e){let r=en(await gh({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=Jn(await Gt({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=Jn(await Gt({message:"Context Repo name",placeholder:pt(t),initialValue:pt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function yh(t={profile:void 0}){let e=Ne(t.profile);zS(`codepipe project add \u2192 ${e.hubUrl}`);let r=en(await Gt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>qt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=en(await Gt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=en(await gh({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=en(await Gt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=en(await VS({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Jn(await Gt({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:b=>!b||!b.trim()||Me(b)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let m=Me(d);ve.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=Jn(await Gt({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:b=>b.trim().length>0?void 0:"required"})).trim(),g=Jn(await Gt({message:"default branch (optional)",placeholder:"main"})).trim(),y={name:f,host:m.host,owner:m.owner,repoName:m.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 XS(r,a),u=G(e.projectId);ve.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await Yr(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??br(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>ve.message(d),warn:d=>ve.warn(d)}})}catch(d){ve.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,ve.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await At(e.hubUrl,e.cliToken,c);ve.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),or(r,it(c,s,u?.youtrack?.url),{info:m=>ve.message(m),warn:m=>ve.warn(m)}),d.contextRepo&&(ve.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),ve.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&ve.error(` error: ${d.provisioningError}`),JS("done")}catch(d){d instanceof U?(ve.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&ve.message(JSON.stringify(d.payload,null,2))):ve.error(d instanceof Error?d.message:String(d)),process.exit(1)}}Wr();Ie();we();oe();tt();Kn();import{existsSync as QS,rmSync as ZS}from"node:fs";import{confirm as eR,intro as tR,isCancel as rR,log as Kt,outro as nR,spinner as oR}from"@clack/prompts";function at(t){Kt.error(t),process.exit(1)}var wh=t=>t.trim().replace(/\/+$/,"");async function bh(t){tR("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ge()?.spec.projectId??void 0;e||at("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Ke(e);r||at(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=wh(r.hubUrl),o=r.projectId,i=wh(t.hub);i.startsWith("http")||at("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&at(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let b=oR();b.start(`reading project ${o} from ${n}\u2026`);try{l=await Q(n,r.cliToken,o),b.stop(`read project ${o} (${l.name})`)}catch(h){throw b.stop("could not read the source project",1),h instanceof U&&at(`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||at(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=G(o),p=(t.account??r.accountEmail??await Qr()).trim().toLowerCase();if(Kt.message(`move project '${o}'
818
+ (${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=te(await ro({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await no("contextWrite",()=>hT(r,t)))return{token:r};_.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function hT(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/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 jh(){for(;;){let t=te(await ue({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=te(await ro({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await no("YouTrack",()=>Pt({baseUrl:t,token:e}))){let r=await xu({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}_.warn("re-enter the YouTrack URL / token.")}}var yh,Zn=$(()=>{"use strict";Re();W();Ue();Cg();No();Pe();yt();ar();Pr();Ei();Ea();Ii();Et();Xt();Mg();we();Fg();Hg();va();Zo();oe();Ai();it();yh=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});W();Re();Pe();import{Command as zT}from"commander";bo();import{homedir as Ul}from"node:os";import{join as Bl}from"node:path";function Fl(){zt(Bl(Ul(),".devpipe"),Bl(Ul(),".codepipe"))}Pe();oe();async function eu(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=Ye(e);r&&!t.force&&(console.error(`already configured at ${Tr(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");ht({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...G(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};X(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Tr(e)}`)}us();Pe();Ca();we();oe();yt();Ia();it();Zo();import{homedir as Pa}from"node:os";import{join as Wn}from"node:path";async function mf(t={profile:void 0}){let{cfg:e,profile:r}=So(t.profile),n=G(e.projectId);n&&Tn(n),Mn(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Un(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Bn(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Wn(Pa(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Co("CLI_LOG",i,o);if(s.enabled){let d=new Er(s);Eo(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=vo(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=Wn(Pa(),".codepipe",r?Wn("profiles",r,"context"):"context");if(await Es(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await df(()=>bi({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 Es(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=Wn(Pa(),".codepipe",r?Wn("profiles",r,"context-config"):"context-config");Wo(a.contextDir,m,{info:f=>console.log(f),warn:f=>console.warn(f)})}}let l=wi(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(`
819
+ [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}tn();Pe();we();async function $g(t={profile:void 0}){let e=De(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Oo(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await Q(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ve(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`)")}Zn();import{readFileSync as yT}from"node:fs";W();Pe();yt();Ei();ar();Et();Xt();we();oe();function le(t){throw new Error(t)}function he(t,e){return(typeof t!="string"||t.trim().length===0)&&le(`config: '${e}' must be a non-empty string`),t.trim()}function oo(t,e){if(t==null)return;typeof t!="string"&&le(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function wT(t){(!t||typeof t!="object")&&le("config: expected a JSON object");let e=t,r=he(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||le("config: 'hubUrl' must start with http(s)://");let n=he(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&le("config: 'project' is required");let i=o,s=he(i.id,"project.id");qt.test(s)||le("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=he(i.name,"project.name"),c=he(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&le("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||le("config: 'project.repos' must be an array");let u=l.map((h,b)=>{(!h||typeof h!="object")&&le(`config: project.repos[${b}] must be an object`);let S=h,D=he(S.host,`project.repos[${b}].host`);D!=="github"&&D!=="bitbucket"&&D!=="gitlab"&&le(`config: project.repos[${b}].host must be 'github', 'bitbucket' or 'gitlab'`);let I={name:he(S.name,`project.repos[${b}].name`),host:D,owner:he(S.owner,`project.repos[${b}].owner`),repoName:he(S.repoName,`project.repos[${b}].repoName`)},v=oo(S.defaultBranch,`project.repos[${b}].defaultBranch`);v&&(I.defaultBranch=v);let A=oo(S.mountAs,`project.repos[${b}].mountAs`);return A&&(I.mountAs=A),I}),p=i.contextRepo;(!p||typeof p!="object")&&le("config: 'project.contextRepo' is required");let d=p,m=oo(d.host,"project.contextRepo.host")??"github";m!=="github"&&m!=="bitbucket"&&m!=="gitlab"&&le("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let f={host:m,owner:he(d.owner,"project.contextRepo.owner"),name:oo(d.name,"project.contextRepo.name")??gt(s)},g={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:f}},y=oo(i.youtrackProjectKey,"project.youtrackProjectKey");if(y&&(g.project.youtrackProjectKey=y),i.index!==void 0&&(typeof i.index!="boolean"&&le("config: 'project.index' must be a boolean"),g.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&le("config: 'project.youtrackWrites' must be a boolean"),g.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let h=he(i.llmProvider,"project.llmProvider");h==="codex"&&le(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),h!=="claude"&&le("config: 'project.llmProvider' must be 'claude'"),g.project.llmProvider=h}let k=e.secrets;if(k!==void 0){(typeof k!="object"||k===null)&&le("config: 'secrets' must be an object");let h=k,b={};if(h.github){let S=h.github;b.github={token:he(S.token,"secrets.github.token")}}if(h.bitbucket){let S=h.bitbucket;b.bitbucket={email:he(S.email,"secrets.bitbucket.email"),apiToken:he(S.apiToken,"secrets.bitbucket.apiToken")}}if(h.gitlab){let S=h.gitlab;b.gitlab={token:he(S.token,"secrets.gitlab.token")}}if(h.youtrack){let S=h.youtrack;b.youtrack={url:he(S.url,"secrets.youtrack.url").replace(/\/$/,""),token:he(S.token,"secrets.youtrack.token")}}if(h.contextWrite){let S=h.contextWrite;b.contextWrite={token:he(S.token,"secrets.contextWrite.token")}}g.secrets=b}return g}async function kT(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function bT(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Tt(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 Rt(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 Ct(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Pt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function _h(t){let e=!t.configPath||t.configPath==="-"?await kT():yT(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){le(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=wT(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 bT(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 nn(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Cr(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){le(`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 jt(o,i,a)}catch(d){if(d instanceof U&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await Q(o,i,s.id);else if(d instanceof U)le(`HUB \u2192 ${d.status} ${d.message}`);else throw d}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let p={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(X(p),ht({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${st(s.id)}`),sr(s.id,ct(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,"auto",s.llmProvider??nt),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await En(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}Pe();oe();import{cancel as Nh,intro as Oh,isCancel as Dh,log as dc,outro as $T,password as Lh}from"@clack/prompts";async function vT(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Mh(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await vT(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Oh("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),dc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Lh({message:"Claude OAuth token"});Dh(i)&&(Nh("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Zl({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Ro()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=De(t.profile);if(!e){Oh(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),dc.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Lh({message:"Claude OAuth token"});Dh(i)&&(Nh("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=G(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},X(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(dc.success("Claude OAuth token saved."),$T("It will be sealed into job bundles when a SANDBOX (re)connects."))}ic();W();Pe();yt();Ei();ar();Ii();we();oe();import{cancel as xT,confirm as ST,intro as TT,isCancel as Uh,log as Se,outro as RT,select as Bh,text as Kt}from"@clack/prompts";function Fh(t){xT(t),process.exit(1)}function dn(t){return Uh(t)&&Fh("aborted"),t}function io(t){return Uh(t)&&Fh("aborted"),typeof t=="string"?t:""}async function CT(t,e){let r=dn(await Bh({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=io(await Kt({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=io(await Kt({message:"Context Repo name",placeholder:gt(t),initialValue:gt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Gh(t={profile:void 0}){let e=De(t.profile);TT(`codepipe project add \u2192 ${e.hubUrl}`);let r=dn(await Kt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>qt.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=dn(await Kt({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=dn(await Bh({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=dn(await Kt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=dn(await ST({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=io(await Kt({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:k=>!k||!k.trim()||Be(k)?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=Be(d);Se.message(`${m.host}: ${m.owner}/${m.repoName}`);let f=io(await Kt({message:"repo logical name (used inside Context Repo paths)",placeholder:m.repoName,initialValue:m.repoName,validate:k=>k.trim().length>0?void 0:"required"})).trim(),g=io(await Kt({message:"default branch (optional)",placeholder:"main"})).trim(),y={name:f,host:m.host,owner:m.owner,repoName:m.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 CT(r,a),u=G(e.projectId);Se.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await nn(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??Cr(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>Se.message(d),warn:d=>Se.warn(d)}})}catch(d){Se.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,Se.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await jt(e.hubUrl,e.cliToken,c);Se.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),sr(r,ct(c,s,u?.youtrack?.url),{info:m=>Se.message(m),warn:m=>Se.warn(m)}),d.contextRepo&&(Se.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),Se.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&Se.error(` error: ${d.provisioningError}`),RT("done")}catch(d){d instanceof U?(Se.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&Se.message(JSON.stringify(d.payload,null,2))):Se.error(d instanceof Error?d.message:String(d)),process.exit(1)}}tn();Pe();we();oe();it();Zn();import{existsSync as ET,rmSync as IT}from"node:fs";import{confirm as PT,intro as AT,isCancel as jT,log as Ht,outro as _T,spinner as NT}from"@clack/prompts";function ut(t){Ht.error(t),process.exit(1)}var Kh=t=>t.trim().replace(/\/+$/,"");async function Hh(t){AT("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ye()?.spec.projectId??void 0;e||ut("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Ye(e);r||ut(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Kh(r.hubUrl),o=r.projectId,i=Kh(t.hub);i.startsWith("http")||ut("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&ut(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let k=NT();k.start(`reading project ${o} from ${n}\u2026`);try{l=await Q(n,r.cliToken,o),k.stop(`read project ${o} (${l.name})`)}catch(h){throw k.stop("could not read the source project",1),h instanceof U&&ut(`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||ut(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=G(o),p=(t.account??r.accountEmail??await ln()).trim().toLowerCase();if(Ht.message(`move project '${o}'
818
820
  from : ${n} (profile ${e})
819
821
  to : ${i} (profile ${s}, project ${a}, account ${p})
820
822
  \u2022 the source registration on the old HUB is left intact (non-destructive)
821
823
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
822
- `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let b=await eR({message:"Continue?",initialValue:!0});(rR(b)||!b)&&at("aborted")}!c&&a===o&&Kt.warn(`source and destination share the same project id, so they share one secrets file (${rt(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:m}=await Zr(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Kt.step(`registering project on ${i}\u2026`);let g;try{g=await At(i,d,f)}catch(b){if(b instanceof U&&b.status===409){Kt.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await Q(i,d,a)}catch(h){throw h instanceof U&&at(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if(b instanceof U&&b.status===403)at(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(b instanceof U)at(`target HUB \u2192 ${b.status} ${b.message}`);else throw b}Kt.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),mt({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let y={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete y.sandboxPins,X(y),Kt.success(`profile '${s}' \u2192 ${rt(a)}`),c){let b=Ye(s);QS(b)&&(ZS(b),Kt.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}nR(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Ie();Ls();di();we();xr();oe();tt();import{existsSync as Va,rmSync as iR,statSync as sR}from"node:fs";import{join as $i,relative as aR,resolve as cR}from"node:path";import{cancel as lR,intro as $h,isCancel as uR,log as ue,outro as vh,text as lr}from"@clack/prompts";import{simpleGit as xh}from"simple-git";function Pe(t){lR(t),process.exit(1)}function ur(t){return uR(t)&&Pe("aborted"),typeof t=="string"?t:""}async function kh(t){try{let e=await xh(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function dR(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function pR(t,e){let r=G(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(dR(r,e)){ue.message(`reusing existing ${e} credentials`);return}if(ue.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=ur(await lr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=ur(await lr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=ur(await lr({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}}X(r),ue.success(`saved ${e} credentials`)}async function Sh(t){let e=Ne(t.profile);$h(`codepipe repo add \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{n=(await Q(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){Pe(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await kh(process.cwd());h?(o=process.cwd(),ue.message(`using the current directory (${h})`)):o=ur(await lr({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(Va(o)&&sR(o).isDirectory()){i=cR(o);let h=await kh(i);h||Pe(`${i} is not a git repository (no origin remote)`);let $=Me(h);$||Pe(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=$,s=h,ue.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=Me(o);h||Pe(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,ue.message(`${a}: ${c}/${l}`)}let u=ur(await lr({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)&&Pe(`a repo named "${u}" is already registered`);let p=ur(await lr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=aR(r.root,i);d=h===""?".":h}let m=ur(await lr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(h=>(h.mountAs??h.name)===m)&&Pe(`mount_as "${m}" is already used by another repo`),await pR(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!i){let h=r?$i(r.root,m):Se(e.projectId,u);if(Va($i(h,".git")))ue.message(`already cloned at ${h}`);else{ue.info(`cloning ${s} \u2192 ${h} \u2026`);try{await xh().clone(s,h),ue.success(`cloned into ${h}`)}catch($){Pe(`clone failed: ${$ instanceof Error?$.message.trim():String($)}
823
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await Wu(e.hubUrl,e.cliToken,e.projectId,f)}catch(h){h instanceof U&&Pe(`HUB \u2192 ${h.status} ${h.message}`),Pe(h instanceof Error?h.message:String(h))}let{updated:y,errors:b}=Cn(e.projectId,g.repos,r?.contextDir);for(let h of y)ue.message(`updated ${h}`);for(let h of b)ue.warn(`could not update ${h.path}: ${h.error}`);ue.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),vh("done")}async function Rh(t){let e=Ne(t.profile);$h(`codepipe repo remove \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{let c=(await Q(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await qu(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof U&&(a.status===404&&Pe(`no repo named "${t.name}" in this project`),Pe(`HUB \u2192 ${a.status} ${a.message}`)),Pe(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Cn(e.projectId,o.repos,r?.contextDir);for(let a of i)ue.message(`updated ${a}`);for(let a of s)ue.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")ue.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?$i(r.root,n):Se(e.projectId,t.name);if(Va($i(a,".git")))try{iR(a,{recursive:!0,force:!0}),ue.message(`deleted local clone ${a}`)}catch(c){ue.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else ue.message(`no local clone found to purge (${a})`)}ue.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),vh("done")}async function Th(t){let e=Ne(t.profile),r;try{r=(await Q(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}mi();ka();Ta();Wr();W();xe();Wr();Ie();we();Kn();import{hostname as mR}from"node:os";import{cancel as fR,confirm as Ch,intro as gR,isCancel as Ph,log as tn,multiselect as hR,outro as Ih,password as yR,select as za,text as Ja}from"@clack/prompts";function Xn(t){fR(t),process.exit(1)}function rn(t){return Ph(t)&&Xn("aborted"),t}function vi(t){return Ph(t)&&Xn("aborted"),typeof t=="string"?t:""}function xi(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Eh(t,e){try{let{secret:r}=await To(t,e);return r}catch(r){throw r instanceof U&&r.status===404&&Xn("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 wR(t,e){if(rn(await za({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 fs(t,e);if(o.length>0)return rn(await hR({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 vi(await Ja({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 Xa(t){gR("codepipe worker \u2014 set up this machine as a runner");let e=ke(t.profile);e&&(tn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),rn(await Ch({message:"re-register this worker?",initialValue:!1}))||Xn("keeping the existing registration"));let r=Ke(t.profile)??Ke(),n=vi(await Ja({message:"HUB URL",placeholder:Je,initialValue:H("HUB_URL")??r?.hubUrl??Je,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 za({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 Eh(n,a),tn.success("account-issued registration token minted");else if(i==="login"){let d=await Qr();a=(await Zr(n,d)).cliToken,s=await Eh(n,a),tn.success("account-issued registration token minted")}else s=vi(await yR({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Xn("a registration token is required");let c=await wR(n,a),l=vi(await Ja({message:"worker name",initialValue:mR(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=rn(await za({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 sr({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 Ch({message:"start the claim-loop now?",initialValue:!0}))){Ih("registered. start later with `codepipe worker`.");return}Ih("starting the claim-loop\u2026"),await Bn(t.profile?{profile:t.profile}:{})}function kR(){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 H("PROFILE")}var se=kR();$l(se);Sl();var Ce=new bR;Ce.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(je).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{xi()?await Ra({profile:se}):await ba({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ce.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 ch({configPath:t.config,skipVerify:t.skipVerify===!0}):await Qg({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ce.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 Ll({...t,profile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ce.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 Zg({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ce.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await lm({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ce.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 qf({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ce.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 mh({profile:se,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ce.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await wf({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ce.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 ba({profile:se,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Ah=Ce.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Ah.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??H("HUB_URL")??Ke(se)?.hubUrl??Je,r=t.token??H("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&xi()){await Xa({profile:se});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=H("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??H("WORKER_NAME"),i=t.llm??H("WORKER_LLM");await sr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...se?{profile:se}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ah.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ke(se)&&xi()){await Xa({profile:se});return}await Bn(se?{profile:se}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var jh=Ce.command("project").description("Manage CodePipe projects");jh.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await yh({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});jh.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 bh({...t,cliProfile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Qa=Ce.command("repo").description("Manage the project's git repositories");Qa.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 Sh({profile:se,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Qa.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 Rh({profile:se,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Qa.command("list").description("List the project's repos").action(async()=>{try{await Th({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var _h=Ce.command("model").description("Project map (model/ in the Context Repo)");_h.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 Ua({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});_h.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 Ba({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ce.parseAsync();
824
+ `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let k=await PT({message:"Continue?",initialValue:!0});(jT(k)||!k)&&ut("aborted")}!c&&a===o&&Ht.warn(`source and destination share the same project id, so they share one secrets file (${st(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 un(i,p),f={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:m,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Ht.step(`registering project on ${i}\u2026`);let g;try{g=await jt(i,d,f)}catch(k){if(k instanceof U&&k.status===409){Ht.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{g=await Q(i,d,a)}catch(h){throw h instanceof U&&ut(`target HUB \u2192 ${h.status} ${h.message}`),h}}else if(k instanceof U&&k.status===403)ut(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(k instanceof U)ut(`target HUB \u2192 ${k.status} ${k.message}`);else throw k}Ht.success(`project ${g.projectId} ready on ${i} (${g.provisioningStatus})`),ht({hubUrl:i,cliToken:d,projectId:a,accountEmail:m},s);let y={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete y.sandboxPins,X(y),Ht.success(`profile '${s}' \u2192 ${st(a)}`),c){let k=Xe(s);ET(k)&&(IT(k),Ht.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}_T(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}Pe();zs();Ii();we();Ar();oe();it();import{existsSync as pc,rmSync as OT,statSync as DT}from"node:fs";import{join as Di,relative as LT,resolve as MT}from"node:path";import{cancel as UT,intro as Yh,isCancel as BT,log as de,outro as qh,text as pr}from"@clack/prompts";import{simpleGit as Vh}from"simple-git";function je(t){UT(t),process.exit(1)}function mr(t){return BT(t)&&je("aborted"),typeof t=="string"?t:""}async function Wh(t){try{let e=await Vh(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function FT(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function GT(t,e){let r=G(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(FT(r,e)){de.message(`reusing existing ${e} credentials`);return}if(de.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=mr(await pr({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=mr(await pr({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=mr(await pr({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}}X(r),de.success(`saved ${e} credentials`)}async function zh(t){let e=De(t.profile);Yh(`codepipe repo add \u2192 project ${e.projectId}`);let r=ye()??void 0,n;try{n=(await Q(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){je(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await Wh(process.cwd());h?(o=process.cwd(),de.message(`using the current directory (${h})`)):o=mr(await pr({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:b=>b.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(pc(o)&&DT(o).isDirectory()){i=MT(o);let h=await Wh(i);h||je(`${i} is not a git repository (no origin remote)`);let b=Be(h);b||je(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=b,s=h,de.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=Be(o);h||je(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,de.message(`${a}: ${c}/${l}`)}let u=mr(await pr({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)&&je(`a repo named "${u}" is already registered`);let p=mr(await pr({message:"default branch (optional)",placeholder:"main"})).trim(),d=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=LT(r.root,i);d=h===""?".":h}let m=mr(await pr({message:"mount_as (directory relative to the workspace root)",placeholder:d,initialValue:d})).trim()||d;n.some(h=>(h.mountAs??h.name)===m)&&je(`mount_as "${m}" is already used by another repo`),await GT(e,a);let f={name:u,host:a,owner:c,repoName:l,mountAs:m,...p?{defaultBranch:p}:{}};if(!i){let h=r?Di(r.root,m):$e(e.projectId,u);if(pc(Di(h,".git")))de.message(`already cloned at ${h}`);else{de.info(`cloning ${s} \u2192 ${h} \u2026`);try{await Vh().clone(s,h),de.success(`cloned into ${h}`)}catch(b){je(`clone failed: ${b instanceof Error?b.message.trim():String(b)}
825
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let g;try{g=await cd(e.hubUrl,e.cliToken,e.projectId,f)}catch(h){h instanceof U&&je(`HUB \u2192 ${h.status} ${h.message}`),je(h instanceof Error?h.message:String(h))}let{updated:y,errors:k}=Ln(e.projectId,g.repos,r?.contextDir);for(let h of y)de.message(`updated ${h}`);for(let h of k)de.warn(`could not update ${h.path}: ${h.error}`);de.success(`added "${u}" \u2014 project now has ${g.repos.length} repo(s)`),qh("done")}async function Jh(t){let e=De(t.profile);Yh(`codepipe repo remove \u2192 project ${e.projectId}`);let r=ye()??void 0,n;try{let c=(await Q(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await ld(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof U&&(a.status===404&&je(`no repo named "${t.name}" in this project`),je(`HUB \u2192 ${a.status} ${a.message}`)),je(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Ln(e.projectId,o.repos,r?.contextDir);for(let a of i)de.message(`updated ${a}`);for(let a of s)de.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")de.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Di(r.root,n):$e(e.projectId,t.name);if(pc(Di(a,".git")))try{OT(a,{recursive:!0,force:!0}),de.message(`deleted local clone ${a}`)}catch(c){de.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else de.message(`no local clone found to purge (${a})`)}de.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),qh("done")}async function Xh(t){let e=De(t.profile),r;try{r=(await Q(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}Ai();qa();Za();tn();W();Re();tn();Pe();we();Zn();import{hostname as KT}from"node:os";import{cancel as HT,confirm as Qh,intro as WT,isCancel as ty,log as pn,multiselect as YT,outro as Zh,password as qT,select as mc,text as fc}from"@clack/prompts";function so(t){HT(t),process.exit(1)}function mn(t){return ty(t)&&so("aborted"),t}function Li(t){return ty(t)&&so("aborted"),typeof t=="string"?t:""}function Mi(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function ey(t,e){try{let{secret:r}=await Lo(t,e);return r}catch(r){throw r instanceof U&&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 VT(t,e){if(mn(await mc({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 Rs(t,e);if(o.length>0)return mn(await YT({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}));pn.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){pn.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Li(await fc({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 gc(t){WT("codepipe worker \u2014 set up this machine as a runner");let e=ve(t.profile);e&&(pn.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),mn(await Qh({message:"re-register this worker?",initialValue:!1}))||so("keeping the existing registration"));let r=Ye(t.profile)??Ye(),n=Li(await fc({message:"HUB URL",placeholder:Ze,initialValue:H("HUB_URL")??r?.hubUrl??Ze,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=mn(await mc({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 ey(n,a),pn.success("account-issued registration token minted");else if(i==="login"){let d=await ln();a=(await un(n,d)).cliToken,s=await ey(n,a),pn.success("account-issued registration token minted")}else s=Li(await qT({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||so("a registration token is required");let c=await VT(n,a),l=Li(await fc({message:"worker name",initialValue:KT(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=mn(await mc({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 lr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),pn.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!mn(await Qh({message:"start the claim-loop now?",initialValue:!0}))){Zh("registered. start later with `codepipe worker`.");return}Zh("starting the claim-loop\u2026"),await Jn(t.profile?{profile:t.profile}:{})}function JT(){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 H("PROFILE")}var se=JT();Ml(se);Fl();var Ie=new zT;Ie.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(Ne).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{Mi()?await Qa({profile:se}):await Ya({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ie.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 _h({configPath:t.config,skipVerify:t.skipVerify===!0}):await xh({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ie.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await eu({...t,profile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ie.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 Sh({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ie.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await mf({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ie.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 zg({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ie.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 Mh({profile:se,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ie.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await $g({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ie.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 Ya({profile:se,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var ry=Ie.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");ry.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??H("HUB_URL")??Ye(se)?.hubUrl??Ze,r=t.token??H("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Mi()){await gc({profile:se});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=H("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??H("WORKER_NAME"),i=t.llm??H("WORKER_LLM");await lr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...se?{profile:se}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ry.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ve(se)&&Mi()){await gc({profile:se});return}await Jn(se?{profile:se}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var ny=Ie.command("project").description("Manage CodePipe projects");ny.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Gh({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ny.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 Hh({...t,cliProfile:se})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var hc=Ie.command("repo").description("Manage the project's git repositories");hc.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 zh({profile:se,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});hc.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 Jh({profile:se,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});hc.command("list").description("List the project's repos").action(async()=>{try{await Xh({profile:se})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var oy=Ie.command("model").description("Project map (model/ in the Context Repo)");oy.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 nc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});oy.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 oc({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ie.parseAsync();