@code-partner/codepipe 0.14.1-dev.305.g250dfd51 → 0.14.1-dev.312.gd90c067f

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 +386 -372
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,40 +1,41 @@
1
1
  #!/usr/bin/env node
2
- var Jv=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ne=(t,e)=>{for(var r in e)Jv(t,r,{get:e[r],enumerable:!0})};var et,vt,Ta=E(()=>{"use strict";et="0.14.1-dev.305.g250dfd51",vt="https://hub.dev.codepipe.dev"});function bo(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=_d&&t<=$t}var $t,_d,jd=E(()=>{"use strict";Ta();$t=4,_d=4});var Nd=E(()=>{"use strict";Ta()});function ko(t=6){return`# CodePipe Context Repo format version.
2
+ var g$=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Me=(t,e)=>{for(var r in e)g$(t,r,{get:e[r],enumerable:!0})};var ot,Et,Oa=E(()=>{"use strict";ot="0.14.1-dev.312.gd90c067f",Et="https://hub.dev.codepipe.dev"});function Eo(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Hd&&t<=Rt}var Rt,Hd,Wd=E(()=>{"use strict";Oa();Rt=4,Hd=4});var qd=E(()=>{"use strict";Oa()});function Ro(t=6){return`# CodePipe Context Repo format version.
3
3
  # Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
4
4
  template_version: ${t}
5
- `}function Ca(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 Pa(t,e=Ia){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 Aa(t,e=Ia){return e.filter(r=>r.version>t)}var Od,xt,fn,Ia,Ld=E(()=>{"use strict";Od=6,xt=".codepipe-context.yaml",fn=".devpipe-context.yaml",Ia=[{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",xt]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[xt]},{version:3,summary:"Custom project actions (the RUN tab): actions/ scaffold with the format README",addedPaths:["actions/README.md"]},{version:4,summary:"Project map: model/ scaffold with the format README (facts/ vs derived/ layout)",addedPaths:["model/README.md"]},{version:5,summary:"Roles: roles/ scaffold with the format README (override a bundled critic by name, or add your own)",addedPaths:["roles/README.md"]},{version:6,summary:"Skills: skills/ scaffold with the format README (procedures the agent invokes instead of improvising)",addedPaths:["skills/README.md"]}]});function $o(t){return`model/facts/identity/${t}.yaml`}function _r(t){return`model/facts/events/${t}.yaml`}function Na(t){return`model/facts/annotations/${t}.md`}function Oa(t){return`model/derived/correlates/${t}.yaml`}function La(t){return`model/derived/touched/${t}.yaml`}function Md(t){return t===""?"root":t.replace(/\//g,"-")}function Ma(t,e){return`model/derived/structure/${t}/${Md(e)}.yaml`}function Ri(t){return typeof t=="string"&&Ud.test(t)}function re(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(!Dd.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!r$.includes(n)||i===""?null:{level:n,repo:o,path:i}}function Re(t){return`task::${t}`}function be(t,e,r){return`${t}:${e}:${r}`}function xo(t){let e=[];return _t(t)?(Ii(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(!_t(r)){e.push(`edges[${n}]: not an object`);return}Da.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),re(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),re(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 Bd(t){return{...t,edges:mn(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function jr(t){return Or(Bd(t))}function _t(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ii(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function St(t){return typeof t=="string"&&t.length>0}function o$(t){return t.modelFormatVersion!==2}function Gt(t){let e=[];if(!_t(t))return{ok:!1,errors:["shard: not an object"]};Ii(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),St(t.repo)||e.push("repo: missing or empty"),St(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=re(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&&!Ri(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}Da.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!St(o.to)||!re(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!St(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 So(t){let e=[];if(!_t(t))return{ok:!1,errors:["identity: not an object"]};if(Ii(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),St(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!St(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}Ri(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)})`),re(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),St(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),St(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!_t(i)||!re(i.key)||!St(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 Kt(t){let e=[];return _t(t)?(Ii(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),St(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=>!St(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!_t(r)||!re(r.key)){e.push(`files[${n}].key: malformed nodeKey`);return}r.entityId!==void 0&&!Ri(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 mn(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Fd(t){return{...t,nodes:mn(t.nodes,e=>e.key),edges:mn(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function Gd(t){return{...t,entities:mn(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:mn(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function Kd(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:mn(t.files,r=>r.key),...e?{links:e}:{}}}function vo(t){return i$.test(t)?t:JSON.stringify(t)}function Hd(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 Wd(t){return t===null||["boolean","number","string"].includes(typeof t)}function _a(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function qd(t,e,r){if(Array.isArray(t)){for(let n of t)if(Wd(n))r.push(`${e}- ${Hd(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=_a(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;ja(i,s,c,`${e} `,r)})}}return}for(let[n,o]of _a(t))ja(n,o,e,e,r)}function ja(t,e,r,n,o){if(Wd(e))o.push(`${r}${vo(t)}: ${Hd(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${vo(t)}: []`):(o.push(`${r}${vo(t)}:`),qd(e,`${n} `,o));else{let i=_a(e);if(i.length===0)o.push(`${r}${vo(t)}: {}`);else{o.push(`${r}${vo(t)}:`);for(let[s,a]of i)ja(s,a,`${n} `,`${n} `,o)}}}function Or(t){let e=[];return qd(t,"",e),e.join(`
5
+ `}function Ma(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 Da(t,e=La){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 Ua(t,e=La){return e.filter(r=>r.version>t)}var Yd,Tt,vn,La,Vd=E(()=>{"use strict";Yd=6,Tt=".codepipe-context.yaml",vn=".devpipe-context.yaml",La=[{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"]},{version:5,summary:"Roles: roles/ scaffold with the format README (override a bundled critic by name, or add your own)",addedPaths:["roles/README.md"]},{version:6,summary:"Skills: skills/ scaffold with the format README (procedures the agent invokes instead of improvising)",addedPaths:["skills/README.md"]}]});function Io(t){return`model/facts/identity/${t}.yaml`}function Dr(t){return`model/facts/events/${t}.yaml`}function Ga(t){return`model/facts/annotations/${t}.md`}function Ka(t){return`model/derived/correlates/${t}.yaml`}function Ha(t){return`model/derived/touched/${t}.yaml`}function zd(t){return t===""?"root":t.replace(/\//g,"-")}function Wa(t,e){return`model/derived/structure/${t}/${zd(e)}.yaml`}function ji(t){return typeof t=="string"&&Jd.test(t)}function re(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(!Xd.includes(n))return null;let o=t.slice(e+1,r),i=t.slice(r+1);return o===""&&!v$.includes(n)||i===""?null:{level:n,repo:o,path:i}}function Re(t){return`task::${t}`}function be(t,e,r){return`${t}:${e}:${r}`}function Co(t){let e=[];return Mt(t)?(Oi(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(!Mt(r)){e.push(`edges[${n}]: not an object`);return}qa.includes(r.kind)||e.push(`edges[${n}].kind: unknown "${String(r.kind)}"`),re(r.from)||e.push(`edges[${n}].from: malformed nodeKey`),re(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 Zd(t){return{...t,edges:$n(t.edges,e=>`${e.kind} ${e.from} ${e.to}`)}}function Ur(t){return Fr(Zd(t))}function Mt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Oi(t){return typeof t=="number"&&Number.isInteger(t)&&t>0}function It(t){return typeof t=="string"&&t.length>0}function x$(t){return t.modelFormatVersion!==2}function qt(t){let e=[];if(!Mt(t))return{ok:!1,errors:["shard: not an object"]};Oi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),It(t.repo)||e.push("repo: missing or empty"),It(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(!Mt(o)){e.push(`nodes[${i}]: not an object`);return}let s=re(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(!Mt(o)){e.push(`edges[${i}]: not an object`);return}qa.includes(o.kind)||e.push(`edges[${i}].kind: unknown "${String(o.kind)}"`),(!It(o.to)||!re(o.to))&&e.push(`edges[${i}].to: malformed nodeKey`),(!It(o.from)||!n.has(o.from))&&e.push(`edges[${i}].from: "${String(o.from)}" is not a node of this shard`),o.weight!==void 0&&!(typeof o.weight=="number"&&Number.isFinite(o.weight))&&e.push(`edges[${i}].weight: not a finite number`)}):e.push("edges: not an array"),e.length?{ok:!1,errors:e}:{ok:!0,value:t}}function Po(t){let e=[];if(!Mt(t))return{ok:!1,errors:["identity: not an object"]};if(Oi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),It(t.repo)||e.push("repo: missing or empty"),t.builtFromCommit!==void 0&&!It(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(!Mt(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)})`),re(n.currentKey)||e.push(`entities[${o}].currentKey: malformed nodeKey`),n.status!=="active"&&n.status!=="orphaned"&&e.push(`entities[${o}].status: expected active|orphaned`),It(n.firstSeen)||e.push(`entities[${o}].firstSeen: missing`),It(n.lastSeen)||e.push(`entities[${o}].lastSeen: missing`),n.aliases!==void 0&&(Array.isArray(n.aliases)?n.aliases.forEach((i,s)=>{(!Mt(i)||!re(i.key)||!It(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 Yt(t){let e=[];return Mt(t)?(Oi(t.modelFormatVersion)||e.push("modelFormatVersion: missing or not a positive integer"),It(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=>!It(r)))&&e.push("commits: not an array of non-empty strings"),Array.isArray(t.files)?t.files.forEach((r,n)=>{if(!Mt(r)||!re(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 $n(t,e){return[...t].sort((r,n)=>e(r)<e(n)?-1:e(r)>e(n)?1:0)}function Qd(t){return{...t,nodes:$n(t.nodes,e=>e.key),edges:$n(t.edges,e=>`${e.kind}\0${e.from}\0${e.to}`)}}function ep(t){return{...t,entities:$n(t.entities,e=>e.entityId).map(e=>e.aliases?{...e,aliases:$n(e.aliases,r=>`${r.key}\0${r.until}`)}:e)}}function tp(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:$n(t.files,r=>r.key),...e?{links:e}:{}}}function To(t){return S$.test(t)?t:JSON.stringify(t)}function rp(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 np(t){return t===null||["boolean","number","string"].includes(typeof t)}function Ba(t){return Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[r])=>e<r?-1:e>r?1:0)}function op(t,e,r){if(Array.isArray(t)){for(let n of t)if(np(n))r.push(`${e}- ${rp(n)}`);else{if(Array.isArray(n))throw new Error("model yaml: nested arrays are not part of the model schema");{let o=Ba(n);if(o.length===0){r.push(`${e}- {}`);continue}o.forEach(([i,s],a)=>{let c=a===0?`${e}- `:`${e} `;Fa(i,s,c,`${e} `,r)})}}return}for(let[n,o]of Ba(t))Fa(n,o,e,e,r)}function Fa(t,e,r,n,o){if(np(e))o.push(`${r}${To(t)}: ${rp(e)}`);else if(Array.isArray(e))e.length===0?o.push(`${r}${To(t)}: []`):(o.push(`${r}${To(t)}:`),op(e,`${n} `,o));else{let i=Ba(e);if(i.length===0)o.push(`${r}${To(t)}: {}`);else{o.push(`${r}${To(t)}:`);for(let[s,a]of i)Fa(s,a,`${n} `,`${n} `,o)}}}function Fr(t){let e=[];return op(t,"",e),e.join(`
6
6
  `)+`
7
- `}function Ka(t){return Or(Fd(t))}function Ha(t){return Or(Gd(t))}function hn(t){return Or(Kd(t))}var Fe,Zv,Qv,e$,t$,Ei,Ar,Dd,Da,Ud,r$,lt,Ua,Ba,Fa,Ti,n$,Ga,Nr,i$,Wa=E(()=>{"use strict";Fe=2,Zv="model",Qv="model/README.md",e$="model/facts",t$="model/derived",Ei="model/derived/INDEX.yaml",Ar="model/derived/relates.yaml";Dd=["system","container","component","code","task","adr"],Da=["contains","touched_by","correlates","relates","references","depends_on"],Ud=/^e_[0-9a-f]{8}$/;r$=["system","task","adr"];lt={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Ua=2,Ba=5,Fa=50,Ti=2e3,n$=5e4,Ga={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},Nr={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};i$=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function s$(t){return t==="DONE"}function a$(t){return t==="AWAITING_EXTERNAL_FIX"?!1:qa.indexOf(t)>=qa.indexOf("IMPLEMENTING")}var qa,Yd=E(()=>{"use strict";qa=["BACKLOG","QUEUED","INTAKE","AWAITING_APPROVAL","ANALYZING","ESTIMATING","AWAITING_ANSWER","REVIEW","READY","IMPLEMENTING","BUILD","CODE_REVIEW","TESTING","AWAITING_EXTERNAL_FIX","READY_TO_APPLY","APPLYING","AWAITING_CLUSTER","TRACKING","NEEDS_MANUAL","DONE"]});function l$(t){for(let e of Ya)if(e.phases.includes(t))return e.id;return null}function u$(t){for(let e of Vd)if(e.phases.includes(t))return e.id;return null}var Ya,c$,Vd,zd=E(()=>{"use strict";Ya=[{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"]}],c$=Ya.flatMap(t=>t.phases),Vd=[{id:"review",label:"Review / tracking",phases:["CODE_REVIEW","TESTING","TRACKING"]},{id:"attention",label:"Need your attention",phases:["NEEDS_MANUAL","AWAITING_APPROVAL","AWAITING_EXTERNAL_FIX","AWAITING_ANSWER","REVIEW"]},{id:"backlog",label:"Backlog / queue",phases:["BACKLOG","QUEUED"]}]});function za(t){return Jd.includes(t)}function d$(t){return Xd.includes(t)?"planning":"implementation"}function ut(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Va,Xd,Jd,p$,Xa=E(()=>{"use strict";Va=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","config","observer","council","testing"],Xd=["draft","analysis","chat","config","observer","council"],Jd=["chat","config"];p$=1});function f$(t){return typeof t=="string"&&np.includes(t.trim())?t.trim():null}function Zd(t,e){return e.toLowerCase().includes(t.toLowerCase())}function Za(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||ap.every(o=>e.some(i=>Zd(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 sp){let i=n.find(s=>Zd(o,s.id));if(i)return i.id}return n[0].id}function gn(){return{default:null,roles:{}}}function m$(t,e,r=op){let n=t?.roles?.[e];if(typeof n=="string"&&n.trim().length>0)return n.trim();if(t?.default&&t.default.trim().length>0)return t.default.trim();let o=ip[r]?.[e];return o||(Eo[e]??rp)}function h$(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():tt}function g$(t){let e=gn();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.provider;typeof n=="string"&&n.trim().length>0&&(e.provider=n.trim());let o=r.models;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o))typeof s!="string"||s.trim().length===0||(i==="default"?e.default=s.trim():e.roles[i]=s.trim());return e}function yn(){return{default:null,roles:{}}}function y$(t,e){let r=t?.roles?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():t?.default&&t.default.trim().length>0?t.default.trim():Ro[e]}function w$(t){let e=yn();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.effort;if(!n||typeof n!="object")return e;for(let[o,i]of Object.entries(n))typeof i!="string"||i.trim().length===0||(o==="default"?e.default=i.trim():e.roles[o]=i.trim());return e}function b$(t){return t.default===null&&Object.keys(t.roles).length===0?null:JSON.stringify(t)}function k$(t){if(!t)return yn();try{let e=JSON.parse(t);if(!e||typeof e!="object")return yn();let r=e,n=yn();typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return yn()}}function v$(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==tt;if(t.default===null&&Object.keys(t.roles).length===0&&!e)return null;let{provider:r,...n}=t;return JSON.stringify(e?{provider:r.trim(),...n}:n)}function $$(t){if(!t)return gn();try{let e=JSON.parse(t);if(!e||typeof e!="object")return gn();let r=e,n=gn();typeof r.provider=="string"&&r.provider.trim().length>0&&(n.provider=r.provider.trim()),typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return gn()}}var tt,Ja,Ce,Ht,wn,Ci,Qd,ep,tp,Pi,Eo,rp,np,op,ip,sp,ap,cp,Ai,Ro,Qa=E(()=>{"use strict";Xa();tt="claude",Ja=[tt],Ce="opus",Ht="sonnet",wn="haiku",Ci=[Ce,Ht,wn],Qd="build-discovery",ep="code-review-verify",tp=[Qd,ep],Pi=[...Va,...tp],Eo={analyze:Ce,implement:Ce,"resolve-conflict":Ce,rework:Ce,estimate:Ht,build:wn,"build-discovery":Ce,"code-review":Ce,"code-review-verify":Ht,draft:Ht,index:Ce,backfill:Ce,analysis:Ce,chat:Ce,config:Ce,observer:Ce,council:Ce,testing:Ce},rp=Ce,np=["express","balanced","full"],op="full",ip={express:{"code-review":Ht,"code-review-verify":wn},balanced:{implement:Ht,"code-review":Ht,"code-review-verify":wn},full:{}};sp=[Ce,Ht,wn],ap=Array.from(new Set(Object.values(Eo)));cp=["low","medium","high","xhigh"],Ai=cp,Ro={build:"low",estimate:"low",draft:"medium",index:"medium","code-review-verify":"medium"}});function Wt(t){return x$.has(t)?!0:S$.some(e=>t.startsWith(e))}function _i(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Lr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function tc(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function nc(t,e){let r=_i(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Lr(r.id,"id")??n;if(!ec.test(o))throw new Error(`id must match ${ec} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Lr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=_i(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!rt.test(d))throw new Error(`env name "${d}" must match ${rt}`);if(typeof f!="string"&&typeof f!="number"&&typeof f!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(f)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>lp)throw new Error(`too many params (max ${lp})`);let p=new Set;a=c.map((d,f)=>E$(d,f,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>up)throw new Error(`too many steps (max ${up})`);let u=l.map((p,d)=>{let f=_i(p,`steps[${d}]`),m=Lr(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let y=Lr(f.name,`steps[${d}].name`),b=tc(f.timeout_sec,`steps[${d}].timeout_sec`);if(b!==void 0&&(!Number.isInteger(b)||b<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...y?{name:y}:{},...b!==void 0?{timeout_sec:b}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function E$(t,e,r){let n=_i(t,`params[${e}]`),o=Lr(n.name,`params[${e}].name`);if(!o||!rt.test(o))throw new Error(`params[${e}].name must match ${rt}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=Lr(n.label,`params[${e}].label`),c=Lr(n.help,`params[${e}].help`),l=n.required===!0,u=tc(n.min,`params[${e}].min`),p=tc(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 oc(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 rt,x$,S$,rc,ec,lp,up,ic=E(()=>{"use strict";rt=/^[A-Z][A-Z0-9_]*$/,x$=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),S$=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];rc=600,ec=/^[a-z0-9-]+$/,lp=32,up=64});function dp(){return{primary:ke,context:ke,tasks:ke,docs:ke,code_comments:ke,chat:ke,code_review:ke,commits:ke}}function pp(t){return!t||t.trim().length===0||t.trim().toLowerCase()===ke}function R$(t){if(typeof t!="string")return ke;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===ke?ke:e}function T$(t){let e=dp();if(!t||typeof t!="object")return e;let r=t.language;if(!r||typeof r!="object"||Array.isArray(r))return e;let n=r;for(let o of To)e[o]=R$(n[o]);return e}function I$(t){return To.every(e=>pp(t[e]))}var ke,To,bn,Io,sc=E(()=>{"use strict";ke="auto",To=["primary","context","tasks","docs","code_comments","chat","code_review","commits"],bn=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],Io=40});function uc(t=fp){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...uc(r.groups));return e}function mp(t,e){let r=JSON.stringify(e);return uc().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function dc(t){let e=mp(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)?{ok:!1,error:`${e.id} must be a number`}:!e.float&&!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>ac)return{ok:!1,error:`${e.id} must have \u2264 ${ac} entries`};let s={};for(let[a,c]of i){if(!rt.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${rt}`};if(Wt(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>cc)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${cc} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var C$,P$,ac,cc,lc,fp,hp=E(()=>{"use strict";ic();Qa();Wa();sc();C$={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat",code_review:"Code review comments",commits:"Commits & branches"},P$={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages.",code_review:"Review findings and PR comments. Empty \u21D2 follows the tracker-issues language.",commits:"Commit/PR subject & branch slug. Empty \u21D2 follows the tracker-issues language."},ac=64,cc=2e3,lc=2e3,fp=[{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:[...Ja],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:[...Ci],help:"Overrides the recommended defaults for every role not listed below."},...Pi.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Ci],help:`recommended: ${Eo[t]} (the workflow preset may set a cheaper default \u2014 an explicit value here overrides both)`}))]},{id:"llm.effort",label:"Reasoning effort by role",help:"Reasoning effort per pipeline stage (Claude Code --effort). Empty \u21D2 the mechanical roles run lowered (build/estimate: low; draft/index/code-review-verify: medium) and every other role keeps the backend default.",fields:[{id:"llm.effort.default",file:"regimen.yaml",path:["llm","effort","default"],type:"enum",label:"default (catch-all)",nullable:!0,suggestions:[...Ai],help:"Overrides the recommended lowerings for every role not listed below."},...Pi.map(t=>({id:`llm.effort.${t}`,file:"regimen.yaml",path:["llm","effort",t],type:"enum",label:t,nullable:!0,suggestions:[...Ai],help:Ro[t]?`recommended: ${Ro[t]}`:"recommended: backend default"}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:lc,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:lc,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"regimen.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"regimen.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"code_review",label:"Code review",help:"One review mechanism for the pipeline's own changes and for developers' branches (the review column); they differ only in where the findings go.",fields:[{id:"code_review.verify_pass",file:"regimen.yaml",path:["code_review","verify_pass"],type:"boolean",nullable:!1,label:"Verifier pass (precision)",help:"On by default. A second, narrow agent checks every finding against the code (real? re-grade) before it costs a rework round or reaches a developer; the findings threshold below keeps small rounds cheap."},{id:"code_review.verify_min_findings",file:"regimen.yaml",path:["code_review","verify_min_findings"],type:"number",nullable:!0,min:1,label:"Verifier threshold (findings)",help:"The verifier runs only when a round carries at least this many actionable findings \u2014 1-2 are cheap to absorb, noise scales with volume. Empty = 3; 1 = verify every round."},{id:"code_review.max_blocking",file:"regimen.yaml",path:["code_review","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (internal)",help:"Max blocker findings that keep their power in the pipeline's own review; the rest are demoted to major, weakest confidence first. Empty = 5."},{id:"code_review.external.max_blocking",file:"regimen.yaml",path:["code_review","external","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (external)",help:"The same budget for a developer's branch review \u2014 tighter by default because a human reads these. Empty = 3."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"regimen.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"regimen.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"regimen.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"quality",label:"Quality block",help:"Skip the whole quality block (build + code review) when a change touches only safe paths.",fields:[{id:"quality.skip_paths",file:"regimen.yaml",path:["quality","skip_paths"],type:"string_list",nullable:!0,label:"Skip paths (gitignore-style)",help:"When every changed file across all repos matches these globs, build and code review are skipped and the change goes straight to apply. One file outside the list runs both as usual. Use ! to re-include (e.g. !schema/**/*.md). Empty = never skip."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), the observer's intake plan waits for your APPROVE & START before the batch runs. Off \u21D2 conveyor: the batch starts automatically on the observer's plan. Either way every task passes the observer intake first."},{id:"observer.debounce_seconds",file:"regimen.yaml",path:["observer","debounce_seconds"],type:"number",label:"Intake window (seconds)",nullable:!0,min:5,max:3600,help:"How long the queue collects newly staged tasks before the observer reviews them as one batch. Empty \u21D2 60."},{id:"observer.fast_path",file:"regimen.yaml",path:["observer","fast_path"],type:"boolean",label:"Fast path for trivial tasks",nullable:!1,help:"On by default. A single small task with no links skips the observer's LLM pass and is routed by rules (noted in its journal as routed without review)."}]},{id:"council",label:"Council",help:"Several roles examine the same subject in parallel, each in its own process; a final session weighs their written opinions. Costs several agent runs per use \u2014 off by default, enable per phase.",fields:[{id:"council.questions",file:"regimen.yaml",path:["council","questions"],type:"boolean",nullable:!1,label:"Council on blocking questions",help:"Off (default): an agent's blocking question is answered by a single session, which keeps full automation moving cheaply. On: the council's roles each write an independent opinion first, and the answering session weighs them."},{id:"council.code_review",file:"regimen.yaml",path:["council","code_review"],type:"boolean",nullable:!1,label:"Council on code review",help:"Off (default): one reviewer session judges the change alone. On: the project's critic roles each review the change in their own parallel process first, and the reviewer session weighs their written findings into the verdict. Applies to the internal and the external review; the verifier pass always runs solo."},{id:"council.max_parallel",file:"regimen.yaml",path:["council","max_parallel"],type:"number",nullable:!0,min:1,max:5,label:"Max parallel roles",help:"How many role processes run at once (the rest wait their turn). Empty \u21D2 3; hard ceiling 5."}]},{id:"workflow",label:"Workflow",help:"How much pipeline a task gets. A preset is a set of defaults \u2014 any explicit setting below always wins over it.",fields:[{id:"workflow.preset",file:"regimen.yaml",path:["workflow","preset"],type:"enum",nullable:!1,suggestions:["express","balanced","full"],label:"Preset",help:"express \u2014 no analysis phase, no review: one implementation session on the capable model (cheapest, for small clear tasks). balanced \u2014 every phase, cheaper models for implementation and review. full \u2014 the classic pipeline on the capable model."},{id:"workflow.observer_routing",file:"regimen.yaml",path:["workflow","observer_routing"],type:"boolean",nullable:!1,label:"Observer routes presets",help:"Off (default): every task runs the project's preset. On: the intake observer may assign a preset per task (a small clear task goes express, a risky one goes full), within the allowed list below; your explicit pick on a queued task always wins. A task that gets stuck on express escalates to the full pipeline automatically."},{id:"workflow.allowed_presets",file:"regimen.yaml",path:["workflow","allowed_presets"],type:"string_list",nullable:!0,label:"Presets the observer may use",help:"Limits observer routing, e.g. only balanced and full (no express). Empty \u21D2 all three."},{id:"analysis.enabled",file:"regimen.yaml",path:["analysis","enabled"],type:"boolean",nullable:!1,label:"Analysis phase",help:"Whether a task starts with a dedicated analysis pass (plan + open questions) before implementation. Off \u21D2 the implementer works straight from the task text and the context pack; an explicit value here overrides the preset."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:To.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:C$[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[ke,...bn]:[...bn],help:P$[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"regimen.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"On by default. Agents are asked to record intent annotations and receive an assembled context pack built from the project map. Off \u21D2 the pipeline ignores the map entirely and behaves exactly as if the feature were absent."},{id:"context.model.pack.idf_penalty",file:"regimen.yaml",path:["context","model","pack","idf_penalty"],type:"boolean",label:"Demote ubiquitous files in the pack",nullable:!1,help:"On by default. Files that reached the pack only through STATISTICAL co-change (not direct task evidence) are ranked down in proportion to how many past tasks touched them, so the budget goes to task-specific paths. Off restores pure activation order."},{id:"context.model.prompt.pack",file:"regimen.yaml",path:["context","model","prompt","pack"],type:"boolean",nullable:!1,label:"Give agents the context pack",help:"On by default. The assembled pack costs up to ~4000 tokens on every task of the analyze / estimate / implement / rework roles. Turning it off keeps the map building and stops the spend \u2014 the way to see what the pack is actually worth on this project."},{id:"context.model.prompt.annotations",file:"regimen.yaml",path:["context","model","prompt","annotations"],type:"boolean",nullable:!1,label:"Ask agents for intent annotations",help:"On by default. Adds the annotations block to the implement and rework prompts \u2014 the layer that records WHY the code is shaped this way. Cheap, and worth accumulating even while the pack is off."},{id:"context.index.hub",file:"regimen.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"regimen.yaml",path:["context","model","issue_key_pattern"],type:"string",label:"Issue-key pattern (regex)",nullable:!0,maxLength:200,help:"Regex that finds tracker issue keys in commit subjects when mining task events from history. Empty \u21D2 derived from the tracker project key (e.g. DEV-\\d+)."},{id:"context.model.cochange.window_commits",file:"regimen.yaml",path:["context","model","cochange","window_commits"],type:"number",label:"History window (commits)",nullable:!0,min:50,max:5e4,help:`How many commits back from the build commit are mined. Default ${lt.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 ${lt.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 ${lt.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 ${lt.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 ${lt.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 ${lt.topK}.`}]},{id:"rate_limit",label:"Rate limit",help:"Automatic project pause as the LLM usage window fills up.",fields:[{id:"rate_limit.auto_pause.enabled",file:"project.yaml",path:["rate_limit","auto_pause","enabled"],type:"boolean",nullable:!1,label:"Pause the project near the limit",help:"On (default): when window utilization reaches the threshold, the project is paused (same pause as the manual one) and you get an email \u2014 the remaining window stays available for your own work. Off: agents keep working until the provider actually runs out."},{id:"rate_limit.auto_pause.threshold",file:"project.yaml",path:["rate_limit","auto_pause","threshold"],type:"number",float:!0,nullable:!0,min:.05,max:1,label:"Pause threshold (share of the window)",help:"Fraction of the usage window at which the pause fires; the rest (1 \u2212 threshold) is your manual-work reserve. Empty \u21D2 0.75."}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"regimen.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});var gp=E(()=>{"use strict"});function yp(t){if(t==null)return[];if(!Array.isArray(t))return null;let e=[];for(let r of t){if(typeof r!="string"||r.trim().length===0)return null;e.push(r.trim())}return e}function fc(t){let{name:e,body:r,origin:n}=t;if(!pc.test(e))return{ok:!1,error:`role name must match ${pc} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let i=o,s=i.description;if(typeof s!="string"||s.trim().length===0)return{ok:!1,error:"description is required (one line: what this role looks for)"};if(s.length>300)return{ok:!1,error:"description must be \u2264 300 characters"};let a=yp(i.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let f of a)if(f.startsWith("/")||f.includes(".."))return{ok:!1,error:`ref "${f}" must be a path inside the Context Repo`};let c=yp(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let f of c){if(!ji.includes(f))return{ok:!1,error:`unknown scenario "${f}" \u2014 one of: ${ji.join(", ")}`};l.includes(f)||l.push(f)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${ji.join(", ")}`};let u=i.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=i.provider;if(p!==void 0&&(typeof p!="string"||p.trim().length===0))return{ok:!1,error:"provider must be a non-empty string when set"};let d=i.enabled;return d!==void 0&&typeof d!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:s.trim(),...typeof u=="string"?{model:u.trim()}:{},...typeof p=="string"?{provider:p.trim()}:{},refs:a,scenarios:l,enabled:d!==!1,body:r.trim(),origin:n}}}function mc(t,e){let r=new Map;for(let n of t)r.set(n.name,n);for(let n of e)r.set(n.name,n);return[...r.values()].sort((n,o)=>n.name<o.name?-1:n.name>o.name?1:0)}function hc(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var ji,pc,i0,s0,wp=E(()=>{"use strict";ji=["plan_review","code_review","council"],pc=/^[a-z][a-z0-9-]{1,39}$/,i0=10,s0=300});function gc(t){return bp.includes(t)}function yc(t){return`prompts/${t}.md`}var bp,kp=E(()=>{"use strict";bp=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","code-review-verify","config","council","draft","estimate","implement","implement-direct","index","observer","resolve-conflict","review-comment","rework","testing"]});function bc(t){if(!wc.test(t.name))return{ok:!1,error:`skill directory name must match ${wc}`};if(t.body.trim().length===0)return{ok:!1,error:"SKILL.md has no body \u2014 the body IS the procedure"};let e=t.frontmatter;if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"SKILL.md has no frontmatter block"};let r=e.description;return typeof r!="string"||r.trim().length===0?{ok:!1,error:"description is required \u2014 it is what decides when the skill fires"}:r.length>300?{ok:!1,error:"description must be \u2264 300 characters"}:{ok:!0,skill:{name:t.name,description:r.trim()}}}function kc(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}function $p(t){let e=t.trim(),r=e.lastIndexOf("@"),n=r===-1?e:e.slice(0,r),o=r===-1?"":e.slice(r+1).trim();if(!A$.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let i=vp.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!_$.test(o)?{ok:!1,error:`"${t}": pin to a full 40-character commit sha \u2014 a branch or tag can change under you`}:!i&&!o?{ok:!1,error:`"${t}": a third-party marketplace must be pinned to a commit (<owner>/<repo>@<sha>). Its skills run beside your code with the agent's token.`}:{ok:!0,source:{repo:n,sha:o,name:i?.name??n.replace("/","-").toLowerCase(),official:!!i}}}function j$(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=$p(o);if(!i.ok){r.push(i.error);continue}n.has(i.source.name)||(n.add(i.source.name),e.push(i.source))}return{sources:e,errors:r}}function O$(t,e){let r=new Set(e.map(i=>i.name)),n={},o=[];for(let i of t){let s=i.trim();if(s){if(!N$.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var wc,l0,vp,A$,_$,N$,xp=E(()=>{"use strict";wc=/^[a-z][a-z0-9-]{1,39}$/,l0=300;vp=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],A$=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,_$=/^[0-9a-f]{40}$/;N$=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function Sp(t,e){if(t==null)return[];if(!Array.isArray(t)||t.length>e)return null;let r=[];for(let n of t){if(typeof n!="string"||n.trim().length===0)return null;r.push(n.trim())}return r}function L$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"queue plan must be a JSON object"};let r=new Set(e),n=t,o=Sp(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let m of o)if(!r.has(m))return{ok:!1,error:`order names ${m}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let i=e.filter(m=>!o.includes(m));if(o.length>0&&i.length>0)return{ok:!1,error:`order omits ${i.join(", ")}`};let s=n.tasks,a=[];if(s!=null){if(!Array.isArray(s))return{ok:!1,error:"tasks must be a list"};for(let m of s){if(!m||typeof m!="object")return{ok:!1,error:"each task entry must be an object"};let y=m,b=typeof y.taskKey=="string"?y.taskKey.trim():"";if(!r.has(b))return{ok:!1,error:`tasks names ${b||"(empty)"}, which is not in this batch`};let w=Sp(y.after,e.length);if(w===null)return{ok:!1,error:`${b}: after must be a list of task keys`};for(let T of w){if(!r.has(T))return{ok:!1,error:`${b}: after names ${T}, not in this batch`};if(T===b)return{ok:!1,error:`${b}: cannot come after itself`}}let k=typeof y.decisions=="string"?y.decisions.trim():"",x,h=y.workflow;if(h&&typeof h=="object"){let T=h,R=typeof T.preset=="string"?T.preset.trim():"";if(R==="express"||R==="balanced"||R==="full"){let v=typeof T.reason=="string"?T.reason.trim().slice(0,4e3):"";x={preset:R,reason:v}}}a.push({taskKey:b,decisions:k.slice(0,4e3),after:w,...x?{workflow:x}:{}})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let m of l){if(!m||typeof m!="object")continue;let y=m,b=typeof y.taskKey=="string"?y.taskKey.trim():"",w=typeof y.adr=="string"?y.adr.trim():"",k=typeof y.detail=="string"?y.detail.trim():"";!r.has(b)||!k||c.push({taskKey:b,adr:w,detail:k.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let m of p){if(!m||typeof m!="object")continue;let y=m,b=typeof y.taskKey=="string"?y.taskKey.trim():"",w=typeof y.detail=="string"?y.detail.trim():"";!b||!w||u.push({taskKey:b,detail:w.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",f=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:f}}}var d0,p0,Ep=E(()=>{"use strict";d0=4e3,p0=4e3});function M$(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"council verdict must be a JSON object"};let r=t,n=r.unresolved===!0,o=typeof r.fork=="string"?r.fork.trim().slice(0,4e3):"";if(n)return o?{ok:!0,verdict:{answers:[],unresolved:!0,fork:o}}:{ok:!1,error:"an unresolved verdict must describe the fork"};let i=r.answers;if(!Array.isArray(i))return{ok:!1,error:"answers must be a list"};if(i.length!==e.length)return{ok:!1,error:`expected ${e.length} answer(s), got ${i.length}`};let s=[];for(let[a,c]of i.entries()){if(!c||typeof c!="object")return{ok:!1,error:`answer ${a+1} must be an object`};let l=c,u=typeof l.answer=="string"?l.answer.trim():"";if(!u)return{ok:!1,error:`answer ${a+1} is empty`};s.push({question:typeof l.question=="string"?l.question.trim():e[a],answer:u.slice(0,4e3),rationale:typeof l.rationale=="string"?l.rationale.trim().slice(0,4e3):""})}return{ok:!0,verdict:{answers:s,unresolved:!1,fork:""}}}var m0,Rp=E(()=>{"use strict";m0=4e3});function B$(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of D$)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function vc(t){let e=[],r=new Map,n="",o=null,i=null;for(let a of t.split(`
8
- `)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=B$(n),i=null;continue}let l=U$.exec(a);if(l&&o){let u=l[1];r.set(u,(r.get(u)??0)+1),i={id:u,kind:o.kind,text:l[2].trim(),section:n},e.push(i);continue}if(i&&a.trim()&&!/^#{1,6}\s/.test(a)&&!/^\s*[-*]\s/.test(a)){i.text=`${i.text}
9
- ${a.trim()}`.trim();continue}a.trim()||(i=null)}let s=[...r.entries()].filter(([,a])=>a>1).map(([a])=>a);return{items:e,structured:e.length>=2&&s.length===0,duplicateIds:s}}function F$(t){let e={decision:"D",change:"C",assumption:"A",out_of_scope:"O",test:"T",procedure:"P"};return t.items.filter(r=>!r.id.startsWith(e[r.kind]))}function G$(t,e){let r=new Map(t.items.map(s=>[s.id,s])),n=e.filter(s=>!s.approved),o=e.filter(s=>s.approved).map(s=>s.id);if(n.length===0)return"";let i=["Rejected plan items:",""];for(let s of n){let a=r.get(s.id),c=a?`${s.id} \u2014 ${a.text.split(`
7
+ `}function Ja(t){return Fr(Qd(t))}function Za(t){return Fr(ep(t))}function xn(t){return Fr(tp(t))}var He,y$,w$,b$,k$,_i,Mr,Xd,qa,Jd,v$,mt,Ya,Va,za,Ni,$$,Xa,Br,S$,Qa=E(()=>{"use strict";He=2,y$="model",w$="model/README.md",b$="model/facts",k$="model/derived",_i="model/derived/INDEX.yaml",Mr="model/derived/relates.yaml";Xd=["system","container","component","code","task","adr"],qa=["contains","touched_by","correlates","relates","references","depends_on"],Jd=/^e_[0-9a-f]{8}$/;v$=["system","task","adr"];mt={windowCommits:1e3,commitFileCap:30,supportMin:5,jaccardMinPct:25,halfLifeDays:270,topK:8};Ya=2,Va=5,za=50,Ni=2e3,$$=5e4,Xa={touched_by:.8,references:.7,relates:.6,correlates:.4,contains:.3,depends_on:.5},Br={budgetTokens:4e3,activationCutoff:.05,topKPerNode:8,nodeCap:200};S$=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/});function E$(t){return t==="DONE"}function R$(t){return t==="AWAITING_EXTERNAL_FIX"?!1:ec.indexOf(t)>=ec.indexOf("IMPLEMENTING")}var ec,ip=E(()=>{"use strict";ec=["BACKLOG","QUEUED","INTAKE","AWAITING_APPROVAL","ANALYZING","ESTIMATING","AWAITING_ANSWER","REVIEW","READY","IMPLEMENTING","BUILD","CODE_REVIEW","TESTING","AWAITING_EXTERNAL_FIX","READY_TO_APPLY","APPLYING","AWAITING_CLUSTER","TRACKING","NEEDS_MANUAL","DONE"]});function I$(t){for(let e of tc)if(e.phases.includes(t))return e.id;return null}function C$(t){for(let e of sp)if(e.phases.includes(t))return e.id;return null}var tc,T$,sp,ap=E(()=>{"use strict";tc=[{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"]}],T$=tc.flatMap(t=>t.phases),sp=[{id:"review",label:"Review / tracking",phases:["CODE_REVIEW","TESTING","TRACKING"]},{id:"attention",label:"Need your attention",phases:["NEEDS_MANUAL","AWAITING_APPROVAL","AWAITING_EXTERNAL_FIX","AWAITING_ANSWER","REVIEW"]},{id:"backlog",label:"Backlog / queue",phases:["BACKLOG","QUEUED"]}]});function nc(t){return lp.includes(t)}function P$(t){return cp.includes(t)?"planning":"implementation"}function ht(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var rc,cp,lp,A$,oc=E(()=>{"use strict";rc=["estimate","analyze","implement","resolve-conflict","rework","draft","build","code-review","index","backfill","analysis","chat","config","observer","council","testing"],cp=["draft","analysis","chat","config","observer","council"],lp=["chat","config"];A$=1});function _$(t){return typeof t=="string"&&hp.includes(t.trim())?t.trim():null}function up(t,e){return e.toLowerCase().includes(t.toLowerCase())}function sc(t){let e=t.filter(o=>o&&typeof o.id=="string"&&o.id.trim().length>0);if(e.length===0||bp.every(o=>e.some(i=>up(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 wp){let i=n.find(s=>up(o,s.id));if(i)return i.id}return n[0].id}function Sn(){return{default:null,roles:{}}}function j$(t,e,r=gp){let n=t?.roles?.[e];if(typeof n=="string"&&n.trim().length>0)return n.trim();if(t?.default&&t.default.trim().length>0)return t.default.trim();let o=yp[r]?.[e];return o||(Ao[e]??mp)}function N$(t){let e=t?.provider;return typeof e=="string"&&e.trim().length>0?e.trim():it}function O$(t){let e=Sn();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.provider;typeof n=="string"&&n.trim().length>0&&(e.provider=n.trim());let o=r.models;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o))typeof s!="string"||s.trim().length===0||(i==="default"?e.default=s.trim():e.roles[i]=s.trim());return e}function En(){return{default:null,roles:{}}}function L$(t,e){let r=t?.roles?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():t?.default&&t.default.trim().length>0?t.default.trim():_o[e]}function M$(t){let e=En();if(!t||typeof t!="object")return e;let r=t.llm;if(!r||typeof r!="object")return e;let n=r.effort;if(!n||typeof n!="object")return e;for(let[o,i]of Object.entries(n))typeof i!="string"||i.trim().length===0||(o==="default"?e.default=i.trim():e.roles[o]=i.trim());return e}function D$(t){return t.default===null&&Object.keys(t.roles).length===0?null:JSON.stringify(t)}function U$(t){if(!t)return En();try{let e=JSON.parse(t);if(!e||typeof e!="object")return En();let r=e,n=En();typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return En()}}function B$(t){let e=typeof t.provider=="string"&&t.provider.trim().length>0&&t.provider.trim()!==it;if(t.default===null&&Object.keys(t.roles).length===0&&!e)return null;let{provider:r,...n}=t;return JSON.stringify(e?{provider:r.trim(),...n}:n)}function F$(t){if(!t)return Sn();try{let e=JSON.parse(t);if(!e||typeof e!="object")return Sn();let r=e,n=Sn();typeof r.provider=="string"&&r.provider.trim().length>0&&(n.provider=r.provider.trim()),typeof r.default=="string"&&(n.default=r.default);let o=r.roles;if(o&&typeof o=="object")for(let[i,s]of Object.entries(o))typeof s=="string"&&(n.roles[i]=s);return n}catch{return Sn()}}var it,ic,Ce,Vt,Rn,Li,dp,pp,fp,Mi,Ao,mp,hp,gp,yp,wp,bp,kp,Di,_o,ac=E(()=>{"use strict";oc();it="claude",ic=[it],Ce="opus",Vt="sonnet",Rn="haiku",Li=[Ce,Vt,Rn],dp="build-discovery",pp="code-review-verify",fp=[dp,pp],Mi=[...rc,...fp],Ao={analyze:Ce,implement:Ce,"resolve-conflict":Ce,rework:Ce,estimate:Vt,build:Rn,"build-discovery":Ce,"code-review":Ce,"code-review-verify":Vt,draft:Vt,index:Ce,backfill:Ce,analysis:Ce,chat:Ce,config:Ce,observer:Ce,council:Ce,testing:Ce},mp=Ce,hp=["express","balanced","full"],gp="full",yp={express:{"code-review":Vt,"code-review-verify":Rn},balanced:{implement:Vt,"code-review":Vt,"code-review-verify":Rn},full:{}};wp=[Ce,Vt,Rn],bp=Array.from(new Set(Object.values(Ao)));kp=["low","medium","high","xhigh"],Di=kp,_o={build:"low",estimate:"low",draft:"medium",index:"medium","code-review-verify":"medium"}});function zt(t){return G$.has(t)?!0:K$.some(e=>t.startsWith(e))}function Ui(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Gr(t,e){if(t!=null){if(typeof t!="string")throw new Error(`${e} must be a string`);return t}}function lc(t,e){if(t!=null){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${e} must be a number`);return t}}function dc(t,e){let r=Ui(e,"action definition"),n=t.replace(/\.(yml|yaml)$/i,""),o=Gr(r.id,"id")??n;if(!cc.test(o))throw new Error(`id must match ${cc} (got "${o}")`);if(o!==n)throw new Error(`id "${o}" must match the file name ("${n}")`);let i=Gr(r.title,"title")?.trim()||o,s;if(r.env!==void 0&&r.env!==null){let p=Ui(r.env,"env");s={};for(let[d,f]of Object.entries(p)){if(!st.test(d))throw new Error(`env name "${d}" must match ${st}`);if(typeof f!="string"&&typeof f!="number"&&typeof f!="boolean")throw new Error(`env.${d} must be a scalar`);s[d]=String(f)}}let a,c=r.params;if(c!=null){if(!Array.isArray(c))throw new Error("params must be a list");if(c.length>vp)throw new Error(`too many params (max ${vp})`);let p=new Set;a=c.map((d,f)=>H$(d,f,p))}let l=r.steps;if(!Array.isArray(l)||l.length===0)throw new Error("steps must be a non-empty list");if(l.length>$p)throw new Error(`too many steps (max ${$p})`);let u=l.map((p,d)=>{let f=Ui(p,`steps[${d}]`),m=Gr(f.run,`steps[${d}].run`);if(!m||m.trim().length===0)throw new Error(`steps[${d}].run is required`);let y=Gr(f.name,`steps[${d}].name`),b=lc(f.timeout_sec,`steps[${d}].timeout_sec`);if(b!==void 0&&(!Number.isInteger(b)||b<=0))throw new Error(`steps[${d}].timeout_sec must be a positive integer`);return{run:m,...y?{name:y}:{},...b!==void 0?{timeout_sec:b}:{}}});return{id:o,title:i,...s?{env:s}:{},...a?{params:a}:{},steps:u}}function H$(t,e,r){let n=Ui(t,`params[${e}]`),o=Gr(n.name,`params[${e}].name`);if(!o||!st.test(o))throw new Error(`params[${e}].name must match ${st}`);if(r.has(o))throw new Error(`duplicate param "${o}"`);r.add(o);let i=n.type;if(i!=="string"&&i!=="enum"&&i!=="number"&&i!=="boolean")throw new Error(`params[${e}].type must be string | enum | number | boolean`);let s;if(i==="enum"){let f=n.enum;if(!Array.isArray(f)||f.length===0||!f.every(m=>typeof m=="string"))throw new Error(`params[${e}].enum must be a non-empty string list`);s=f}let a=Gr(n.label,`params[${e}].label`),c=Gr(n.help,`params[${e}].help`),l=n.required===!0,u=lc(n.min,`params[${e}].min`),p=lc(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 pc(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 st,G$,K$,uc,cc,vp,$p,fc=E(()=>{"use strict";st=/^[A-Z][A-Z0-9_]*$/,G$=new Set(["GH_TOKEN","GITHUB_TOKEN","GITLAB_TOKEN"]),K$=["BITBUCKET_","YOUTRACK_","CLAUDE_","INPUT_"];uc=600,cc=/^[a-z0-9-]+$/,vp=32,$p=64});function W$(t){let e=t.toLowerCase(),r="";for(let o of e)r+=Object.prototype.hasOwnProperty.call(xp,o)?xp[o]:o;return r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50).replace(/-+$/g,"")}function q$(t,e,r){let o=(t&&t.includes("<TASK_ID>")?t:Sp).replace(/<TASK_ID>/g,e.toLowerCase()).replace(/<SLUG>/g,r??"");return o=o.replace(/-{2,}/g,"-").replace(/\/{2,}/g,"/").replace(/-\//g,"/").replace(/\/-/g,"/").replace(/^[-/]+|[-/]+$/g,""),o}function Y$(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function or(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 mc(t){if(!t||typeof t!="object")return null;let e=t,r=typeof e.owner=="string"?e.owner.trim():"",n=typeof e.repo=="string"?e.repo.trim():typeof e.repoName=="string"?e.repoName.trim():"",o=typeof e.host=="string"?e.host.trim():"";return!r||!n||o!=="github"&&o!=="gitlab"&&o!=="bitbucket"?null:{host:o,owner:r,repoName:n}}function hc(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function Dt(t){return`${t}${Ep}`}var Sp,R0,xp,ir,Ep,gc=E(()=>{"use strict";Sp="codepipe/<TASK_ID>",R0=50,xp={\u0430:"a",\u0431:"b",\u0432:"v",\u0433:"g",\u0434:"d",\u0435:"e",\u0451:"e",\u0436:"zh",\u0437:"z",\u0438:"i",\u0439:"y",\u043A:"k",\u043B:"l",\u043C:"m",\u043D:"n",\u043E:"o",\u043F:"p",\u0440:"r",\u0441:"s",\u0442:"t",\u0443:"u",\u0444:"f",\u0445:"h",\u0446:"c",\u0447:"ch",\u0448:"sh",\u0449:"sch",\u044A:"",\u044B:"y",\u044C:"",\u044D:"e",\u044E:"yu",\u044F:"ya"};ir=/^[a-z][a-z0-9-]{1,30}$/,Ep="-codepipe-ctx"});function V$(t){return t==="simple"||t==="gitflow"||t==="release"}function yc(t){return t==="integration"||t==="stable"||t==="release_pattern"}function z$(t){let e=t.endsWith("/*")?t.slice(0,-2):t;return or(e)}function X$(t){let e=new Set(Bi[t.flow].roles);for(let r of Object.keys(t.branchTypes??{}))yc(r)&&e.add(r);return e}function sr(t){if(t==null)return{config:null,errors:[]};let e=[];if(typeof t!="object"||Array.isArray(t))return{config:null,errors:["git: must be a mapping"]};let r=t,n=r.flow;if(!V$(n))return e.push(`git.flow must be one of simple | gitflow | release (got ${JSON.stringify(n)})`),{config:null,errors:e};let o=n,i={},s=r.branch_types??r.branchTypes;if(s!==void 0)if(typeof s!="object"||s===null||Array.isArray(s))e.push("git.branch_types must be a mapping of role \u2192 name/pattern");else for(let[d,f]of Object.entries(s)){if(!yc(d)){e.push(`git.branch_types: unknown role "${d}"`);continue}if(typeof f!="string"||!Rp(d,f)){e.push(`git.branch_types.${d}: invalid branch name/pattern ${JSON.stringify(f)}`);continue}i[d]=f}let a=new Set(Bi[o].roles);for(let d of Object.keys(i))a.add(d);let c={},l=r.branches;if(l!==void 0)if(typeof l!="object"||l===null||Array.isArray(l))e.push("git.branches must be a mapping of role \u2192 branch name");else for(let[d,f]of Object.entries(l)){if(!yc(d)){e.push(`git.branches: unknown role "${d}"`);continue}if(!a.has(d)){e.push(`git.branches.${d}: role not part of flow "${o}"`);continue}if(typeof f!="string"||!Rp(d,f)){e.push(`git.branches.${d}: invalid branch name/pattern ${JSON.stringify(f)}`);continue}c[d]=f}let u,p=r.commit;if(p!==void 0)if(typeof p!="object"||p===null||Array.isArray(p))e.push("git.commit must be a mapping");else{let d=p,f=d.subject,m=d.subject_max??d.subjectMax,y,b;f!==void 0&&typeof f!="string"?e.push("git.commit.subject must be a string"):typeof f=="string"&&f.trim()!==""&&(y=f),m!==void 0&&(typeof m!="number"||!Number.isInteger(m)||m<1?e.push("git.commit.subject_max must be a positive integer"):b=m),u={...y!==void 0?{subject:y}:{},...b!==void 0?{subjectMax:b}:{}}}return e.length>0?{config:null,errors:e}:{config:{flow:o,branches:c,...Object.keys(i).length>0?{branchTypes:i}:{},...u?{commit:u}:{}},errors:[]}}function Rp(t,e){return t==="release_pattern"?z$(e):or(e)}function J$(t,e,r){let n=r??"main",o=e??t;if(!o)return{flow:"simple",integration:n};let i=X$(o),s=u=>o.branches[u]??o.branchTypes?.[u],a=s("integration")??n,c=i.has("stable")?s("stable"):void 0,l=i.has("release_pattern")?s("release_pattern"):void 0;return{flow:o.flow,integration:a,...c?{stable:c}:{},...l?{releasePattern:l}:{}}}function Tn(t){return t.gitFlow?.integration??t.defaultBranch??"main"}function Z$(t,e){return e??Tn(t)}function Tp(t,e){if(e.endsWith("/*")){let r=e.slice(0,-1);return t.startsWith(r)&&t.length>r.length}return t===e}function bc(t,e){return e.flow==="simple"?!1:!!(t===e.integration||e.stable&&t===e.stable||e.releasePattern&&Tp(t,e.releasePattern))}function jo(t){let e=t.branches??[],r=e.some(s=>/^release\//.test(s)),n=e.includes("develop")||e.includes("dev"),o=r?"release":n?"gitflow":"simple",i={integration:Q$(o,t)};if(o!=="simple"){let s=ex(t,i.integration??"");s&&(i.stable=s)}return o==="release"&&(i.release_pattern="release/*"),{flow:o,branches:i}}function Q$(t,e){let r=e.branches??[];if(t!=="simple"){if(r.includes("develop"))return"develop";if(r.includes("dev"))return"dev"}return e.defaultBranch??r[0]??""}function ex(t,e){let r=t.branches??[],n=t.defaultBranch;if(n&&(n==="main"||n==="master")&&n!==e)return n;if(r.includes("main")&&e!=="main")return"main";if(r.includes("master")&&e!=="master")return"master"}function kc(t,e){if(t.flow==="simple")return!1;if(t.flow!==e.flow)return!0;let r=t.branches,n=e.branches;return(r.integration??"")!==(n.integration??"")||(r.stable??"")!==(n.stable??"")||(r.release_pattern??"")!==(n.release_pattern??"")}var Bi,wc,vc=E(()=>{"use strict";gc();Bi={simple:{roles:["integration"]},gitflow:{roles:["integration","stable"]},release:{roles:["integration","stable","release_pattern"]}},wc=Object.keys(Bi)});function Ip(){return{primary:ke,context:ke,tasks:ke,docs:ke,code_comments:ke,chat:ke,code_review:ke,commits:ke}}function Cp(t){return!t||t.trim().length===0||t.trim().toLowerCase()===ke}function tx(t){if(typeof t!="string")return ke;let e=t.trim().replace(/\s+/g," ");return e.length===0||e.length>40||e.toLowerCase()===ke?ke:e}function rx(t){let e=Ip();if(!t||typeof t!="object")return e;let r=t.language;if(!r||typeof r!="object"||Array.isArray(r))return e;let n=r;for(let o of No)e[o]=tx(n[o]);return e}function nx(t){return No.every(e=>Cp(t[e]))}var ke,No,In,Oo,$c=E(()=>{"use strict";ke="auto",No=["primary","context","tasks","docs","code_comments","chat","code_review","commits"],In=["English","Russian","German","Spanish","French","Portuguese","Italian","Chinese","Japanese","Korean"],Oo=40});function Fi(t=Pp){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...Fi(r.groups));return e}function Ap(t,e){let r=JSON.stringify(e);return Fi().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function _p(t){let e=JSON.stringify(t);return Fi().find(r=>JSON.stringify(r.path)===e)}function Rc(t){let e=Ap(t.file,t.path)??_p(t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:e.maxLength!==void 0&&i.length>e.maxLength?{ok:!1,error:`${e.id} must be \u2264 ${e.maxLength} chars`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)?{ok:!1,error:`${e.id} must be a number`}:!e.float&&!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}case"string_map":{if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,error:`${e.id} must be a name\u2192value map`};let i=Object.entries(r);if(i.length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty map`};if(i.length>xc)return{ok:!1,error:`${e.id} must have \u2264 ${xc} entries`};let s={};for(let[a,c]of i){if(!st.test(a))return{ok:!1,error:`${e.id}: name "${a}" must match ${st}`};if(zt(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>Sc)return{ok:!1,error:`${e.id}: value of "${a}" must be \u2264 ${Sc} chars`};s[a]=c}return{ok:!0,field:e,value:s}}}}var ox,ix,xc,Sc,Ec,Pp,jp=E(()=>{"use strict";fc();vc();ac();Qa();$c();ox={primary:"Primary language",context:"Context documents",tasks:"Tracker issues",docs:"Repo documentation",code_comments:"Code comments",chat:"Agent chat",code_review:"Code review comments",commits:"Commits & branches"},ix={primary:"The project's main language (agent status notes ride it). Empty \u21D2 auto.",context:"Knowledge, ADRs and task artifacts in the Context Repo. Empty \u21D2 auto.",tasks:"Issue titles/bodies the agent drafts. Empty \u21D2 auto.",docs:"Documentation changes in the project repos. Empty \u21D2 auto.",code_comments:"New code comments the agent writes. Empty \u21D2 auto.",chat:"The interactive task-drafting chat. Empty/auto \u21D2 mirror the user's messages.",code_review:"Review findings and PR comments. Empty \u21D2 follows the tracker-issues language.",commits:"Commit/PR subject & branch slug. Empty \u21D2 follows the tracker-issues language."},xc=64,Sc=2e3,Ec=2e3,Pp=[{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:"git",label:"Git workflow",help:"Branching flow: which branch feature work targets, and the deterministic commit subject.",fields:[{id:"git.flow",file:"project.yaml",path:["git","flow"],type:"enum",label:"Flow preset",nullable:!0,suggestions:[...wc],help:"simple \u2014 one branch (default); gitflow \u2014 integration + stable; release \u2014 gitflow + release/* branches. Empty \u21D2 remove the key (only valid when the rest of the git: section is cleared too)."},{id:"git.branches.integration",file:"project.yaml",path:["git","branches","integration"],type:"string",label:"Integration branch",nullable:!0,help:"The branch feature work targets (e.g. develop). Empty \u21D2 the repo's default branch."},{id:"git.branches.stable",file:"project.yaml",path:["git","branches","stable"],type:"string",label:"Stable branch",nullable:!0,help:"The production branch (e.g. master). Only part of the gitflow/release presets."},{id:"git.branches.release_pattern",file:"project.yaml",path:["git","branches","release_pattern"],type:"string",label:"Release branch pattern",nullable:!0,help:"Glob for release branches (e.g. release/*). Only part of the release preset."},{id:"git.commit.subject",file:"project.yaml",path:["git","commit","subject"],type:"string",label:"Commit subject template",nullable:!0,maxLength:200,help:"First-line template with {key} / {summary} placeholders. Empty \u21D2 default {key}: {summary}. Requires a git: section (set Flow preset, e.g. simple)."},{id:"git.commit.subject_max",file:"project.yaml",path:["git","commit","subject_max"],type:"number",label:"Commit subject length cap",nullable:!0,min:1,max:500,help:"Length cap for the rendered subject line. Empty \u21D2 72."}]},{id:"llm",label:"LLM",fields:[{id:"llm.provider",file:"local.yaml",path:["llm","provider"],type:"enum",label:"Provider",nullable:!1,suggestions:[...ic],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:"local.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Li],help:"Overrides the recommended defaults for every role not listed below."},...Mi.map(t=>({id:`llm.models.${t}`,file:"local.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Li],help:`recommended: ${Ao[t]} (the workflow preset may set a cheaper default \u2014 an explicit value here overrides both)`}))]},{id:"llm.effort",label:"Reasoning effort by role",help:"Reasoning effort per pipeline stage (Claude Code --effort). Empty \u21D2 the mechanical roles run lowered (build/estimate: low; draft/index/code-review-verify: medium) and every other role keeps the backend default.",fields:[{id:"llm.effort.default",file:"project.yaml",path:["llm","effort","default"],type:"enum",label:"default (catch-all)",nullable:!0,suggestions:[...Di],help:"Overrides the recommended lowerings for every role not listed below."},...Mi.map(t=>({id:`llm.effort.${t}`,file:"project.yaml",path:["llm","effort",t],type:"enum",label:t,nullable:!0,suggestions:[...Di],help:_o[t]?`recommended: ${_o[t]}`:"recommended: backend default"}))]}]},{id:"apply.style",label:"Commits & PRs",help:"Instructions for the AI agent on how to write commit messages and PR descriptions. Empty \u21D2 built-in templates.",fields:[{id:"apply.commit_style",file:"project.yaml",path:["apply","commit_style"],type:"string",label:"Commit message style",nullable:!0,multiline:!0,maxLength:Ec,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:Ec,help:`e.g. "implementation details, bullet list of what was done, in the tracker's language". Empty \u21D2 the default PR body.`}]},{id:"apply.delivery",label:"Delivery & merge",help:"How a finished change reaches the repository: with or without a pull request, and who merges it.",fields:[{id:"apply.pull_request",file:"project.yaml",path:["apply","pull_request"],type:"boolean",label:"Open a pull request",nullable:!1,help:"On (default): the task branch is pushed and a pull request is opened \u2014 the change is reviewable in the git host and keeps a history of review comments. Off: no PR at all; the branch is merged into the default branch directly, and the agent's review remarks live only in the dashboard and the Context Repo."},{id:"apply.done",file:"project.yaml",path:["apply","done"],type:"enum",label:"Task is done when",nullable:!1,suggestions:["merge","branch"],help:"merge (default): the task is finished only once its change lands in the default branch. branch: the task ends at the pushed branch (plus the PR, if enabled) and nothing is merged for you."},{id:"apply.auto_merge",file:"project.yaml",path:["apply","auto_merge"],type:"enum",label:"Auto-merge pull requests",nullable:!1,suggestions:["off","on_ci_green"],help:"Applies to the pull-request path only. off (default): the merge waits for you (Approve on the task card). on_ci_green: as soon as the PR is open, conflict-free and its CI is green, CodePipe merges it \u2014 changes reach the default branch with no further review from you. Requires full automation; branch protection on the host still applies (a refused merge parks the task). Without pull requests, full automation merges the branch itself and this switch does not apply."}]},{id:"variables",label:"Variables",help:"Non-secret env vars for custom actions (RUN tab). Secrets go via the sealed Secrets form on the Tokens section instead.",fields:[{id:"variables",file:"project.yaml",path:["variables"],type:"string_map",label:"Variables",nullable:!0,help:"NAME=value pairs, one per line. Names are env-style (A-Z, 0-9, _); reserved credential names are refused."}]},{id:"testing",label:"Testing",help:"An optional phase after code review: writes the test plan you run in the morning and reports what it could verify.",fields:[{id:"testing.enabled",file:"project.yaml",path:["testing","enabled"],type:"boolean",nullable:!1,label:"Run the testing phase",help:"Off by default. When on, a task passing code review goes through a test pass before the PR: it derives TESTPLAN.md from the plan's requirements and reports per requirement what it could verify. A requirement it finds broken sends the change back for a fix (bounded below)."},{id:"testing.max_iterations",file:"project.yaml",path:["testing","max_iterations"],type:"number",nullable:!0,min:1,max:10,label:"Fix rounds before stopping",help:"How many times a failed test pass may send the change back before the task waits for you. Empty \u21D2 2."}]},{id:"code_review",label:"Code review",help:"One review mechanism for the pipeline's own changes and for developers' branches (the review column); they differ only in where the findings go.",fields:[{id:"code_review.verify_pass",file:"project.yaml",path:["code_review","verify_pass"],type:"boolean",nullable:!1,label:"Verifier pass (precision)",help:"On by default. A second, narrow agent checks every finding against the code (real? re-grade) before it costs a rework round or reaches a developer; the findings threshold below keeps small rounds cheap."},{id:"code_review.verify_min_findings",file:"project.yaml",path:["code_review","verify_min_findings"],type:"number",nullable:!0,min:1,label:"Verifier threshold (findings)",help:"The verifier runs only when a round carries at least this many actionable findings \u2014 1-2 are cheap to absorb, noise scales with volume. Empty = 3; 1 = verify every round."},{id:"code_review.max_blocking",file:"project.yaml",path:["code_review","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (internal)",help:"Max blocker findings that keep their power in the pipeline's own review; the rest are demoted to major, weakest confidence first. Empty = 5."},{id:"code_review.external.max_blocking",file:"project.yaml",path:["code_review","external","max_blocking"],type:"number",nullable:!0,label:"Blocking budget (external)",help:"The same budget for a developer's branch review \u2014 tighter by default because a human reads these. Empty = 3."}]},{id:"skills",label:"Skills",help:"Reusable procedures the agent can invoke instead of improvising. Only their names and one-line descriptions sit in the prompt; the steps load when a skill is used.",fields:[{id:"skills.from_bundled",file:"project.yaml",path:["skills","from_bundled"],type:"boolean",nullable:!1,label:"Use the skills shipped with CodePipe",help:"On by default. General procedures maintained with the product."},{id:"skills.from_context_repo",file:"project.yaml",path:["skills","from_context_repo"],type:"boolean",nullable:!1,label:"Use this project's skills",help:"On by default. Skills the team writes in the context repository under `skills/<name>/SKILL.md`. These override a bundled skill of the same name."},{id:"skills.from_project_repo",file:"project.yaml",path:["skills","from_project_repo"],type:"boolean",nullable:!1,label:"Use the code repository's skills",help:"On by default. `.claude/skills/` inside the project repositories \u2014 the skills your developers already use locally. These win over both other sources."}]},{id:"quality",label:"Quality block",help:"Skip the whole quality block (build + code review) when a change touches only safe paths.",fields:[{id:"quality.skip_paths",file:"project.yaml",path:["quality","skip_paths"],type:"string_list",nullable:!0,label:"Skip paths (gitignore-style)",help:"When every changed file across all repos matches these globs, build and code review are skipped and the change goes straight to apply. One file outside the list runs both as usual. Use ! to re-include (e.g. !schema/**/*.md). Empty = never skip."}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (on by default; orthogonal to automation).",fields:[{id:"gates.require_approval",file:"local.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on (default), the observer's intake plan waits for your APPROVE & START before the batch runs. Off \u21D2 conveyor: the batch starts automatically on the observer's plan. Either way every task passes the observer intake first."},{id:"observer.debounce_seconds",file:"project.yaml",path:["observer","debounce_seconds"],type:"number",label:"Intake window (seconds)",nullable:!0,min:5,max:3600,help:"How long the queue collects newly staged tasks before the observer reviews them as one batch. Empty \u21D2 60."},{id:"observer.fast_path",file:"project.yaml",path:["observer","fast_path"],type:"boolean",label:"Fast path for trivial tasks",nullable:!1,help:"On by default. A single small task with no links skips the observer's LLM pass and is routed by rules (noted in its journal as routed without review)."}]},{id:"council",label:"Council",help:"Several roles examine the same subject in parallel, each in its own process; a final session weighs their written opinions. Costs several agent runs per use \u2014 off by default, enable per phase.",fields:[{id:"council.questions",file:"project.yaml",path:["council","questions"],type:"boolean",nullable:!1,label:"Council on blocking questions",help:"Off (default): an agent's blocking question is answered by a single session, which keeps full automation moving cheaply. On: the council's roles each write an independent opinion first, and the answering session weighs them."},{id:"council.code_review",file:"project.yaml",path:["council","code_review"],type:"boolean",nullable:!1,label:"Council on code review",help:"Off (default): one reviewer session judges the change alone. On: the project's critic roles each review the change in their own parallel process first, and the reviewer session weighs their written findings into the verdict. Applies to the internal and the external review; the verifier pass always runs solo."},{id:"council.max_parallel",file:"project.yaml",path:["council","max_parallel"],type:"number",nullable:!0,min:1,max:5,label:"Max parallel roles",help:"How many role processes run at once (the rest wait their turn). Empty \u21D2 3; hard ceiling 5."}]},{id:"workflow",label:"Workflow",help:"How much pipeline a task gets. A preset is a set of defaults \u2014 any explicit setting below always wins over it.",fields:[{id:"workflow.preset",file:"project.yaml",path:["workflow","preset"],type:"enum",nullable:!1,suggestions:["express","balanced","full"],label:"Preset",help:"express \u2014 no analysis phase, no review: one implementation session on the capable model (cheapest, for small clear tasks). balanced \u2014 every phase, cheaper models for implementation and review. full \u2014 the classic pipeline on the capable model."},{id:"workflow.observer_routing",file:"project.yaml",path:["workflow","observer_routing"],type:"boolean",nullable:!1,label:"Observer routes presets",help:"Off (default): every task runs the project's preset. On: the intake observer may assign a preset per task (a small clear task goes express, a risky one goes full), within the allowed list below; your explicit pick on a queued task always wins. A task that gets stuck on express escalates to the full pipeline automatically."},{id:"workflow.allowed_presets",file:"project.yaml",path:["workflow","allowed_presets"],type:"string_list",nullable:!0,label:"Presets the observer may use",help:"Limits observer routing, e.g. only balanced and full (no express). Empty \u21D2 all three."},{id:"analysis.enabled",file:"project.yaml",path:["analysis","enabled"],type:"boolean",nullable:!1,label:"Analysis phase",help:"Whether a task starts with a dedicated analysis pass (plan + open questions) before implementation. Off \u21D2 the implementer works straight from the task text and the context pack; an explicit value here overrides the preset."}]},{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:"local.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]},{id:"language",label:"Language",help:"Languages the agent writes in, per area. Empty \u21D2 auto: mirror the language of the user's material.",fields:No.map(t=>({id:`language.${t}`,file:"project.yaml",path:["language",t],type:"string",label:ox[t],nullable:!0,maxLength:40,suggestions:t==="chat"?[ke,...In]:[...In],help:ix[t]}))},{id:"context.model",label:"Project map",help:"Parameters of the project map (built from git history by the CLI). Empty fields keep the defaults.",fields:[{id:"context.model.enabled",file:"project.yaml",path:["context","model","enabled"],type:"boolean",label:"Enable in the pipeline",nullable:!1,help:"On by default. Agents are asked to record intent annotations and receive an assembled context pack built from the project map. Off \u21D2 the pipeline ignores the map entirely and behaves exactly as if the feature were absent."},{id:"context.model.pack.idf_penalty",file:"project.yaml",path:["context","model","pack","idf_penalty"],type:"boolean",label:"Demote ubiquitous files in the pack",nullable:!1,help:"On by default. Files that reached the pack only through STATISTICAL co-change (not direct task evidence) are ranked down in proportion to how many past tasks touched them, so the budget goes to task-specific paths. Off restores pure activation order."},{id:"context.model.prompt.pack",file:"project.yaml",path:["context","model","prompt","pack"],type:"boolean",nullable:!1,label:"Give agents the context pack",help:"On by default. The assembled pack costs up to ~4000 tokens on every task of the analyze / estimate / implement / rework roles. Turning it off keeps the map building and stops the spend \u2014 the way to see what the pack is actually worth on this project."},{id:"context.model.prompt.annotations",file:"project.yaml",path:["context","model","prompt","annotations"],type:"boolean",nullable:!1,label:"Ask agents for intent annotations",help:"On by default. Adds the annotations block to the implement and rework prompts \u2014 the layer that records WHY the code is shaped this way. Cheap, and worth accumulating even while the pack is off."},{id:"context.index.hub",file:"project.yaml",path:["context","index","hub"],type:"enum",label:"Search index on the server",nullable:!0,suggestions:["off","metadata"],help:"off (default): search runs on your machine, nothing is uploaded. metadata: paths, labels and task texts (never code) are mirrored to the server so search and structure stay available while your machine is offline. Switching back to off deletes the mirrored rows."},{id:"context.model.issue_key_pattern",file:"project.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:"project.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 ${mt.windowCommits}.`},{id:"context.model.cochange.commit_file_cap",file:"project.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 ${mt.commitFileCap}.`},{id:"context.model.cochange.support_min",file:"project.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 ${mt.supportMin}.`},{id:"context.model.cochange.jaccard_min_pct",file:"project.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 ${mt.jaccardMinPct}.`},{id:"context.model.cochange.half_life_days",file:"project.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 ${mt.halfLifeDays} (~9 months).`},{id:"context.model.cochange.top_k",file:"project.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 ${mt.topK}.`}]},{id:"rate_limit",label:"Rate limit",help:"Automatic project pause as the LLM usage window fills up.",fields:[{id:"rate_limit.auto_pause.enabled",file:"local.yaml",path:["rate_limit","auto_pause","enabled"],type:"boolean",nullable:!1,label:"Pause the project near the limit",help:"On (default): when window utilization reaches the threshold, the project is paused (same pause as the manual one) and you get an email \u2014 the remaining window stays available for your own work. Off: agents keep working until the provider actually runs out."},{id:"rate_limit.auto_pause.threshold",file:"local.yaml",path:["rate_limit","auto_pause","threshold"],type:"number",float:!0,nullable:!0,min:.05,max:1,label:"Pause threshold (share of the window)",help:"Fraction of the usage window at which the pause fires; the rest (1 \u2212 threshold) is your manual-work reserve. Empty \u21D2 0.75."}]},{id:"context.job_logs",label:"Job transcripts",help:"Whether the raw agent transcript of each job is kept in the Context Repo.",fields:[{id:"context.job_logs.enabled",file:"project.yaml",path:["context","job_logs","enabled"],type:"boolean",label:"Keep transcripts in the Context Repo",nullable:!1,help:"Off (default): the transcript is discarded after the run \u2014 nothing lands in the Context Repo. On: each job's raw transcript is committed as tasks/<KEY>/logs/job-<id>.jsonl for post-mortem debugging."}]}]});var Np=E(()=>{"use strict"});function Op(t){if(t==null)return[];if(!Array.isArray(t))return null;let e=[];for(let r of t){if(typeof r!="string"||r.trim().length===0)return null;e.push(r.trim())}return e}function Ic(t){let{name:e,body:r,origin:n}=t;if(!Tc.test(e))return{ok:!1,error:`role name must match ${Tc} (got "${e}")`};if(r.trim().length===0)return{ok:!1,error:"role body is empty \u2014 the body IS the role's prompt"};let o=t.frontmatter;if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:"missing or malformed frontmatter block"};let i=o,s=i.description;if(typeof s!="string"||s.trim().length===0)return{ok:!1,error:"description is required (one line: what this role looks for)"};if(s.length>300)return{ok:!1,error:"description must be \u2264 300 characters"};let a=Op(i.refs);if(a===null)return{ok:!1,error:"refs must be a list of non-empty paths"};if(a.length>10)return{ok:!1,error:"refs must list at most 10 files \u2014 a role is a narrow view"};for(let f of a)if(f.startsWith("/")||f.includes(".."))return{ok:!1,error:`ref "${f}" must be a path inside the Context Repo`};let c=Op(i.scenarios);if(c===null)return{ok:!1,error:"scenarios must be a list"};let l=[];for(let f of c){if(!Gi.includes(f))return{ok:!1,error:`unknown scenario "${f}" \u2014 one of: ${Gi.join(", ")}`};l.includes(f)||l.push(f)}if(l.length===0)return{ok:!1,error:`scenarios must name at least one of: ${Gi.join(", ")}`};let u=i.model;if(u!==void 0&&(typeof u!="string"||u.trim().length===0))return{ok:!1,error:"model must be a non-empty string when set"};let p=i.provider;if(p!==void 0&&(typeof p!="string"||p.trim().length===0))return{ok:!1,error:"provider must be a non-empty string when set"};let d=i.enabled;return d!==void 0&&typeof d!="boolean"?{ok:!1,error:"enabled must be true or false"}:{ok:!0,role:{name:e,description:s.trim(),...typeof u=="string"?{model:u.trim()}:{},...typeof p=="string"?{provider:p.trim()}:{},refs:a,scenarios:l,enabled:d!==!1,body:r.trim(),origin:n}}}function Cc(t,e){let r=new Map;for(let n of t)r.set(n.name,n);for(let n of e)r.set(n.name,n);return[...r.values()].sort((n,o)=>n.name<o.name?-1:n.name>o.name?1:0)}function Pc(t,e){return t.filter(r=>r.enabled&&r.scenarios.includes(e))}var Gi,Tc,M0,D0,Lp=E(()=>{"use strict";Gi=["plan_review","code_review","council"],Tc=/^[a-z][a-z0-9-]{1,39}$/,M0=10,D0=300});function Ac(t){return Mp.includes(t)}function _c(t){return`prompts/${t}.md`}var Mp,Dp=E(()=>{"use strict";Mp=["analysis","analyze","backfill","build","chat","code-review","code-review-external","code-review-fix","code-review-verify","config","council","draft","estimate","implement","implement-direct","index","observer","resolve-conflict","review-comment","rework","testing"]});function Nc(t){if(!jc.test(t.name))return{ok:!1,error:`skill directory name must match ${jc}`};if(t.body.trim().length===0)return{ok:!1,error:"SKILL.md has no body \u2014 the body IS the procedure"};let e=t.frontmatter;if(!e||typeof e!="object"||Array.isArray(e))return{ok:!1,error:"SKILL.md has no frontmatter block"};let r=e.description;return typeof r!="string"||r.trim().length===0?{ok:!1,error:"description is required \u2014 it is what decides when the skill fires"}:r.length>300?{ok:!1,error:"description must be \u2264 300 characters"}:{ok:!0,skill:{name:t.name,description:r.trim()}}}function Oc(t,e,r){let n=new Map;for(let o of[...t,...e,...r])n.set(o.name,o);return[...n.values()].sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}function Bp(t){let e=t.trim(),r=e.lastIndexOf("@"),n=r===-1?e:e.slice(0,r),o=r===-1?"":e.slice(r+1).trim();if(!sx.test(n))return{ok:!1,error:`"${t}": expected <owner>/<repo>[@<40-hex sha>]`};let i=Up.find(s=>s.repo.toLowerCase()===n.toLowerCase());return o&&!ax.test(o)?{ok:!1,error:`"${t}": pin to a full 40-character commit sha \u2014 a branch or tag can change under you`}:!i&&!o?{ok:!1,error:`"${t}": a third-party marketplace must be pinned to a commit (<owner>/<repo>@<sha>). Its skills run beside your code with the agent's token.`}:{ok:!0,source:{repo:n,sha:o,name:i?.name??n.replace("/","-").toLowerCase(),official:!!i}}}function cx(t){let e=[],r=[],n=new Set;for(let o of t){if(!o.trim())continue;let i=Bp(o);if(!i.ok){r.push(i.error);continue}n.has(i.source.name)||(n.add(i.source.name),e.push(i.source))}return{sources:e,errors:r}}function ux(t,e){let r=new Set(e.map(i=>i.name)),n={},o=[];for(let i of t){let s=i.trim();if(s){if(!lx.test(s)||!r.has(s.slice(s.indexOf("@")+1))){o.push(s);continue}n[s]=!0}}return{enabled:n,unknown:o}}var jc,F0,Up,sx,ax,lx,Fp=E(()=>{"use strict";jc=/^[a-z][a-z0-9-]{1,39}$/,F0=300;Up=[{repo:"anthropics/skills",name:"anthropic-agent-skills"},{repo:"anthropics/claude-plugins-official",name:"claude-plugins-official"}],sx=/^[A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*$/,ax=/^[0-9a-f]{40}$/;lx=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*$/});function Gp(t,e){if(t==null)return[];if(!Array.isArray(t)||t.length>e)return null;let r=[];for(let n of t){if(typeof n!="string"||n.trim().length===0)return null;r.push(n.trim())}return r}function dx(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"queue plan must be a JSON object"};let r=new Set(e),n=t,o=Gp(n.order,e.length);if(o===null)return{ok:!1,error:"order must be a list of task keys"};for(let m of o)if(!r.has(m))return{ok:!1,error:`order names ${m}, which is not in this batch`};if(new Set(o).size!==o.length)return{ok:!1,error:"order repeats a task key"};let i=e.filter(m=>!o.includes(m));if(o.length>0&&i.length>0)return{ok:!1,error:`order omits ${i.join(", ")}`};let s=n.tasks,a=[];if(s!=null){if(!Array.isArray(s))return{ok:!1,error:"tasks must be a list"};for(let m of s){if(!m||typeof m!="object")return{ok:!1,error:"each task entry must be an object"};let y=m,b=typeof y.taskKey=="string"?y.taskKey.trim():"";if(!r.has(b))return{ok:!1,error:`tasks names ${b||"(empty)"}, which is not in this batch`};let w=Gp(y.after,e.length);if(w===null)return{ok:!1,error:`${b}: after must be a list of task keys`};for(let T of w){if(!r.has(T))return{ok:!1,error:`${b}: after names ${T}, not in this batch`};if(T===b)return{ok:!1,error:`${b}: cannot come after itself`}}let k=typeof y.decisions=="string"?y.decisions.trim():"",x,h=y.workflow;if(h&&typeof h=="object"){let T=h,R=typeof T.preset=="string"?T.preset.trim():"";if(R==="express"||R==="balanced"||R==="full"){let v=typeof T.reason=="string"?T.reason.trim().slice(0,4e3):"";x={preset:R,reason:v}}}a.push({taskKey:b,decisions:k.slice(0,4e3),after:w,...x?{workflow:x}:{}})}}let c=[],l=n.conflicts;if(Array.isArray(l))for(let m of l){if(!m||typeof m!="object")continue;let y=m,b=typeof y.taskKey=="string"?y.taskKey.trim():"",w=typeof y.adr=="string"?y.adr.trim():"",k=typeof y.detail=="string"?y.detail.trim():"";!r.has(b)||!k||c.push({taskKey:b,adr:w,detail:k.slice(0,4e3)})}let u=[],p=n.related;if(Array.isArray(p))for(let m of p){if(!m||typeof m!="object")continue;let y=m,b=typeof y.taskKey=="string"?y.taskKey.trim():"",w=typeof y.detail=="string"?y.detail.trim():"";!b||!w||u.push({taskKey:b,detail:w.slice(0,4e3)})}let d=typeof n.summary=="string"?n.summary.trim().slice(0,4e3):"",f=n.deferBehind===!0;return{ok:!0,plan:{order:o,tasks:a,conflicts:c,related:u,summary:d,deferBehind:f}}}var K0,H0,Kp=E(()=>{"use strict";K0=4e3,H0=4e3});function px(t,e){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"council verdict must be a JSON object"};let r=t,n=r.unresolved===!0,o=typeof r.fork=="string"?r.fork.trim().slice(0,4e3):"";if(n)return o?{ok:!0,verdict:{answers:[],unresolved:!0,fork:o}}:{ok:!1,error:"an unresolved verdict must describe the fork"};let i=r.answers;if(!Array.isArray(i))return{ok:!1,error:"answers must be a list"};if(i.length!==e.length)return{ok:!1,error:`expected ${e.length} answer(s), got ${i.length}`};let s=[];for(let[a,c]of i.entries()){if(!c||typeof c!="object")return{ok:!1,error:`answer ${a+1} must be an object`};let l=c,u=typeof l.answer=="string"?l.answer.trim():"";if(!u)return{ok:!1,error:`answer ${a+1} is empty`};s.push({question:typeof l.question=="string"?l.question.trim():e[a],answer:u.slice(0,4e3),rationale:typeof l.rationale=="string"?l.rationale.trim().slice(0,4e3):""})}return{ok:!0,verdict:{answers:s,unresolved:!1,fork:""}}}var q0,Hp=E(()=>{"use strict";q0=4e3});function hx(t){let e=t.replace(/^#+\s*/,"").trim();for(let r of fx)if(r.re.test(e))return{kind:r.kind,letter:r.letter};return null}function Lc(t){let e=[],r=new Map,n="",o=null,i=null;for(let a of t.split(`
8
+ `)){let c=/^#{1,6}\s+(.*)$/.exec(a);if(c){n=c[1].trim(),o=hx(n),i=null;continue}let l=mx.exec(a);if(l&&o){let u=l[1];r.set(u,(r.get(u)??0)+1),i={id:u,kind:o.kind,text:l[2].trim(),section:n},e.push(i);continue}if(i&&a.trim()&&!/^#{1,6}\s/.test(a)&&!/^\s*[-*]\s/.test(a)){i.text=`${i.text}
9
+ ${a.trim()}`.trim();continue}a.trim()||(i=null)}let s=[...r.entries()].filter(([,a])=>a>1).map(([a])=>a);return{items:e,structured:e.length>=2&&s.length===0,duplicateIds:s}}function gx(t){let e={decision:"D",change:"C",assumption:"A",out_of_scope:"O",test:"T",procedure:"P"};return t.items.filter(r=>!r.id.startsWith(e[r.kind]))}function yx(t,e){let r=new Map(t.items.map(s=>[s.id,s])),n=e.filter(s=>!s.approved),o=e.filter(s=>s.approved).map(s=>s.id);if(n.length===0)return"";let i=["Rejected plan items:",""];for(let s of n){let a=r.get(s.id),c=a?`${s.id} \u2014 ${a.text.split(`
10
10
  `)[0]}`:s.id;i.push(`- **${c}**`),s.remark?.trim()&&i.push(` ${s.remark.trim()}`)}return o.length>0&&i.push("",`Approved and settled: ${o.join(", ")}. Do not revisit these unless a`,"rejected item forces it \u2014 and say so explicitly if it does."),i.join(`
11
- `)}function $c(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(K$))e.add(n[1]);return[...e]}var D$,U$,K$,Tp=E(()=>{"use strict";D$=[{re:/^decisions?$/i,kind:"decision",letter:"D"},{re:/^changes?$/i,kind:"change",letter:"C"},{re:/^assumptions?$/i,kind:"assumption",letter:"A"},{re:/^out of scope$/i,kind:"out_of_scope",letter:"O"},{re:/^test strategy$/i,kind:"test",letter:"T"},{re:/^procedures?$/i,kind:"procedure",letter:"P"}],U$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;K$=/`([a-z][a-z0-9-]{1,39})`/g});function q$(t){let e=[],r=null;for(let o of t.split(`
12
- `)){let i=W$.exec(o);if(i){r={id:i[1],status:i[2].toLowerCase(),text:i[3].trim()},e.push(r);continue}if(/^#{1,6}\s/.test(o)||/^\s*[-*]\s/.test(o)||!o.trim()){r=null;continue}r&&(r.text=`${r.text}
13
- ${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}function Y$(t,e){let r=new Set(t);return{unreported:t.filter(n=>!(n in e.byId)),unknown:e.items.filter(n=>!r.has(n.id)).map(n=>n.id),notDone:e.items.filter(n=>n.status!=="done")}}var H$,W$,Ip=E(()=>{"use strict";H$=["done","deviated","partial","dropped"],W$=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var Cp=E(()=>{"use strict"});var Pp=E(()=>{"use strict"});var Ap=E(()=>{"use strict"});function xc(t){return`codepipe-host-${t}`}function V$(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var _p=E(()=>{"use strict"});function z$(t){let e=t.toLowerCase(),r="";for(let o of e)r+=Object.prototype.hasOwnProperty.call(jp,o)?jp[o]:o;return r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50).replace(/-+$/g,"")}function X$(t,e,r){let o=(t&&t.includes("<TASK_ID>")?t:Np).replace(/<TASK_ID>/g,e.toLowerCase()).replace(/<SLUG>/g,r??"");return o=o.replace(/-{2,}/g,"-").replace(/\/{2,}/g,"/").replace(/-\//g,"/").replace(/\/-/g,"/").replace(/^[-/]+|[-/]+$/g,""),o}function J$(t,e){if(t)return`${t.replace(/\/+$/,"")}/issue/${encodeURIComponent(e)}`}function rr(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 Sc(t){if(!t||typeof t!="object")return null;let e=t,r=typeof e.owner=="string"?e.owner.trim():"",n=typeof e.repo=="string"?e.repo.trim():typeof e.repoName=="string"?e.repoName.trim():"",o=typeof e.host=="string"?e.host.trim():"";return!r||!n||o!=="github"&&o!=="gitlab"&&o!=="bitbucket"?null:{host:o,owner:r,repoName:n}}function Ec(t){if(!t.mirror)return t;let{mirror:e,...r}=t;return{...r,host:e.host,owner:e.owner,repoName:e.repoName}}function jt(t){return`${t}${Op}`}var Np,b0,jp,nr,Op,Rc=E(()=>{"use strict";Np="codepipe/<TASK_ID>",b0=50,jp={\u0430:"a",\u0431:"b",\u0432:"v",\u0433:"g",\u0434:"d",\u0435:"e",\u0451:"e",\u0436:"zh",\u0437:"z",\u0438:"i",\u0439:"y",\u043A:"k",\u043B:"l",\u043C:"m",\u043D:"n",\u043E:"o",\u043F:"p",\u0440:"r",\u0441:"s",\u0442:"t",\u0443:"u",\u0444:"f",\u0445:"h",\u0446:"c",\u0447:"ch",\u0448:"sh",\u0449:"sch",\u044A:"",\u044B:"y",\u044C:"",\u044D:"e",\u044E:"yu",\u044F:"ya"};nr=/^[a-z][a-z0-9-]{1,30}$/,Op="-codepipe-ctx"});function Z$(t){return t==="simple"||t==="gitflow"||t==="release"}function Tc(t){return t==="integration"||t==="stable"||t==="release_pattern"}function Q$(t){let e=t.endsWith("/*")?t.slice(0,-2):t;return rr(e)}function ex(t){let e=new Set(Ic[t.flow].roles);for(let r of Object.keys(t.branchTypes??{}))Tc(r)&&e.add(r);return e}function kn(t){if(t==null)return{config:null,errors:[]};let e=[];if(typeof t!="object"||Array.isArray(t))return{config:null,errors:["git: must be a mapping"]};let r=t,n=r.flow;if(!Z$(n))return e.push(`git.flow must be one of simple | gitflow | release (got ${JSON.stringify(n)})`),{config:null,errors:e};let o=n,i={},s=r.branch_types??r.branchTypes;if(s!==void 0)if(typeof s!="object"||s===null||Array.isArray(s))e.push("git.branch_types must be a mapping of role \u2192 name/pattern");else for(let[d,f]of Object.entries(s)){if(!Tc(d)){e.push(`git.branch_types: unknown role "${d}"`);continue}if(typeof f!="string"||!Lp(d,f)){e.push(`git.branch_types.${d}: invalid branch name/pattern ${JSON.stringify(f)}`);continue}i[d]=f}let a=new Set(Ic[o].roles);for(let d of Object.keys(i))a.add(d);let c={},l=r.branches;if(l!==void 0)if(typeof l!="object"||l===null||Array.isArray(l))e.push("git.branches must be a mapping of role \u2192 branch name");else for(let[d,f]of Object.entries(l)){if(!Tc(d)){e.push(`git.branches: unknown role "${d}"`);continue}if(!a.has(d)){e.push(`git.branches.${d}: role not part of flow "${o}"`);continue}if(typeof f!="string"||!Lp(d,f)){e.push(`git.branches.${d}: invalid branch name/pattern ${JSON.stringify(f)}`);continue}c[d]=f}let u,p=r.commit;if(p!==void 0)if(typeof p!="object"||p===null||Array.isArray(p))e.push("git.commit must be a mapping");else{let d=p.subject;d!==void 0&&typeof d!="string"?e.push("git.commit.subject must be a string"):typeof d=="string"?u={subject:d}:u={}}return e.length>0?{config:null,errors:e}:{config:{flow:o,branches:c,...Object.keys(i).length>0?{branchTypes:i}:{},...u?{commit:u}:{}},errors:[]}}function Lp(t,e){return t==="release_pattern"?Q$(e):rr(e)}function tx(t,e,r){let n=r??"main",o=e??t;if(!o)return{flow:"simple",integration:n};let i=ex(o),s=u=>o.branches[u]??o.branchTypes?.[u],a=s("integration")??n,c=i.has("stable")?s("stable"):void 0,l=i.has("release_pattern")?s("release_pattern"):void 0;return{flow:o.flow,integration:a,...c?{stable:c}:{},...l?{releasePattern:l}:{}}}function vn(t){return t.gitFlow?.integration??t.defaultBranch??"main"}function rx(t,e){return e??vn(t)}function Mp(t,e){if(e.endsWith("/*")){let r=e.slice(0,-1);return t.startsWith(r)&&t.length>r.length}return t===e}function Cc(t,e){return e.flow==="simple"?!1:!!(t===e.integration||e.stable&&t===e.stable||e.releasePattern&&Mp(t,e.releasePattern))}function Co(t){let e=t.branches??[],r=e.some(s=>/^release\//.test(s)),n=e.includes("develop")||e.includes("dev"),o=r?"release":n?"gitflow":"simple",i={integration:nx(o,t)};if(o!=="simple"){let s=ox(t,i.integration??"");s&&(i.stable=s)}return o==="release"&&(i.release_pattern="release/*"),{flow:o,branches:i}}function nx(t,e){let r=e.branches??[];if(t!=="simple"){if(r.includes("develop"))return"develop";if(r.includes("dev"))return"dev"}return e.defaultBranch??r[0]??""}function ox(t,e){let r=t.branches??[],n=t.defaultBranch;if(n&&(n==="main"||n==="master")&&n!==e)return n;if(r.includes("main")&&e!=="main")return"main";if(r.includes("master")&&e!=="master")return"master"}function Pc(t,e){if(t.flow==="simple")return!1;if(t.flow!==e.flow)return!0;let r=t.branches,n=e.branches;return(r.integration??"")!==(n.integration??"")||(r.stable??"")!==(n.stable??"")||(r.release_pattern??"")!==(n.release_pattern??"")}var Ic,Dp=E(()=>{"use strict";Rc();Ic={simple:{roles:["integration"]},gitflow:{roles:["integration","stable"]},release:{roles:["integration","stable","release_pattern"]}}});function ix(t,e,r=72){let n=(t||Up).replace(/\{key\}/g,e.key).replace(/\{summary\}/g,e.summary).replace(/\s+/g," ").trim(),o=Number.isFinite(r)&&r>0?Math.floor(r):72;if(n.length<=o)return n;let i=n.slice(0,o),s=i.lastIndexOf(" ");return s>=Math.floor(o/2)?i.slice(0,s).trimEnd():i.trimEnd()}var Up,x0,Bp=E(()=>{"use strict";Up="{key}: {summary}",x0=72});function sx(t,e){return`${t}:${e}`}var Fp=E(()=>{"use strict"});function Gp(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)||/^write action apply_delivery failed: .*hit conflicts/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function ax(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function cx(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=ax(e)?.reason,o={kind:Gp(n)};return n&&(o.reason=n),o}}var Kp=E(()=>{"use strict"});function Mr(t){for(let e of Hp){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Hp,Wp=E(()=>{"use strict";Hp=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0},{name:"fix",pattern:/^@(?:codepipe|devpipe)\s+fix\s*$/im,description:"Fix the external review remarks on the developer's branch (waiting-for-fix state only)."}]});var qp=E(()=>{"use strict"});function Yp(t){let e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;let r=Math.round(e/60);if(r<60)return`${r}m`;let n=Math.round(r/60);return n<24?`${n}h`:`${Math.round(n/24)}d`}function lx(t,e=Date.now()){return`${Yp((e-t)/1e3)} ago`}function ux(t){let e=Math.floor(t/86400),r=Math.floor(t%86400/3600),n=Math.floor(t%3600/60);return e>0?`${e}d ${r}h`:r>0?`${r}h ${n}m`:`${n}m`}var Vp=E(()=>{"use strict"});var zp=E(()=>{"use strict"});function Xp(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function _c(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=Xp(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Dr.test(r))return r;let n=Xp(t);return Dr.test(n)?n:Ni}function jc(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 Ac,Po,Ni,Dr,Oi,dx,Ao,$n,Jp=E(()=>{"use strict";Ac=["bug","feature","epic"],Po="feature",Ni="TASK",Dr=/^[A-Z][A-Z0-9]{1,9}$/;Oi={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},dx=Oi.backlog,Ao="tracker/config.yaml",$n="tracker/counter"});function _o(t){let e=t.split(`
11
+ `)}function Mc(t){let e=new Set;for(let r of t.items)if(r.kind==="procedure")for(let n of r.text.matchAll(wx))e.add(n[1]);return[...e]}var fx,mx,wx,Wp=E(()=>{"use strict";fx=[{re:/^decisions?$/i,kind:"decision",letter:"D"},{re:/^changes?$/i,kind:"change",letter:"C"},{re:/^assumptions?$/i,kind:"assumption",letter:"A"},{re:/^out of scope$/i,kind:"out_of_scope",letter:"O"},{re:/^test strategy$/i,kind:"test",letter:"T"},{re:/^procedures?$/i,kind:"procedure",letter:"P"}],mx=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*(.*)$/;wx=/`([a-z][a-z0-9-]{1,39})`/g});function vx(t){let e=[],r=null;for(let o of t.split(`
12
+ `)){let i=kx.exec(o);if(i){r={id:i[1],status:i[2].toLowerCase(),text:i[3].trim()},e.push(r);continue}if(/^#{1,6}\s/.test(o)||/^\s*[-*]\s/.test(o)||!o.trim()){r=null;continue}r&&(r.text=`${r.text}
13
+ ${o.trim()}`.trim())}let n={};for(let o of e)n[o.id]=o;return{items:e,byId:n}}function $x(t,e){let r=new Set(t);return{unreported:t.filter(n=>!(n in e.byId)),unknown:e.items.filter(n=>!r.has(n.id)).map(n=>n.id),notDone:e.items.filter(n=>n.status!=="done")}}var bx,kx,qp=E(()=>{"use strict";bx=["done","deviated","partial","dropped"],kx=/^\s*[-*]\s+(?:\*\*)?\[([A-Z][0-9]+)\](?:\*\*)?\s*[—:-]?\s*(done|deviated|partial|dropped)\b\s*[—:-]?\s*(.*)$/i});var Yp=E(()=>{"use strict"});var Vp=E(()=>{"use strict"});var zp=E(()=>{"use strict"});function Dc(t){return`codepipe-host-${t}`}function xx(t){let e=t.filter(r=>r!=="self-hosted");return`runs-on: [self-hosted${e.length?", "+e.join(", "):""}]`}var Xp=E(()=>{"use strict"});function Sx(t,e,r=72){let n=(t||Jp).replace(/\{key\}/g,e.key).replace(/\{summary\}/g,e.summary).replace(/\s+/g," ").trim(),o=Number.isFinite(r)&&r>0?Math.floor(r):72;if(n.length<=o)return n;let i=n.slice(0,o),s=i.lastIndexOf(" ");return s>=Math.floor(o/2)?i.slice(0,s).trimEnd():i.trimEnd()}var Jp,J0,Zp=E(()=>{"use strict";Jp="{key}: {summary}",J0=72});function Ex(t,e){return`${t}:${e}`}var Qp=E(()=>{"use strict"});function ef(t){let e=(t??"").trim();return/^pr_closed_without_merge\b/.test(e)?"blocked":/^(merge_failed|close_failed)\b/.test(e)||/^chain_base_changed\b/.test(e)||/^write action apply_delivery failed: .*hit conflicts/.test(e)?"conflict":/^(build_failed|ci_failed)\b/.test(e)?"loop_exhausted":"error"}function Rx(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.to==="NEEDS_MANUAL")return r}return null}function Tx(t,e){if(t==="AWAITING_ANSWER")return{kind:"question"};if(t==="NEEDS_MANUAL"){let n=Rx(e)?.reason,o={kind:ef(n)};return n&&(o.reason=n),o}}var tf=E(()=>{"use strict"});function Kr(t){for(let e of rf){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var rf,nf=E(()=>{"use strict";rf=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0},{name:"fix",pattern:/^@(?:codepipe|devpipe)\s+fix\s*$/im,description:"Fix the external review remarks on the developer's branch (waiting-for-fix state only)."}]});var of=E(()=>{"use strict"});function sf(t){let e=Math.max(1,Math.round(t));if(e<60)return`${e}s`;let r=Math.round(e/60);if(r<60)return`${r}m`;let n=Math.round(r/60);return n<24?`${n}h`:`${Math.round(n/24)}d`}function Ix(t,e=Date.now()){return`${sf((e-t)/1e3)} ago`}function Cx(t){let e=Math.floor(t/86400),r=Math.floor(t%86400/3600),n=Math.floor(t%3600/60);return e>0?`${e}d ${r}h`:r>0?`${r}h ${n}m`:`${n}m`}var af=E(()=>{"use strict"});var cf=E(()=>{"use strict"});function lf(t){return t.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/^[^A-Z]+/,"").slice(0,10)}function Bc(t){let e=t.split(/[^A-Za-z0-9]+/).filter(Boolean),r=lf(e.length>=2?e.map(o=>o[0]).join(""):(e[0]??"").slice(0,4));if(Hr.test(r))return r;let n=lf(t);return Hr.test(n)?n:Ki}function Fc(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 Uc,Lo,Ki,Hr,Hi,Px,Mo,Cn,uf=E(()=>{"use strict";Uc=["bug","feature","epic"],Lo="feature",Ki="TASK",Hr=/^[A-Z][A-Z0-9]{1,9}$/;Hi={backlog:"Backlog",source:["To Do"],inProgress:"In Progress",review:"Review",done:["Done"],rejected:["Rejected"],statusColumns:["Backlog","To Do","In Progress","Review","Done","Rejected"]},Px=Hi.backlog,Mo="tracker/config.yaml",Cn="tracker/counter"});function Do(t){let e=t.split(`
14
14
  `),r=e.indexOf("---");if(r<0)return;let n=e.slice(r+1),o=n.lastIndexOf("## Attachments");o>=0&&n.slice(o+1).every(c=>c.trim()===""||/^- \[[^\]]*\]\(attachments\/[^)]*\)$/.test(c.trim()))&&(n=n.slice(0,o));let i=n.join(`
15
- `).trim();if(!(!i||i==="_(no description)_"))return i}function px(t){return`{{ancestorExcerpt:${t}}}`}var Li,Zp=E(()=>{"use strict";Li=/\{\{ancestorExcerpt:([^}]+)\}\}/g});var fx,Qp=E(()=>{"use strict";fx="youtrack"});function Ur(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 jo(t){switch(t){case Sn.gitlab:return"oauth2";case Sn.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Sn,qt,ef=E(()=>{"use strict";Sn={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};qt="x-bitbucket-api-token-auth"});var tf=E(()=>{"use strict"});var rf=E(()=>{"use strict";Qp();ef();tf()});var Oc={};Ne(Oc,{ACTION_ID_RE:()=>ec,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>rc,ALL_JOB_ROLES:()=>Va,ALL_MODEL_ROLE_KEYS:()=>Pi,ANALYSIS_MAX_DRAFTS:()=>Nc,ANCESTOR_EXCERPT_RE:()=>Li,ANCESTOR_EXCERPT_TOKEN:()=>px,ANNOTATION_MAX_PER_TASK:()=>Ba,BACKFILL_MAX_DRAFTS:()=>mx,BITBUCKET_API_TOKEN_GIT_USER:()=>qt,BRANCH_SLUG_MAX_LENGTH:()=>b0,BUILD_DISCOVERY:()=>Qd,COCHANGE_DEFAULTS:()=>lt,CODEPIPE_COMMANDS:()=>Hp,CODE_REVIEW_VERIFY:()=>ep,COMMIT_STYLE_MAX_LENGTH:()=>lc,CONTEXT_PACK_DECAY:()=>Ga,CONTEXT_PACK_DEFAULTS:()=>Nr,CONTEXT_REPO_SUFFIX:()=>Op,CONTEXT_STAMP_FILE:()=>xt,CONTEXT_TEMPLATE_CHANGELOG:()=>Ia,CONTEXT_TEMPLATE_VERSION:()=>Od,COUNCIL_MAX_ANSWER:()=>m0,DEFAULT_BRANCH_PATTERN:()=>Np,DEFAULT_COMMIT_SUBJECT:()=>Up,DEFAULT_HUB_URL:()=>vt,DEFAULT_INTERNAL_ISSUE_TYPE:()=>Po,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>Ni,DEFAULT_LLM_PROVIDER:()=>tt,DEFAULT_REGIMEN_ALIASES:()=>ap,DEFAULT_SUBJECT_MAX:()=>x0,DEFAULT_TRACKER_PROVIDER:()=>fx,DEFAULT_WORKFLOW_PRESET:()=>op,EFFORT_LEVELS:()=>cp,EFFORT_LEVEL_SUGGESTIONS:()=>Ai,ENV_NAME_RE:()=>rt,FALLBACK_MODEL:()=>rp,GIT_FLOW_PRESETS:()=>Ic,GIT_HOST_DOMAINS:()=>Sn,INTERACTIVE_ROLES:()=>Jd,INTERNAL_ISSUE_TYPES:()=>Ac,INTERNAL_TRACKER_CONFIG_PATH:()=>Ao,INTERNAL_TRACKER_COUNTER_PATH:()=>$n,INTERNAL_TRACKER_DEFAULT_STATUS:()=>dx,INTERNAL_TRACKER_PREFIX_RE:()=>Dr,INTERNAL_TRACKER_STATUSES:()=>Oi,LANE_PHASES:()=>c$,LANE_SEGMENTS:()=>Ya,LANGUAGE_AUTO:()=>ke,LANGUAGE_SUGGESTIONS:()=>bn,LANGUAGE_VALUE_MAX_LENGTH:()=>Io,LEGACY_CONTEXT_STAMP_FILE:()=>fn,LLM_PROVIDER_SUGGESTIONS:()=>Ja,MIN_SUPPORTED_PROTOCOL:()=>_d,MODEL_ALIAS_SUGGESTIONS:()=>Ci,MODEL_DERIVED_DIR:()=>t$,MODEL_DERIVED_INDEX_PATH:()=>Ei,MODEL_DIR:()=>Zv,MODEL_EDGE_KINDS:()=>Da,MODEL_ENTITY_ID_RE:()=>Ud,MODEL_FACTS_DIR:()=>e$,MODEL_FAMILY_PREFERENCE:()=>sp,MODEL_HAIKU:()=>wn,MODEL_LEVELS:()=>Dd,MODEL_OPUS:()=>Ce,MODEL_README_PATH:()=>Qv,MODEL_RELATES_PATH:()=>Ar,MODEL_SEARCH_MAX_LIMIT:()=>Fa,MODEL_SEARCH_MAX_ROWS:()=>n$,MODEL_SEARCH_ROW_TEXT_MAX:()=>Ti,MODEL_SONNET:()=>Ht,MODEL_SUB_ROLES:()=>tp,OBSERVER_MAX_DECISION:()=>d0,OBSERVER_MAX_SUMMARY:()=>p0,OFFICIAL_MARKETPLACES:()=>vp,PHASES:()=>qa,PIPELINE_COLUMNS:()=>Vd,PLANNING_LANE_MAX_JOBS:()=>p$,PLANNING_ROLES:()=>Xd,PLATFORM_VERSION:()=>et,PRESET_ROLE_MODELS:()=>ip,PROJECT_ID_RE:()=>nr,PROJECT_LANGUAGE_SECTIONS:()=>To,PROJECT_MODEL_FORMAT_VERSION:()=>Fe,PROJECT_SETTINGS_MANIFEST:()=>fp,PROMPT_ROLES:()=>bp,PROTOCOL_VERSION:()=>$t,RECOMMENDED_ROLE_EFFORT:()=>Ro,RECOMMENDED_ROLE_MODELS:()=>Eo,RELATES_MIN_OVERLAP:()=>Ua,ROLE_MAX_DESCRIPTION:()=>s0,ROLE_MAX_REFS:()=>i0,ROLE_NAME_RE:()=>pc,ROLE_SCENARIOS:()=>ji,SKILL_MAX_DESCRIPTION:()=>l0,SKILL_NAME_RE:()=>wc,SOLUTION_STATUSES:()=>H$,STRING_MAP_MAX_ENTRIES:()=>ac,STRING_MAP_MAX_VALUE_LENGTH:()=>cc,WORKFLOW_PRESETS:()=>np,additionsSince:()=>Pa,ago:()=>lx,attentionFor:()=>cx,autoLanguageConfig:()=>dp,autoModelDefault:()=>Za,branchMatchesFlow:()=>Cc,canonicalizeModelEdgeSheet:()=>Bd,canonicalizeModelIdentityTable:()=>Gd,canonicalizeModelShard:()=>Fd,canonicalizeModelTaskEvent:()=>Kd,changesSince:()=>Aa,classifyAttentionReason:()=>Gp,compilePlanRework:()=>G$,contextRepoName:()=>jt,deserializeEffortConfig:()=>k$,deserializeModelConfig:()=>$$,detectGitFlowPreset:()=>Co,effectiveClusterBase:()=>rx,emptyEffortConfig:()=>yn,emptyModelConfig:()=>gn,enabledPluginsSetting:()=>O$,extractLanguageConfig:()=>T$,extractTaskMdBody:()=>_o,findSettingField:()=>mp,firstFreeInternalTrackerPrefix:()=>jc,flattenSettingFields:()=>uc,fmtDuration:()=>Yp,fmtUptime:()=>ux,ghRunnerHostLabel:()=>xc,ghRunnerRunsOnSnippet:()=>V$,gitCloneUrlDomain:()=>Ur,gitFlowDiverges:()=>Pc,httpsTokenUser:()=>jo,internalIssueYamlPath:()=>xn,isAllAutoLanguage:()=>I$,isAutoLanguage:()=>pp,isBodyEditFrozen:()=>a$,isInteractiveRole:()=>za,isModelEntityId:()=>Ri,isPromptRole:()=>gc,isProtocolCompatible:()=>bo,isReservedEnvName:()=>Wt,isTerminalPhase:()=>s$,isValidBranchName:()=>rr,jobLane:()=>d$,laneSegmentForPhase:()=>l$,makeTaskId:()=>sx,matchesReleasePattern:()=>Mp,mergeRoles:()=>mc,mergeSkills:()=>kc,mismatchedIds:()=>F$,modelAnnotationPath:()=>Na,modelComponentSlug:()=>Md,modelCorrelatesPath:()=>Oa,modelEventPath:()=>_r,modelIdentityPath:()=>$o,modelNodeKey:()=>be,modelShardNeedsRebuild:()=>o$,modelStructureShardPath:()=>Ma,modelTaskNodeKey:()=>Re,modelTouchedPath:()=>La,parseActionDefinition:()=>nc,parseCodepipeCommand:()=>Mr,parseContextStamp:()=>Ca,parseEffortConfig:()=>w$,parseGitConfig:()=>kn,parseMarketplaceSource:()=>$p,parseMarketplaces:()=>j$,parseModelConfig:()=>g$,parseModelNodeKey:()=>re,parsePlanItems:()=>vc,parseRepoMirror:()=>Sc,parseSolutionItems:()=>q$,parseWorkflowPreset:()=>f$,pipelineColumnForPhase:()=>u$,pipelineRepoSpec:()=>Ec,prescribedSkills:()=>$c,promptOverridePath:()=>yc,renderCommitSubject:()=>ix,renderContextStamp:()=>ko,repoBaseBranch:()=>vn,resolveBranchName:()=>X$,resolveEffortForRole:()=>y$,resolveModelForRole:()=>m$,resolveProvider:()=>h$,resolveRepoFlow:()=>tx,rolesForScenario:()=>hc,serializeEffortConfig:()=>b$,serializeModelConfig:()=>v$,serializeModelEdgeSheet:()=>jr,serializeModelIdentityTable:()=>Ha,serializeModelShard:()=>Ka,serializeModelTaskEvent:()=>hn,serializeModelYaml:()=>Or,slugify:()=>z$,solutionCoverage:()=>Y$,suggestInternalTrackerPrefix:()=>_c,validateActionInput:()=>oc,validateCouncilVerdict:()=>M$,validateModelEdgeSheet:()=>xo,validateModelIdentityTable:()=>So,validateModelShard:()=>Gt,validateModelTaskEvent:()=>Kt,validateObserverPlan:()=>L$,validateRoleDefinition:()=>fc,validateSettingEdit:()=>dc,validateSkill:()=>bc,youtrackIssueUrl:()=>J$,zeroUsage:()=>ut});var Nc,mx,M=E(()=>{"use strict";jd();Nd();Ld();Wa();Yd();zd();Xa();Qa();hp();gp();sc();ic();wp();kp();xp();Ep();Rp();Tp();Ip();Cp();Pp();Ap();_p();Rc();Dp();Bp();Fp();Kp();Wp();qp();Vp();zp();Jp();Zp();rf();Nc=20,mx=15});function ee(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Ye=E(()=>{"use strict"});import{existsSync as hx,readFileSync as gx,readdirSync as yx}from"node:fs";import{dirname as wx,join as Lc}from"node:path";import{parse as bx}from"yaml";function kx(t=process.cwd()){let e=t;for(;;){if(hx(Lc(e,nt,"project.yaml")))return e;let r=wx(e);if(r===e)return null;e=r}}function vx(t){return Lc(t,nt)}function je(t=process.cwd()){let e=kx(t);if(!e)return null;let r=vx(e),n=$x(gx(Lc(r,"project.yaml"),"utf-8"));for(let o of n.gitConfigErrors??[])console.warn(`project.yaml: invalid git config \u2014 ${o}`);return{root:e,contextDir:r,spec:n}}function nf(t,e,r){return yx(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 En(t,e=process.cwd()){try{let r=je(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function $x(t){let e=bx(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[],s=[];s.push(...kn(e.git).errors.map(a=>`git: ${a}`));for(let a of o){if(!a||typeof a!="object")continue;let c=a,l=String(c.repo??c.repoName??""),u=String(c.name??l);if(!u||!l)continue;let p=c.host,d=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github",f=Sc(c.mirror);c.git!==void 0&&c.git!==null&&s.push(...kn(c.git).errors.map(m=>`repos[${u}].git: ${m}`)),i.push({name:u,host:d,owner:String(c.owner??""),repoName:l,defaultBranch:String(c.default_branch??c.defaultBranch??"main"),mountAs:String(c.mount_as??c.mountAs??u),...f?{mirror:f}:{}})}return{projectId:r,name:n,repos:i,...s.length>0?{gitConfigErrors:s}:{}}}function of(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 nt,Et=E(()=>{"use strict";M();nt=".codepipe"});import{homedir as sf}from"node:os";import{mkdirSync as xx,readFileSync as Sx,writeFileSync as Ex,existsSync as Mc}from"node:fs";import{dirname as cf,join as Mi,resolve as Rx}from"node:path";import{fileURLToPath as Tx}from"node:url";function lf(t){let e=Mi(af,".env");if(Mc(e)&&process.loadEnvFile(e),t){let r=Mi(af,"profiles",t,".env");Mc(r)&&process.loadEnvFile(r)}}function Rn(t){let e=ee("CONFIG");return e||(t?Mi(sf(),".codepipe","profiles",t,"config.json"):Mi(sf(),".codepipe","config.json"))}function Rt(t){let e=Rn(t);if(!Mc(e))return null;let r=Sx(e,"utf-8");return JSON.parse(r)}function Yt(t,e){let r=Rn(e);xx(cf(r),{recursive:!0}),Ex(r,JSON.stringify(t,null,2)+`
16
- `,{mode:384})}function Tn(t){if(t)return{cfg:Ve(t),profile:t};let e;try{e=je()?.spec.projectId||void 0}catch{}if(e){let r=Rt(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:Ve(void 0),profile:void 0}}function Ve(t){let e=Rt(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 ${Rn(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var af,Ge=E(()=>{"use strict";Ye();Et();af=Rx(cf(Tx(import.meta.url)),"..")});import{homedir as uf}from"node:os";import{existsSync as df,mkdirSync as pf,readFileSync as ff,writeFileSync as mf}from"node:fs";import{dirname as hf,join as gf}from"node:path";function yf(t,e,r){let n=X(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ie(n)}function wf(t,e){let r=X(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ie(r),!0)}function bf(t){return Object.keys(X(t)?.secrets??{}).sort()}function Di(t,e,r){let n=X(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,ie(n),"pinned")}function kf(t,e){let r=X(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ie(r),!0):!1}function Nt(t){return gf(uf(),".codepipe","secrets",`${t}.json`)}function X(t){let e=Nt(t);return df(e)?JSON.parse(ff(e,"utf-8")):null}function ie(t){let e=Nt(t.projectId);pf(hf(e),{recursive:!0}),mf(e,JSON.stringify(t,null,2)+`
17
- `,{mode:384})}function Br(){return gf(uf(),".codepipe","shared.json")}function In(){let t=Br();return df(t)?JSON.parse(ff(t,"utf-8")):null}function Ui(t){let e=Br();pf(hf(e),{recursive:!0}),mf(e,JSON.stringify(t,null,2)+`
18
- `,{mode:384})}function Cn(t){let e=X(t)?.claude?.oauthToken;return e||In()?.claude?.oauthToken}function No(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 Dc){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Pn(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var Dc,ue=E(()=>{"use strict";Dc=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as Ix,existsSync as $f,mkdirSync as Cx,renameSync as xf,statSync as Px,unlinkSync as Ax}from"node:fs";import{Writable as _x}from"node:stream";import{join as jx}from"node:path";function Bi(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Nx(process.env[`${t}_MAX_BYTES`]??String(Sf.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Sf.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Nx(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 Fi(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(Ox(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 Ox(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Lx(o)).join(" ");return`${r} ${t} ${n}`}function Lx(t){try{return JSON.stringify(t)}catch{return String(t)}}var Sf,An,Uc=E(()=>{"use strict";Sf={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},An=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Cx(e.dir,{recursive:!0}),this.currentPath=jx(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
15
+ `).trim();if(!(!i||i==="_(no description)_"))return i}function Ax(t){return`{{ancestorExcerpt:${t}}}`}var Wi,df=E(()=>{"use strict";Wi=/\{\{ancestorExcerpt:([^}]+)\}\}/g});var _x,pf=E(()=>{"use strict";_x="youtrack"});function Wr(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 Uo(t){switch(t){case An.gitlab:return"oauth2";case An.bitbucket:return"x-token-auth";default:return"x-access-token"}}var An,Xt,ff=E(()=>{"use strict";An={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};Xt="x-bitbucket-api-token-auth"});var mf=E(()=>{"use strict"});var hf=E(()=>{"use strict";pf();ff();mf()});var Kc={};Me(Kc,{ACTION_ID_RE:()=>cc,ACTION_STEP_DEFAULT_TIMEOUT_SEC:()=>uc,ALL_JOB_ROLES:()=>rc,ALL_MODEL_ROLE_KEYS:()=>Mi,ANALYSIS_MAX_DRAFTS:()=>Gc,ANCESTOR_EXCERPT_RE:()=>Wi,ANCESTOR_EXCERPT_TOKEN:()=>Ax,ANNOTATION_MAX_PER_TASK:()=>Va,BACKFILL_MAX_DRAFTS:()=>jx,BITBUCKET_API_TOKEN_GIT_USER:()=>Xt,BRANCH_SLUG_MAX_LENGTH:()=>R0,BUILD_DISCOVERY:()=>dp,COCHANGE_DEFAULTS:()=>mt,CODEPIPE_COMMANDS:()=>rf,CODE_REVIEW_VERIFY:()=>pp,COMMIT_STYLE_MAX_LENGTH:()=>Ec,CONTEXT_PACK_DECAY:()=>Xa,CONTEXT_PACK_DEFAULTS:()=>Br,CONTEXT_REPO_SUFFIX:()=>Ep,CONTEXT_STAMP_FILE:()=>Tt,CONTEXT_TEMPLATE_CHANGELOG:()=>La,CONTEXT_TEMPLATE_VERSION:()=>Yd,COUNCIL_MAX_ANSWER:()=>q0,DEFAULT_BRANCH_PATTERN:()=>Sp,DEFAULT_COMMIT_SUBJECT:()=>Jp,DEFAULT_HUB_URL:()=>Et,DEFAULT_INTERNAL_ISSUE_TYPE:()=>Lo,DEFAULT_INTERNAL_TRACKER_PREFIX:()=>Ki,DEFAULT_LLM_PROVIDER:()=>it,DEFAULT_REGIMEN_ALIASES:()=>bp,DEFAULT_SUBJECT_MAX:()=>J0,DEFAULT_TRACKER_PROVIDER:()=>_x,DEFAULT_WORKFLOW_PRESET:()=>gp,EFFORT_LEVELS:()=>kp,EFFORT_LEVEL_SUGGESTIONS:()=>Di,ENV_NAME_RE:()=>st,FALLBACK_MODEL:()=>mp,GIT_FLOW_PRESETS:()=>Bi,GIT_FLOW_PRESET_NAMES:()=>wc,GIT_HOST_DOMAINS:()=>An,INTERACTIVE_ROLES:()=>lp,INTERNAL_ISSUE_TYPES:()=>Uc,INTERNAL_TRACKER_CONFIG_PATH:()=>Mo,INTERNAL_TRACKER_COUNTER_PATH:()=>Cn,INTERNAL_TRACKER_DEFAULT_STATUS:()=>Px,INTERNAL_TRACKER_PREFIX_RE:()=>Hr,INTERNAL_TRACKER_STATUSES:()=>Hi,LANE_PHASES:()=>T$,LANE_SEGMENTS:()=>tc,LANGUAGE_AUTO:()=>ke,LANGUAGE_SUGGESTIONS:()=>In,LANGUAGE_VALUE_MAX_LENGTH:()=>Oo,LEGACY_CONTEXT_STAMP_FILE:()=>vn,LLM_PROVIDER_SUGGESTIONS:()=>ic,MIN_SUPPORTED_PROTOCOL:()=>Hd,MODEL_ALIAS_SUGGESTIONS:()=>Li,MODEL_DERIVED_DIR:()=>k$,MODEL_DERIVED_INDEX_PATH:()=>_i,MODEL_DIR:()=>y$,MODEL_EDGE_KINDS:()=>qa,MODEL_ENTITY_ID_RE:()=>Jd,MODEL_FACTS_DIR:()=>b$,MODEL_FAMILY_PREFERENCE:()=>wp,MODEL_HAIKU:()=>Rn,MODEL_LEVELS:()=>Xd,MODEL_OPUS:()=>Ce,MODEL_README_PATH:()=>w$,MODEL_RELATES_PATH:()=>Mr,MODEL_SEARCH_MAX_LIMIT:()=>za,MODEL_SEARCH_MAX_ROWS:()=>$$,MODEL_SEARCH_ROW_TEXT_MAX:()=>Ni,MODEL_SONNET:()=>Vt,MODEL_SUB_ROLES:()=>fp,OBSERVER_MAX_DECISION:()=>K0,OBSERVER_MAX_SUMMARY:()=>H0,OFFICIAL_MARKETPLACES:()=>Up,PHASES:()=>ec,PIPELINE_COLUMNS:()=>sp,PLANNING_LANE_MAX_JOBS:()=>A$,PLANNING_ROLES:()=>cp,PLATFORM_VERSION:()=>ot,PRESET_ROLE_MODELS:()=>yp,PROJECT_ID_RE:()=>ir,PROJECT_LANGUAGE_SECTIONS:()=>No,PROJECT_MODEL_FORMAT_VERSION:()=>He,PROJECT_SETTINGS_MANIFEST:()=>Pp,PROMPT_ROLES:()=>Mp,PROTOCOL_VERSION:()=>Rt,RECOMMENDED_ROLE_EFFORT:()=>_o,RECOMMENDED_ROLE_MODELS:()=>Ao,RELATES_MIN_OVERLAP:()=>Ya,ROLE_MAX_DESCRIPTION:()=>D0,ROLE_MAX_REFS:()=>M0,ROLE_NAME_RE:()=>Tc,ROLE_SCENARIOS:()=>Gi,SKILL_MAX_DESCRIPTION:()=>F0,SKILL_NAME_RE:()=>jc,SOLUTION_STATUSES:()=>bx,STRING_MAP_MAX_ENTRIES:()=>xc,STRING_MAP_MAX_VALUE_LENGTH:()=>Sc,WORKFLOW_PRESETS:()=>hp,additionsSince:()=>Da,ago:()=>Ix,attentionFor:()=>Tx,autoLanguageConfig:()=>Ip,autoModelDefault:()=>sc,branchMatchesFlow:()=>bc,canonicalizeModelEdgeSheet:()=>Zd,canonicalizeModelIdentityTable:()=>ep,canonicalizeModelShard:()=>Qd,canonicalizeModelTaskEvent:()=>tp,changesSince:()=>Ua,classifyAttentionReason:()=>ef,compilePlanRework:()=>yx,contextRepoName:()=>Dt,deserializeEffortConfig:()=>U$,deserializeModelConfig:()=>F$,detectGitFlowPreset:()=>jo,effectiveClusterBase:()=>Z$,emptyEffortConfig:()=>En,emptyModelConfig:()=>Sn,enabledPluginsSetting:()=>ux,extractLanguageConfig:()=>rx,extractTaskMdBody:()=>Do,findSettingField:()=>Ap,findSettingFieldByPath:()=>_p,firstFreeInternalTrackerPrefix:()=>Fc,flattenSettingFields:()=>Fi,fmtDuration:()=>sf,fmtUptime:()=>Cx,ghRunnerHostLabel:()=>Dc,ghRunnerRunsOnSnippet:()=>xx,gitCloneUrlDomain:()=>Wr,gitFlowDiverges:()=>kc,httpsTokenUser:()=>Uo,internalIssueYamlPath:()=>Pn,isAllAutoLanguage:()=>nx,isAutoLanguage:()=>Cp,isBodyEditFrozen:()=>R$,isInteractiveRole:()=>nc,isModelEntityId:()=>ji,isPromptRole:()=>Ac,isProtocolCompatible:()=>Eo,isReservedEnvName:()=>zt,isTerminalPhase:()=>E$,isValidBranchName:()=>or,jobLane:()=>P$,laneSegmentForPhase:()=>I$,makeTaskId:()=>Ex,matchesReleasePattern:()=>Tp,mergeRoles:()=>Cc,mergeSkills:()=>Oc,mismatchedIds:()=>gx,modelAnnotationPath:()=>Ga,modelComponentSlug:()=>zd,modelCorrelatesPath:()=>Ka,modelEventPath:()=>Dr,modelIdentityPath:()=>Io,modelNodeKey:()=>be,modelShardNeedsRebuild:()=>x$,modelStructureShardPath:()=>Wa,modelTaskNodeKey:()=>Re,modelTouchedPath:()=>Ha,parseActionDefinition:()=>dc,parseCodepipeCommand:()=>Kr,parseContextStamp:()=>Ma,parseEffortConfig:()=>M$,parseGitConfig:()=>sr,parseMarketplaceSource:()=>Bp,parseMarketplaces:()=>cx,parseModelConfig:()=>O$,parseModelNodeKey:()=>re,parsePlanItems:()=>Lc,parseRepoMirror:()=>mc,parseSolutionItems:()=>vx,parseWorkflowPreset:()=>_$,pipelineColumnForPhase:()=>C$,pipelineRepoSpec:()=>hc,prescribedSkills:()=>Mc,promptOverridePath:()=>_c,renderCommitSubject:()=>Sx,renderContextStamp:()=>Ro,repoBaseBranch:()=>Tn,resolveBranchName:()=>q$,resolveEffortForRole:()=>L$,resolveModelForRole:()=>j$,resolveProvider:()=>N$,resolveRepoFlow:()=>J$,rolesForScenario:()=>Pc,serializeEffortConfig:()=>D$,serializeModelConfig:()=>B$,serializeModelEdgeSheet:()=>Ur,serializeModelIdentityTable:()=>Za,serializeModelShard:()=>Ja,serializeModelTaskEvent:()=>xn,serializeModelYaml:()=>Fr,slugify:()=>W$,solutionCoverage:()=>$x,suggestInternalTrackerPrefix:()=>Bc,validateActionInput:()=>pc,validateCouncilVerdict:()=>px,validateModelEdgeSheet:()=>Co,validateModelIdentityTable:()=>Po,validateModelShard:()=>qt,validateModelTaskEvent:()=>Yt,validateObserverPlan:()=>dx,validateRoleDefinition:()=>Ic,validateSettingEdit:()=>Rc,validateSkill:()=>Nc,youtrackIssueUrl:()=>Y$,zeroUsage:()=>ht});var Gc,jx,M=E(()=>{"use strict";Wd();qd();Vd();Qa();ip();ap();oc();ac();jp();Np();$c();fc();Lp();Dp();Fp();Kp();Hp();Wp();qp();Yp();Vp();zp();Xp();gc();vc();Zp();Qp();tf();nf();of();af();cf();uf();df();hf();Gc=20,jx=15});function ee(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}var Je=E(()=>{"use strict"});import{existsSync as Nx,readFileSync as Ox,readdirSync as Lx}from"node:fs";import{dirname as Mx,join as Hc}from"node:path";import{parse as Dx}from"yaml";function Ux(t=process.cwd()){let e=t;for(;;){if(Nx(Hc(e,gt,"project.yaml")))return e;let r=Mx(e);if(r===e)return null;e=r}}function Bx(t){return Hc(t,gt)}function Ne(t=process.cwd()){let e=Ux(t);if(!e)return null;let r=Bx(e),n=Fx(Ox(Hc(r,"project.yaml"),"utf-8"));for(let o of n.gitConfigErrors??[])console.warn(`project.yaml: invalid git config \u2014 ${o}`);return{root:e,contextDir:r,spec:n}}function gf(t,e,r){return Lx(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 _n(t,e=process.cwd()){try{let r=Ne(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Fx(t){let e=Dx(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[],s=[];s.push(...sr(e.git).errors.map(a=>`git: ${a}`));for(let a of o){if(!a||typeof a!="object")continue;let c=a,l=String(c.repo??c.repoName??""),u=String(c.name??l);if(!u||!l)continue;let p=c.host,d=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github",f=mc(c.mirror);c.git!==void 0&&c.git!==null&&s.push(...sr(c.git).errors.map(m=>`repos[${u}].git: ${m}`)),i.push({name:u,host:d,owner:String(c.owner??""),repoName:l,defaultBranch:String(c.default_branch??c.defaultBranch??"main"),mountAs:String(c.mount_as??c.mountAs??u),...f?{mirror:f}:{}})}return{projectId:r,name:n,repos:i,...s.length>0?{gitConfigErrors:s}:{}}}function yf(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 gt,Ct=E(()=>{"use strict";M();gt=".codepipe"});import{homedir as wf}from"node:os";import{mkdirSync as Gx,readFileSync as Kx,writeFileSync as Hx,existsSync as Wc}from"node:fs";import{dirname as kf,join as qi,resolve as Wx}from"node:path";import{fileURLToPath as qx}from"node:url";function vf(t){let e=qi(bf,".env");if(Wc(e)&&process.loadEnvFile(e),t){let r=qi(bf,"profiles",t,".env");Wc(r)&&process.loadEnvFile(r)}}function jn(t){let e=ee("CONFIG");return e||(t?qi(wf(),".codepipe","profiles",t,"config.json"):qi(wf(),".codepipe","config.json"))}function Pt(t){let e=jn(t);if(!Wc(e))return null;let r=Kx(e,"utf-8");return JSON.parse(r)}function Jt(t,e){let r=jn(e);Gx(kf(r),{recursive:!0}),Hx(r,JSON.stringify(t,null,2)+`
16
+ `,{mode:384})}function Nn(t){if(t)return{cfg:Ze(t),profile:t};let e;try{e=Ne()?.spec.projectId||void 0}catch{}if(e){let r=Pt(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:Ze(void 0),profile:void 0}}function Ze(t){let e=Pt(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 ${jn(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}var bf,We=E(()=>{"use strict";Je();Ct();bf=Wx(kf(qx(import.meta.url)),"..")});import{homedir as $f}from"node:os";import{existsSync as xf,mkdirSync as Sf,readFileSync as Ef,writeFileSync as Rf}from"node:fs";import{dirname as Tf,join as If}from"node:path";function Cf(t,e,r){let n=X(t);if(!n)throw new Error("no secrets file for this project on the CLI");n.secrets={...n.secrets??{},[e]:r},ie(n)}function Pf(t,e){let r=X(t);return!r?.secrets||!(e in r.secrets)?!1:(delete r.secrets[e],ie(r),!0)}function Af(t){return Object.keys(X(t)?.secrets??{}).sort()}function Yi(t,e,r){let n=X(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,ie(n),"pinned")}function _f(t,e){let r=X(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],ie(r),!0):!1}function Ut(t){return If($f(),".codepipe","secrets",`${t}.json`)}function X(t){let e=Ut(t);return xf(e)?JSON.parse(Ef(e,"utf-8")):null}function ie(t){let e=Ut(t.projectId);Sf(Tf(e),{recursive:!0}),Rf(e,JSON.stringify(t,null,2)+`
17
+ `,{mode:384})}function qr(){return If($f(),".codepipe","shared.json")}function On(){let t=qr();return xf(t)?JSON.parse(Ef(t,"utf-8")):null}function Vi(t){let e=qr();Sf(Tf(e),{recursive:!0}),Rf(e,JSON.stringify(t,null,2)+`
18
+ `,{mode:384})}function Ln(t){let e=X(t)?.claude?.oauthToken;return e||On()?.claude?.oauthToken}function Bo(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 qc){let n=e[r];n&&!process.env[r]&&(process.env[r]=n)}}function Mn(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}var qc,de=E(()=>{"use strict";qc=["GH_TOKEN","BITBUCKET_EMAIL","BITBUCKET_API_TOKEN","GITLAB_TOKEN","YOUTRACK_URL","YOUTRACK_TOKEN"]});import{appendFileSync as Yx,existsSync as Nf,mkdirSync as Vx,renameSync as Of,statSync as zx,unlinkSync as Xx}from"node:fs";import{Writable as Jx}from"node:stream";import{join as Zx}from"node:path";function zi(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=Qx(process.env[`${t}_MAX_BYTES`]??String(Lf.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Lf.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function Qx(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 Xi(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(eS(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 eS(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:tS(o)).join(" ");return`${r} ${t} ${n}`}function tS(t){try{return JSON.stringify(t)}catch{return String(t)}}var Lf,Dn,Yc=E(()=>{"use strict";Lf={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},Dn=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Vx(e.dir,{recursive:!0}),this.currentPath=Zx(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
19
19
  `)?e:e+`
20
- `;Ix(this.currentPath,r,"utf-8")}asWritable(){return new _x({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||!$f(this.currentPath)||Px(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;$f(n)&&(r>=this.cfg.maxFiles?Ax(n):xf(n,`${this.currentPath}.${r+1}`))}xf(this.currentPath,`${this.currentPath}.1`)}}}});import{createHash as Mx}from"node:crypto";import{existsSync as Dx,readFileSync as Ux}from"node:fs";import{homedir as Rf,hostname as Bx}from"node:os";import{join as Ef}from"node:path";function Fx(){let t=process.env.CLAUDE_CONFIG_DIR?.trim();return t?Ef(t,".claude.json"):Ef(Rf(),".claude.json")}function Vt(){try{let t=Fx();if(!Dx(t))return null;let r=JSON.parse(Ux(t,"utf-8")).oauthAccount,n=r?.accountUuid;if(typeof n!="string"||n.length===0)return null;let o=c=>typeof c=="string"&&c.length>0?c:void 0,i=o(r?.emailAddress)?.toLowerCase(),s=o(r?.organizationType),a=o(r?.displayName);return{accountUuid:n,...i?{email:i}:{},...s?{organizationType:s}:{},...a?{displayName:a}:{}}}catch{return null}}function Gi(t){return t?`claude-account:${t.accountUuid}`:`machine:${Mx("sha256").update(`${Bx()}:${Rf()}`).digest("hex").slice(0,16)}`}var Oo=E(()=>{"use strict"});function Hi(t){return t===429||t>=500}function If(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
21
- `+t.slice(t.length-e)}async function or(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Ki);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new dt(`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(Hi(i.status))throw new dt(`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 Wi(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Ki);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 dt(`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(Hi(s.status))throw new dt(`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 ir(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(),Ki);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new dt(`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(Hi(s.status))throw new dt(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await Wx(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 Wx(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function qi(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=Cf.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: ${Cf.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function sr(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Ki);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 dt(`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(Hi(n.status))throw new dt(`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 Pf(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 qx(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 Fc(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 ar(t,e){let r=Ec(e);if(!e.mirror)return{spec:r,host:Gr(r)};let n=t?X(t)?.mirrorWrite:void 0;return{spec:r,host:Gr(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function Gr(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new Kc(r)}if(t.host==="bitbucket"){let r=e?.bitbucketEmail??process.env.BITBUCKET_EMAIL,n=e?.token??process.env.BITBUCKET_API_TOKEN;if(r&&n)return new Gc(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new Hc(r)}return new Wc}var Fr,dt,Ki,Cf,Gc,Kc,Hc,Wc,zt=E(()=>{"use strict";M();ue();Fr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},dt=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Ki=5e3;Cf=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Gc=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 Fr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:i},inline:{path:n,to:o}})});if(!s.ok)throw new Error(`bitbucket inline comment PR #${r} ${n}:${o}: ${s.status} ${await s.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Kc=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 Fr(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async getBranchCi(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=await fetch(`${o}/commits/${encodeURIComponent(r)}`,{headers:n});if(!i.ok)return null;let s=(await i.json()).sha;return s?{ci:await this.fetchCiStatus(e,s),headSha:s}:null}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`;try{let i=await fetch(`${o}/pulls/${r}`,{headers:n});if(!i.ok)return;let s=(await i.json()).head?.sha;return s?await this.getCiFailureLogForSha(e,s):void 0}catch{return}}async getCiFailureLogForSha(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/actions/runs?head_sha=${r}&per_page=20`,{headers:n});if(!s.ok)return;let a=(await s.json()).workflow_runs??[],c=[];for(let l of a.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${o}/actions/runs/${l.id}/jobs?per_page=50`,{headers:n});if(!u.ok)continue;let p=(await u.json()).jobs??[];for(let d of p.filter(f=>f.conclusion==="failure")){let f=await fetch(`${o}/actions/jobs/${d.id}/logs`,{headers:n});if(!f.ok)continue;let m=await f.text();c.push(`### CI job: ${d.name}
20
+ `;Yx(this.currentPath,r,"utf-8")}asWritable(){return new Jx({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||!Nf(this.currentPath)||zx(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Nf(n)&&(r>=this.cfg.maxFiles?Xx(n):Of(n,`${this.currentPath}.${r+1}`))}Of(this.currentPath,`${this.currentPath}.1`)}}}});import{createHash as rS}from"node:crypto";import{existsSync as nS,readFileSync as oS}from"node:fs";import{homedir as Df,hostname as iS}from"node:os";import{join as Mf}from"node:path";function sS(){let t=process.env.CLAUDE_CONFIG_DIR?.trim();return t?Mf(t,".claude.json"):Mf(Df(),".claude.json")}function Zt(){try{let t=sS();if(!nS(t))return null;let r=JSON.parse(oS(t,"utf-8")).oauthAccount,n=r?.accountUuid;if(typeof n!="string"||n.length===0)return null;let o=c=>typeof c=="string"&&c.length>0?c:void 0,i=o(r?.emailAddress)?.toLowerCase(),s=o(r?.organizationType),a=o(r?.displayName);return{accountUuid:n,...i?{email:i}:{},...s?{organizationType:s}:{},...a?{displayName:a}:{}}}catch{return null}}function Ji(t){return t?`claude-account:${t.accountUuid}`:`machine:${rS("sha256").update(`${iS()}:${Df()}`).digest("hex").slice(0,16)}`}var Fo=E(()=>{"use strict"});function Qi(t){return t===429||t>=500}function Bf(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
21
+ `+t.slice(t.length-e)}async function ar(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n=new AbortController,o=setTimeout(()=>n.abort(),Zi);try{let i;try{i=await fetch("https://api.github.com/user",{headers:r,signal:n.signal})}catch(l){throw new yt(`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(Qi(i.status))throw new yt(`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 es(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o=new AbortController,i=setTimeout(()=>o.abort(),Zi);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 yt(`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(Qi(s.status))throw new yt(`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 cr(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(),Zi);try{let s;try{s=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")},signal:o.signal})}catch(c){throw new yt(`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(Qi(s.status))throw new yt(`api.bitbucket.org \u2192 ${s.status} ${s.statusText}`);let a=await uS(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 uS(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ts(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=Ff.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: ${Ff.join(", ")}`}let a=i.error?.message?`: ${i.error.message}`:"";return`cannot list pull requests of ${r}/${n} (403${a})`}async function lr(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Zi);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 yt(`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(Qi(n.status))throw new yt(`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 Gf(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 dS(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 zc(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 ur(t,e){let r=hc(e);if(!e.mirror)return{spec:r,host:Vr(r)};let n=t?X(t)?.mirrorWrite:void 0;return{spec:r,host:Vr(r,n?.token?{token:n.token,...n.email?{bitbucketEmail:n.email}:{}}:void 0)}}function Vr(t,e){if(t.host==="github"){let r=e?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(r)return new Jc(r)}if(t.host==="bitbucket"){let r=e?.bitbucketEmail??process.env.BITBUCKET_EMAIL,n=e?.token??process.env.BITBUCKET_API_TOKEN;if(r&&n)return new Xc(r,n)}if(t.host==="gitlab"){let r=e?.token??process.env.GITLAB_TOKEN;if(r)return new Zc(r)}return new Qc}var Yr,yt,Zi,Ff,Xc,Jc,Zc,Qc,Qt=E(()=>{"use strict";M();de();Yr=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}},yt=class extends Error{constructor(e){super(e),this.name="TransientHostError"}},Zi=5e3;Ff=["read:repository:bitbucket","write:repository:bitbucket","read:pullrequest:bitbucket","write:pullrequest:bitbucket"];Xc=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 Yr(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!o.ok)throw new Error(`bitbucket comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:i},inline:{path:n,to:o}})});if(!s.ok)throw new Error(`bitbucket inline comment PR #${r} ${n}:${o}: ${s.status} ${await s.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},Jc=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 Yr(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async getBranchCi(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=await fetch(`${o}/commits/${encodeURIComponent(r)}`,{headers:n});if(!i.ok)return null;let s=(await i.json()).sha;return s?{ci:await this.fetchCiStatus(e,s),headSha:s}:null}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let p of u.check_runs??[])l=!0,p.status!=="completed"?a=!0:p.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(p.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`;try{let i=await fetch(`${o}/pulls/${r}`,{headers:n});if(!i.ok)return;let s=(await i.json()).head?.sha;return s?await this.getCiFailureLogForSha(e,s):void 0}catch{return}}async getCiFailureLogForSha(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/actions/runs?head_sha=${r}&per_page=20`,{headers:n});if(!s.ok)return;let a=(await s.json()).workflow_runs??[],c=[];for(let l of a.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${o}/actions/runs/${l.id}/jobs?per_page=50`,{headers:n});if(!u.ok)continue;let p=(await u.json()).jobs??[];for(let d of p.filter(f=>f.conclusion==="failure")){let f=await fetch(`${o}/actions/jobs/${d.id}/logs`,{headers:n});if(!f.ok)continue;let m=await f.text();c.push(`### CI job: ${d.name}
22
22
 
23
- ${If(m,8e3)}`)}}return c.length===0?void 0:If(c.join(`
23
+ ${Bf(m,8e3)}`)}}return c.length===0?void 0:Bf(c.join(`
24
24
 
25
- `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s={Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:s});if(!a.ok)throw new Error(`github PR #${r}: ${a.status} ${await a.text()}`);let c=(await a.json()).head?.sha;if(!c)throw new Error(`github PR #${r}: no head sha`);let l=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/comments`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({body:i,commit_id:c,path:n,line:o,side:"RIGHT"})});if(!l.ok)throw new Error(`github inline comment PR #${r} ${n}:${o}: ${l.status} ${await l.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Hc=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 Fr(`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=qx(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{headers:this.headers(!1)});if(!s.ok)throw new Error(`gitlab MR !${r}: ${s.status} ${await s.text()}`);let a=(await s.json()).diff_refs;if(!a?.base_sha||!a.head_sha||!a.start_sha)throw new Error(`gitlab MR !${r}: no diff refs`);let c=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/discussions`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:i,position:{position_type:"text",new_path:n,new_line:o,base_sha:a.base_sha,head_sha:a.head_sha,start_sha:a.start_sha}})});if(!c.ok)throw new Error(`gitlab inline comment MR !${r} ${n}:${o}: ${c.status} ${await c.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};Wc=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(Fc(e,r,"merge"))}async closePR(e,r,n){throw new Error(Fc(e,r,"close"))}async addPRComment(e,r,n){throw new Error(Fc(e,r,"comment"))}}});import{X509Certificate as jf}from"node:crypto";import{readFileSync as Yx}from"node:fs";import cr from"node:tls";function Vx(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Lf(t=Of){if(Af)return;Af=!0;let e=ee("EXTRA_CA_FILE");if(!(!e||!Nf))try{let r=Vx(Yx(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}cr.setDefaultCACertificates([...cr.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 Mf(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 zx(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
26
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Xx(t,e,r){return new Promise((n,o)=>{let i=cr.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 jf(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function qc(t,e,r){return new Promise(n=>{let o=cr.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 Jx(t){try{let e=await fetch(t);return e.ok?new jf(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Df(t,e=443,r=Of){let n=`${t}:${e}`,o=_f.get(n);if(o)return o;let i=Zx(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return _f.set(n,i),i}async function Zx(t,e,r){if(!Nf)return!1;let n=8e3;if(await qc(t,e,n))return!0;let o=await Xx(t,e,n),i=cr.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=zx(o);if(!c)break;let l=await Jx(c);if(!l)break;if(s.push(l.toString()),cr.setDefaultCACertificates([...i,...s]),await qc(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 qc(t,e,n)}var Nf,Af,_f,Of,Uf=E(()=>{"use strict";Ye();Nf=typeof cr.getCACertificates=="function"&&typeof cr.setDefaultCACertificates=="function",Af=!1,_f=new Map,Of=t=>console.warn(t)});function Kf(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function pt(t,e,r){Lf();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(Mf(s)&&await Df(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function Qx(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function eS(){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 Yc(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=eS(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await pt(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&&Qx(l.status,u)){await Bf(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Bf(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function lr(t){let e;try{e=await pt(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 Hf(t){try{let e=await pt(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function tS(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Ff.get(o);if(i)return i;let s=await pt(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 Ff.set(o,l.id),l.id}async function Wf(t,e,r,n=Lo){let o=await tS(t,e,r,n);await Yc(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 qf(t,e,r){return await(await Yc(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Yf(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await Yc(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function Vf(t,e){let r=Gf.get(e);if(r)return r;let n=await pt(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 Gf.set(e,i.id),i.id}async function zf(t,e,r,n,o,i=Lo){let s=await Vf(t,e),a=await pt(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 Xf(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await pt(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 Qf(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 em(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 tm(t,e){let r=e.stageField??Lo,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=${Zf}&$top=200`,s=await pt(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);let a=await s.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>om(c,r))}async function rm(t,e,r=Lo){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Zf}`,o=await pt(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return om(await o.json(),r)}async function nm(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${nS}&$top=500`,o=await pt(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=Qf(s.attachments);return c&&(a.attachments=c),a})}function oS(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 om(t,e=Lo){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=Qf(t.attachments);a&&(s.attachments=a);let c=oS(t.links);return c&&(s.links=c),s}async function im(t,e){let r=await iS(t,e);return r.length>0?r:sS(t,e)}async function iS(t,e){let r=await Vf(t,e),n=await pt(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:sm(s.bundle)});return i}async function sS(t,e){let r=`project: ${e}`,n=await pt(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:sm(s.projectCustomField?.bundle)});return i}function sm(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Bf,Lo,Ff,Gf,Jf,rS,Zf,nS,Kr=E(()=>{"use strict";Uf();Bf=t=>new Promise(e=>setTimeout(e,t));Lo="Stage",Ff=new Map;Gf=new Map;Jf="attachments(id,name,url,size,mimeType)",rS="links(direction,linkType(name),issues(idReadable))",Zf=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Jf},${rS}`,nS=`id,text,created,author(login),${Jf}`});function Tt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function _n(t){return t instanceof dt}async function am(t,e){let r=X(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 lr({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:Tt(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:Tt(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 or(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){_n(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:Tt(c)}),o.push({kind:"github",present:!0,ok:!1,detail:Tt(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 ir(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){_n(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:Tt(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:Tt(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await sr(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){_n(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:Tt(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:Tt(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 Wi(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){_n(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:Tt(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await Wi(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){_n(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:Tt(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Wi(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){_n(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:Tt(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=Cn(t);if(!a)n.push({name:"claude",ok:!0,detail:"no project token \u2014 using the runner's own Claude 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 Xt(a);if(c==="invalid"){let l="Claude refused this token \u2014 refresh it with `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Xt(t){let e=new AbortController,r=setTimeout(()=>e.abort(),8e3);try{let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","content-type":"application/json"},body:JSON.stringify({model:aS,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:e.signal});return n.status===200?"valid":n.status===401||n.status===403?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function cm(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 aS,jn=E(()=>{"use strict";ue();zt();Kr();aS="claude-haiku-4-5-20251001"});import cS from"node:http";import Vc from"node:crypto";function Yi(){let t=zc(Vc.randomBytes(32)),e=zc(Vc.createHash("sha256").update(t).digest()),r=zc(Vc.randomBytes(32));return{verifier:t,challenge:e,state:r}}function Jc(t){let e=new URL(lS);return e.search=new URLSearchParams({response_type:"code",client_id:lm,redirect_uri:t.redirectUri,scope:dS,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function fS(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 um(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 mS(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 Zc(t){let e=await fetch(uS,{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:lm,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return mS(await e.json())}async function Qc(t){let e=t.timeoutMs??pS,r=cS.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=Jc({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let f=new URL(p.url??"/",o);if(f.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(fS(f.searchParams,t.state))}catch(m){u(m)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>Zc({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function dm(t){let e=await Qc(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
27
- ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var lm,lS,uS,Xc,dS,pS,zc,el=E(()=>{"use strict";lm="9d1c250a-e61b-44d9-88ed-5944d1962f5e",lS="https://platform.claude.com/oauth/authorize",uS="https://platform.claude.com/v1/oauth/token",Xc="https://platform.claude.com/oauth/code/callback",dS="org:create_api_key user:profile user:inference",pS=12e4,zc=t=>Buffer.from(t).toString("base64url")});import{spawn as hS}from"node:child_process";function ur(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=hS(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var Vi=E(()=>{"use strict"});import{existsSync as dr,mkdirSync as km,readFileSync as ol,writeFileSync as Nn}from"node:fs";import{homedir as SS}from"node:os";import{join as Ot}from"node:path";import{simpleGit as ES}from"simple-git";function Do(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=Ot(t,o);dr(s)||(Nn(s,i),r.push(o))}return r}function pr(t,e,r){let n=Ot(SS(),".codepipe","profiles",t,"context-config");return km(n,{recursive:!0}),Nn(Ot(n,"project.yaml"),e.projectYaml),Nn(Ot(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Ji(t,e,r){if(dr(e))for(let n of On){let o=Ot(e,n),i=Ot(t,n);if(!(!dr(o)||dr(i)))try{Nn(i,ol(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 Ln(t){let e=Ot(t,".gitignore"),r=dr(e)?ol(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(On.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
25
+ `),16e3)}catch{return}}async mergePR(e,r,n,o){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`github comment PR #${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s={Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:s});if(!a.ok)throw new Error(`github PR #${r}: ${a.status} ${await a.text()}`);let c=(await a.json()).head?.sha;if(!c)throw new Error(`github PR #${r}: no head sha`);let l=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/comments`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({body:i,commit_id:c,path:n,line:o,side:"RIGHT"})});if(!l.ok)throw new Error(`github inline comment PR #${r} ${n}:${o}: ${l.status} ${await l.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},Zc=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 Yr(`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=dS(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,n,o){let i=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:n==="squash",should_remove_source_branch:o,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.merge_commit_sha}:{}}async addPRComment(e,r,n){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:n})});if(!o.ok)throw new Error(`gitlab comment MR !${r}: ${o.status} ${await o.text()}`)}async addPRInlineComment(e,r,n,o,i){let s=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{headers:this.headers(!1)});if(!s.ok)throw new Error(`gitlab MR !${r}: ${s.status} ${await s.text()}`);let a=(await s.json()).diff_refs;if(!a?.base_sha||!a.head_sha||!a.start_sha)throw new Error(`gitlab MR !${r}: no diff refs`);let c=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/discussions`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:i,position:{position_type:"text",new_path:n,new_line:o,base_sha:a.base_sha,head_sha:a.head_sha,start_sha:a.start_sha}})});if(!c.ok)throw new Error(`gitlab inline comment MR !${r} ${n}:${o}: ${c.status} ${await c.text()}`)}async closePR(e,r,n){n&&n.length>0&&await this.addPRComment(e,r,n);let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};Qc=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(zc(e,r,"merge"))}async closePR(e,r,n){throw new Error(zc(e,r,"close"))}async addPRComment(e,r,n){throw new Error(zc(e,r,"comment"))}}});import{X509Certificate as Wf}from"node:crypto";import{readFileSync as pS}from"node:fs";import dr from"node:tls";function fS(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Vf(t=Yf){if(Kf)return;Kf=!0;let e=ee("EXTRA_CA_FILE");if(!(!e||!qf))try{let r=fS(pS(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}dr.setDefaultCACertificates([...dr.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 zf(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 mS(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
26
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function hS(t,e,r){return new Promise((n,o)=>{let i=dr.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 Wf(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function el(t,e,r){return new Promise(n=>{let o=dr.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 gS(t){try{let e=await fetch(t);return e.ok?new Wf(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Xf(t,e=443,r=Yf){let n=`${t}:${e}`,o=Hf.get(n);if(o)return o;let i=yS(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Hf.set(n,i),i}async function yS(t,e,r){if(!qf)return!1;let n=8e3;if(await el(t,e,n))return!0;let o=await hS(t,e,n),i=dr.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=mS(o);if(!c)break;let l=await gS(c);if(!l)break;if(s.push(l.toString()),dr.setDefaultCACertificates([...i,...s]),await el(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 el(t,e,n)}var qf,Kf,Hf,Yf,Jf=E(()=>{"use strict";Je();qf=typeof dr.getCACertificates=="function"&&typeof dr.setDefaultCACertificates=="function",Kf=!1,Hf=new Map,Yf=t=>console.warn(t)});function tm(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function wt(t,e,r){Vf();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(zf(s)&&await Xf(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}function wS(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function bS(){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 tl(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=bS(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await wt(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&&wS(l.status,u)){await Zf(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Zf(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function pr(t){let e;try{e=await wt(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 rm(t){try{let e=await wt(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}async function kS(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=Qf.get(o);if(i)return i;let s=await wt(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 Qf.set(o,l.id),l.id}async function nm(t,e,r,n=Go){let o=await kS(t,e,r,n);await tl(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 om(t,e,r){return await(await tl(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function im(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await tl(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}async function sm(t,e){let r=em.get(e);if(r)return r;let n=await wt(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 em.set(e,i.id),i.id}async function am(t,e,r,n,o,i=Go){let s=await sm(t,e),a=await wt(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 cm(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await wt(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 dm(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 pm(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 fm(t,e){let r=e.stageField??Go,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=${um}&$top=200`,s=await wt(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);let a=await s.json();if(e.columns&&e.columns.length>0&&a.length>0&&!a.some(l=>(l.customFields??[]).some(u=>u.name===r))){let l=[...new Set((a[0]?.customFields??[]).map(u=>u.name).filter(u=>!!u))];throw new Error(`youtrack.stage_field "${r}" does not exist in project ${e.projectKey} \u2014 YouTrack ignored the status filter and would have returned unrelated issues. `+(l.length>0?`Fields on the issues: ${l.join(", ")}.`:"The issues carry no custom fields at all."))}return a.map(c=>gm(c,r))}async function mm(t,e,r=Go){let n=`/api/issues/${encodeURIComponent(e)}?fields=${um}`,o=await wt(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return gm(await o.json(),r)}async function hm(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${$S}&$top=500`,o=await wt(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=dm(s.attachments);return c&&(a.attachments=c),a})}function xS(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 gm(t,e=Go){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=dm(t.attachments);a&&(s.attachments=a);let c=xS(t.links);return c&&(s.links=c),s}async function ym(t,e){let r=await SS(t,e);return r.length>0?r:ES(t,e)}async function SS(t,e){let r=await sm(t,e),n=await wt(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:wm(s.bundle)});return i}async function ES(t,e){let r=`project: ${e}`,n=await wt(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:wm(s.projectCustomField?.bundle)});return i}function wm(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}var Zf,Go,Qf,em,lm,vS,um,$S,zr=E(()=>{"use strict";Jf();Zf=t=>new Promise(e=>setTimeout(e,t));Go="Stage",Qf=new Map;em=new Map;lm="attachments(id,name,url,size,mimeType)",vS="links(direction,linkType(name),issues(idReadable))",um=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${lm},${vS}`,$S=`id,text,created,author(login),${lm}`});function At(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}function Un(t){return t instanceof yt}async function bm(t,e){let r=X(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 pr({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:At(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:At(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 ar(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Un(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:At(c)}),o.push({kind:"github",present:!0,ok:!1,detail:At(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 cr(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){Un(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:At(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:At(c),checkedAt:i()}))}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await lr(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){Un(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:At(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:At(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 es(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(p){Un(p)?n.push({name:`repo:${u.name}`,ok:!0,detail:"check inconclusive"}):n.push({name:`repo:${u.name}`,ok:!1,detail:At(p)})}let l=e?.contextRepo;if(l?.host==="github")try{await es(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){Un(u)?n.push({name:"context-repo",ok:!0,detail:"check inconclusive"}):n.push({name:"context-repo",ok:!1,detail:At(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await es(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){Un(l)?o.push({kind:"contextWrite",present:!0,detail:"check inconclusive",checkedAt:i()}):o.push({kind:"contextWrite",present:!0,ok:!1,detail:At(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=Ln(t);if(!a)n.push({name:"claude",ok:!0,detail:"no project token \u2014 using the runner's own Claude 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 er(a);if(c==="invalid"){let l="Claude refused this token \u2014 refresh it with `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function er(t){let e=new AbortController,r=setTimeout(()=>e.abort(),8e3);try{let n=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20","content-type":"application/json"},body:JSON.stringify({model:RS,max_tokens:1,messages:[{role:"user",content:"hi"}]}),signal:e.signal});return n.status===200?"valid":n.status===401||n.status===403?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}async function km(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 RS,Bn=E(()=>{"use strict";de();Qt();zr();RS="claude-haiku-4-5-20251001"});import TS from"node:http";import rl from"node:crypto";function rs(){let t=nl(rl.randomBytes(32)),e=nl(rl.createHash("sha256").update(t).digest()),r=nl(rl.randomBytes(32));return{verifier:t,challenge:e,state:r}}function il(t){let e=new URL(IS);return e.search=new URLSearchParams({response_type:"code",client_id:vm,redirect_uri:t.redirectUri,scope:PS,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"}).toString(),e.toString()}function _S(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 $m(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 jS(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 sl(t){let e=await fetch(CS,{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:vm,code_verifier:t.verifier})});if(!e.ok)throw new Error(`token endpoint ${e.status}: ${await e.text()}`);return jS(await e.json())}async function al(t){let e=t.timeoutMs??AS,r=TS.createServer();await new Promise(l=>r.listen(0,"127.0.0.1",l));let o=`http://localhost:${r.address().port}/callback`,i=il({redirectUri:o,challenge:t.challenge,state:t.state}),s,a=new Promise((l,u)=>{s=setTimeout(()=>u(new Error("no-callback")),e),r.on("request",(p,d)=>{let f=new URL(p.url??"/",o);if(f.pathname!=="/callback"){d.statusCode=404,d.end();return}clearTimeout(s),d.setHeader("content-type","text/html"),d.end("<h3>Authorized \u2014 you can close this tab.</h3>");try{l(_S(f.searchParams,t.state))}catch(m){u(m)}})});a.catch(()=>{});let c;return{authUrl:i,redirectUri:o,waitForToken(){return c||(c=a.then(l=>sl({code:l,verifier:t.verifier,state:t.state,redirectUri:o})),c.catch(()=>{})),c},close(){clearTimeout(s),r.close()}}}async function xm(t){let e=await al(t);try{return t.openUrl(e.authUrl),t.log("Opening your browser to authorize Claude\u2026"),t.log(`If it didn't open, visit:
27
+ ${e.authUrl}`),t.log(`Waiting for the redirect on ${e.redirectUri} \u2026`),await e.waitForToken()}finally{e.close()}}var vm,IS,CS,ol,PS,AS,nl,cl=E(()=>{"use strict";vm="9d1c250a-e61b-44d9-88ed-5944d1962f5e",IS="https://platform.claude.com/oauth/authorize",CS="https://platform.claude.com/v1/oauth/token",ol="https://platform.claude.com/oauth/code/callback",PS="org:create_api_key user:profile user:inference",AS=12e4,nl=t=>Buffer.from(t).toString("base64url")});import{spawn as NS}from"node:child_process";function fr(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=NS(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}var ns=E(()=>{"use strict"});import{existsSync as FS,mkdirSync as GS,rmSync as KS,writeFileSync as dl}from"node:fs";import{dirname as HS,isAbsolute as WS,join as jm,normalize as as}from"node:path";import{simpleGit as Nm}from"simple-git";async function Oe(t,e){let r=as(t),o=(ss.get(r)??Promise.resolve()).catch(()=>{}).then(e);ss.set(r,o);try{return await o}finally{ss.get(r)===o&&ss.delete(r)}}async function Pe(t,e,r){return Oe(t,()=>qe(t,e,r))}async function qe(t,e,r){if(!FS(jm(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=Te(t,a.path);if(a.deleted){KS(c,{force:!0});continue}GS(HS(c),{recursive:!0}),a.encoding==="base64"?dl(c,Buffer.from(a.content,"base64")):dl(c,a.content)}let n=Nm(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+=is)await n.raw(["add","-A","-f","--",...o.slice(a,a+is)]);for(let a=0;a<i.length;a+=is)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+is)]);await n.raw(["reset","-q","--",...ls]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await cs(t))}async function cs(t){let e=Nm(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Am;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 zS(e);if(i.length>0&&i.every(a=>qS.has(a)||_m.test(a)||YS.test(a))){for(let a of i)_m.test(a)?await VS(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 ${Am} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function VS(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(`
28
+ `)){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);dl(Te(e,r),i.join(`
29
+ `)+(i.length>0?`
30
+ `:""))}async function zS(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
31
+ `).map(r=>r.trim()).filter(Boolean)}function Te(t,e){if(WS(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=as(jm(t,e)),n=as(t+"/");if(r!==as(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Am,qS,YS,_m,is,ss,Le=E(()=>{"use strict";Bt();Am=3,qS=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),YS=/^model\/derived\//,_m=/^tasks\/[^/]+\/comments\.jsonl$/,is=500,ss=new Map});import{existsSync as Ye,mkdirSync as Lm,readFileSync as hr,rmSync as Mm,writeFileSync as gr}from"node:fs";import{homedir as XS}from"node:os";import{join as De}from"node:path";import{simpleGit as JS}from"simple-git";import{Document as ZS,isCollection as QS,isMap as mr,parse as eE,parseDocument as Fn}from"yaml";function tE(t){return Ko.some(e=>e.length<=t.length&&e.every((r,n)=>r===t[n]))}function Dm(t,e=[]){if(t===null||typeof t!="object"||Array.isArray(t))return e.length>0?[e]:[];let r=[];for(let[n,o]of Object.entries(t))r.push(...Dm(o,[...e,n]));return r}function rE(t,e){let r=t;for(let n of e){if(r===null||typeof r!="object"||Array.isArray(r)||!(n in r))return;r=r[n]}return r}function Um(t,e,r){if(t===null)return{merged:null};let n=Fn(t);if(e===null)return{merged:n.toString()};let o;try{o=eE(e)}catch(i){return r?.warn(`[config] local.yaml is not valid YAML \u2014 ignoring the personal layer: ${i instanceof Error?i.message:String(i)}`),{merged:n.toString()}}if(o===null||typeof o!="object"||Array.isArray(o))return{merged:n.toString()};for(let i of Dm(o))tE(i)||r?.warn(`[config] local.yaml: ignoring non-personal key "${i.join(".")}" \u2014 only the personal allow-list has effect`);n.contents!==null&&!QS(n.contents)&&(n.contents=null);for(let i of Ko){let s=rE(o,i);if(s!==void 0){for(let a=1;a<i.length;a++){let c=i.slice(0,a);n.hasIn([...c])&&n.getIn([...c])===null&&n.deleteIn([...c])}n.setIn([...i],s)}}return{merged:n.toString()}}function Ho(t,e){let r=De(t,"local.yaml");return Ye(r)&&hr(r,"utf-8").trim()!==""?[]:(gr(r,e.localYaml),["local.yaml"])}function Xr(t,e,r){let n=De(XS(),".codepipe","profiles",t,"context-config");return Lm(n,{recursive:!0}),gr(De(n,"local.yaml"),e.localYaml),r.info(`local project config staged \u2192 ${n}`),n}function us(t,e,r){if(Ye(e))for(let n of[...ls,"project.yaml","regimen.yaml"]){let o=De(e,n),i=De(t,n),s=Ye(i)&&(n!=="local.yaml"||hr(i,"utf-8").trim()!=="");if(!(!Ye(o)||s))try{gr(i,hr(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(a){r.warn(`[config] could not seed ${n}: ${a instanceof Error?a.message:String(a)}`)}}}function Jr(t){let e=De(t,".gitignore"),n=(Ye(e)?hr(e,"utf-8"):"").split(/\r?\n/),o=n.filter(c=>{let l=c.trim();return!(oE.has(l)||l.startsWith("# codepipe project config is local"))}),i=o.length!==n.length,s=o.some(c=>{let l=c.trim();return l==="local.yaml"||l==="/local.yaml"}),a=o.join(`
32
+ `);if(!s){let c=a.length===0||a.endsWith(`
28
33
  `)?"":`
29
- `;return Nn(e,r+i+RS.join(`
34
+ `;a=a+c+nE.join(`
30
35
  `)+`
31
- `),!0}async function vm(t,e){try{if(!dr(Ot(t,".git")))return;let r=ES(t),n=(await r.raw(["ls-files","--",...On])).split(`
32
- `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;Ln(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 al(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 il(t){let e=new Map;for(let r of On){let n=Ot(t,r);dr(n)&&e.set(r,ol(n))}return e}function sl(t,e){km(t,{recursive:!0});for(let[r,n]of e){let o=Ot(t,r);dr(o)||Nn(o,n)}}var On,RS,Jt=E(()=>{"use strict";ft();On=["project.yaml","regimen.yaml"];RS=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"]});import{existsSync as TS,mkdirSync as IS,rmSync as CS,writeFileSync as cl}from"node:fs";import{dirname as PS,isAbsolute as AS,join as Sm,normalize as es}from"node:path";import{simpleGit as Em}from"simple-git";async function ll(t,e){let r=es(t),o=(Qi.get(r)??Promise.resolve()).catch(()=>{}).then(e);Qi.set(r,o);try{return await o}finally{Qi.get(r)===o&&Qi.delete(r)}}async function Pe(t,e,r){return ll(t,()=>ul(t,e,r))}async function ul(t,e,r){if(!TS(Sm(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let a of e){let c=Te(t,a.path);if(a.deleted){CS(c,{force:!0});continue}IS(PS(c),{recursive:!0}),a.encoding==="base64"?cl(c,Buffer.from(a.content,"base64")):cl(c,a.content)}let n=Em(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+=Zi)await n.raw(["add","-A","-f","--",...o.slice(a,a+Zi)]);for(let a=0;a<i.length;a+=Zi)await n.raw(["rm","-q","--cached","--ignore-unmatch","--",...i.slice(a,a+Zi)]);await n.raw(["reset","-q","--",...On]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await al(t))}async function al(t){let e=Em(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=$m;n++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let i=await OS(e);if(i.length>0&&i.every(a=>_S.has(a)||xm.test(a)||jS.test(a))){for(let a of i)xm.test(a)?await NS(e,t,a):await e.raw(["checkout","--theirs","--",a]);await e.add(i),await e.raw(["-c","core.editor=true","rebase","--continue"])}else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${i.join(", ")||"unknown files"} \u2014 concurrent writers edited the same entry; resolve manually in the Context Repo`)}}throw new Error(`context push failed after ${$m} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function NS(t,e,r){let n=async s=>await t.raw(["show",`:${s}:${r}`]).catch(()=>""),o=new Map;for(let s of[await n(2),await n(3)])for(let a of s.split(`
33
- `)){let c=a.trim();if(c)try{let l=JSON.parse(c);if(typeof l.id!="string")continue;o.has(l.id)||o.set(l.id,{raw:c,createdAt:typeof l.createdAt=="string"?l.createdAt:""})}catch{}}let i=[...o.values()].sort((s,a)=>s.createdAt.localeCompare(a.createdAt)).map(s=>s.raw);cl(Te(e,r),i.join(`
34
- `)+(i.length>0?`
35
- `:""))}async function OS(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
36
- `).map(r=>r.trim()).filter(Boolean)}function Te(t,e){if(AS(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=es(Sm(t,e)),n=es(t+"/");if(r!==es(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var $m,_S,jS,xm,Zi,Qi,ft=E(()=>{"use strict";Jt();$m=3,_S=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]),jS=/^model\/derived\//,xm=/^tasks\/[^/]+\/comments\.jsonl$/,Zi=500,Qi=new Map});import{cpSync as HS,existsSync as Uo,mkdirSync as Cm,readFileSync as WS,readdirSync as qS,rmSync as Pm,statSync as YS,writeFileSync as VS}from"node:fs";import{join as fr}from"node:path";function Mn(t,e,r){let n=fr(t,"skills"),o=fr(e,".claude","skills"),i=fr(o,zS),s=XS(i),a={written:[],removed:[],skipped:[]},c=JS(n);for(let u of s)c.includes(u)||(Pm(fr(o,u),{recursive:!0,force:!0}),a.removed.push(u));let l=[];for(let u of c){let p=fr(o,u);if(Uo(p)&&!s.includes(u)){a.skipped.push(u);continue}Cm(o,{recursive:!0}),Pm(p,{recursive:!0,force:!0}),HS(fr(n,u),p,{recursive:!0}),l.push(u),a.written.push(u)}(l.length>0||a.removed.length>0||Uo(i))&&(Cm(o,{recursive:!0}),VS(i,JSON.stringify({managed:l.sort()},null,2)+`
37
- `)),(a.written.length>0||a.removed.length>0)&&r.info(`[skills] context \u2192 .claude/skills: ${a.written.length} written`+(a.removed.length>0?`, ${a.removed.length} removed`:""));for(let u of a.skipped)r.warn(`[skills] "${u}" exists in .claude/skills but is not managed by CodePipe \u2014 your copy wins; rename one of them to get the context version`);return a}function XS(t){if(!Uo(t))return[];try{let e=JSON.parse(WS(t,"utf-8"));return Array.isArray(e.managed)?e.managed.filter(r=>typeof r=="string"):[]}catch{return[]}}function JS(t){return Uo(t)?qS(t).filter(e=>{if(e.startsWith("."))return!1;let r=fr(t,e);try{return YS(r).isDirectory()&&Uo(fr(r,"SKILL.md"))}catch{return!1}}):[]}var zS,ts=E(()=>{"use strict";zS=".codepipe-managed.json"});import{existsSync as mr,readFileSync as Dn,readdirSync as Nm}from"node:fs";import{join as pl}from"node:path";import{simpleGit as Om}from"simple-git";import{parse as Lm}from"yaml";function Mm(t){try{let e=Te(t,Ao);if(!mr(e))return null;let r=Lm(Dn(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Dr.test(n)?null:{prefix:n}}catch{return null}}function Dm(t){return`# Built-in tracker configuration \u2014 shared by every team member.
36
+ `,i=!0}return i&&gr(e,a),i}function iE(t){return Ko.some(e=>t.getIn([...e])!==void 0)}function sE(t,e){let r=e.contents;if(mr(r))for(let n of r.items){let o=String(n.key),i=t.get(o);if(mr(n.value)&&mr(i))for(let s of n.value.items)t.setIn([o,String(s.key)],s.value);else t.set(o,n.value)}}function aE(t,e){let r=e.contents;if(mr(r))for(let n of r.items){let o=String(n.key),i=t.get(o);if(mr(n.value)&&mr(i))for(let s of n.value.items)t.getIn([o,String(s.key)])===void 0&&t.setIn([o,String(s.key)],s.value);else i===void 0&&t.set(o,n.value)}}function Bm(t){for(let e of Ko)if(t.hasIn([...e])&&(t.deleteIn([...e]),e.length>1)){let r=t.getIn(e.slice(0,-1));mr(r)&&r.items.length===0&&t.deleteIn(e.slice(0,-1))}}async function pl(t,e){return(await t.raw(["ls-files","--",e]).catch(()=>"")).trim().length>0}async function Fm(t,e){await pl(t,"regimen.yaml")?await t.raw(["rm","-q","--","regimen.yaml"]):Mm(De(e,"regimen.yaml"),{force:!0})}async function Gm(t,e){return Oe(t,()=>cE(t,e))}async function cE(t,e){try{if(!Ye(De(t,".git")))return;let r=JS(t),n=De(t,"local.yaml"),o=De(t,"project.yaml"),i=De(t,"regimen.yaml");if(Ye(n)&&await pl(r,"project.yaml")&&!Ye(i))return;let s=Ye(o)?Fn(hr(o,"utf-8")):null,a=Ye(i)?Fn(hr(i,"utf-8")):null;if(!Ye(n)){let f=new ZS({});for(let y of Ko){let b=a?.getIn([...y])??s?.getIn([...y]);b!=null&&f.setIn([...y],b)}let m=f.toString();gr(n,m===`{}
37
+ `?"":m)}await r.fetch().catch(()=>{});let c=(await r.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim()||"main",l=await r.raw(["show",`origin/${c}:project.yaml`]).catch(()=>null),u=await r.raw(["show",`origin/${c}:regimen.yaml`]).catch(()=>null);if(l!==null&&u===null&&!iE(Fn(l))){await Om(r,t,c,e,a);return}if(!s&&!a){e.info("[config] no legacy config here and no reformed upstream yet \u2014 leaving the migration to a clone that has the config");return}let d=s??Fn("");a&&sE(d,a),Bm(d);try{await lE(r,t,d,e)}catch(f){let m=f instanceof Error?f.message:String(f);if(/rebase conflict/.test(m)&&/project\.yaml/.test(m)){e.info("[config] another clone migrated first; adopting its shared project.yaml"),await Om(r,t,c,e,a);return}throw f}}catch(r){e.warn(`[config] config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}async function lE(t,e,r,n){if(r.contents==null){n.warn("[config] config migration skipped: the legacy project config is empty");return}if(gr(De(e,"project.yaml"),r.toString()),Jr(e),await Fm(t,e),await t.raw(["add","-A","-f","--","project.yaml",".gitignore"]),!(await t.raw(["diff","--cached","--name-only"])).trim()){n.info("[config] config migration: nothing to commit");return}await t.commit("chore(config): split project config into shared project.yaml + personal local.yaml"),await cs(e),n.info("[config] migrated project config into the Context Repo (shared project.yaml + personal local.yaml)")}async function Om(t,e,r,n,o=null){for(let c of["project.yaml","regimen.yaml"]){let l=De(e,c);Ye(l)&&!await pl(t,c)&&Mm(l,{force:!0})}await t.fetch().catch(()=>{});let i=Number.parseInt((await t.raw(["rev-list","--count",`origin/${r}..HEAD`]).catch(()=>"0")).trim(),10)||0;if(i>0)try{await t.rebase([`origin/${r}`])}catch(c){await t.raw(["rebase","--abort"]).catch(()=>{}),n.warn(`[config] cannot adopt the shared project.yaml over ${i} unpushed commit(s) \u2014 will retry: ${c instanceof Error?c.message:String(c)}`);return}else await t.raw(["reset","--hard",`origin/${r}`]).catch(()=>{});await Fm(t,e),Jr(e);let s=De(e,"project.yaml");if(o&&mr(o.contents)&&Ye(s)){let c=Fn(hr(s,"utf-8")),l=c.toString();aE(c,o),Bm(c);let u=c.toString();u!==l&&(gr(s,u),await t.raw(["add","--","project.yaml"]).catch(()=>{}))}await t.add([".gitignore"]).catch(()=>{}),(await t.raw(["diff","--cached","--name-only"])).trim()&&(await t.commit("chore(config): adopt shared project.yaml, drop regimen.yaml"),await cs(e)),n.info("[config] adopted the team's shared project.yaml; kept only local.yaml")}function fl(t){let e=new Map;for(let r of ls){let n=De(t,r);Ye(n)&&e.set(r,hr(n))}return e}function ml(t,e){Lm(t,{recursive:!0});for(let[r,n]of e){let o=De(t,r);Ye(o)||gr(o,n)}}var ls,Ko,nE,oE,Bt=E(()=>{"use strict";Le();ls=["local.yaml"],Ko=[["youtrack","assignee"],["youtrack","require_assignee"],["youtrack","writes"],["automation","level"],["gates","require_approval"],["llm","provider"],["llm","models"],["rate_limit","auto_pause"]];nE=["# codepipe personal config is local to each member's workspace","local.yaml"],oE=new Set(["project.yaml","/project.yaml","regimen.yaml","/regimen.yaml"])});import{cpSync as kE,existsSync as qo,mkdirSync as Ym,readFileSync as vE,readdirSync as $E,rmSync as Vm,statSync as xE,writeFileSync as SE}from"node:fs";import{join as yr}from"node:path";function Gn(t,e,r){let n=yr(t,"skills"),o=yr(e,".claude","skills"),i=yr(o,EE),s=RE(i),a={written:[],removed:[],skipped:[]},c=TE(n);for(let u of s)c.includes(u)||(Vm(yr(o,u),{recursive:!0,force:!0}),a.removed.push(u));let l=[];for(let u of c){let p=yr(o,u);if(qo(p)&&!s.includes(u)){a.skipped.push(u);continue}Ym(o,{recursive:!0}),Vm(p,{recursive:!0,force:!0}),kE(yr(n,u),p,{recursive:!0}),l.push(u),a.written.push(u)}(l.length>0||a.removed.length>0||qo(i))&&(Ym(o,{recursive:!0}),SE(i,JSON.stringify({managed:l.sort()},null,2)+`
38
+ `)),(a.written.length>0||a.removed.length>0)&&r.info(`[skills] context \u2192 .claude/skills: ${a.written.length} written`+(a.removed.length>0?`, ${a.removed.length} removed`:""));for(let u of a.skipped)r.warn(`[skills] "${u}" exists in .claude/skills but is not managed by CodePipe \u2014 your copy wins; rename one of them to get the context version`);return a}function RE(t){if(!qo(t))return[];try{let e=JSON.parse(vE(t,"utf-8"));return Array.isArray(e.managed)?e.managed.filter(r=>typeof r=="string"):[]}catch{return[]}}function TE(t){return qo(t)?$E(t).filter(e=>{if(e.startsWith("."))return!1;let r=yr(t,e);try{return xE(r).isDirectory()&&qo(yr(r,"SKILL.md"))}catch{return!1}}):[]}var EE,ps=E(()=>{"use strict";EE=".codepipe-managed.json"});import{existsSync as wr,readFileSync as Kn,readdirSync as Zm}from"node:fs";import{join as yl}from"node:path";import{simpleGit as Qm}from"simple-git";import{parse as eh}from"yaml";function th(t){try{let e=Te(t,Mo);if(!wr(e))return null;let r=eh(Kn(e,"utf-8"));if(!r||typeof r!="object")return null;let n=r.prefix;return typeof n!="string"||!Hr.test(n)?null:{prefix:n}}catch{return null}}function rh(t){return`# Built-in tracker configuration \u2014 shared by every team member.
38
39
  # The issue-key prefix (<PREFIX>-<N>). Fixed at project init: changing it
39
40
  # later would orphan existing tasks/<KEY>/ directories.
40
41
  prefix: ${t}
@@ -42,13 +43,13 @@ prefix: ${t}
42
43
  # Statuses are the built-in default set for now:
43
44
  # Backlog | To Do | In Progress | Review | Done | Rejected
44
45
  # A configurable status set / pipeline mapping is a planned extension.
45
- `}function fl(t=0){return`${t}
46
- `}function tE(t){return t==="depends_on"||t==="subtask"}function rE(t){let e;try{e=Lm(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=Ac.includes(r.type)?r.type:Po,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;tE(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 ml(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(`
46
+ `}function wl(t=0){return`${t}
47
+ `}function AE(t){return t==="depends_on"||t==="subtask"}function _E(t){let e;try{e=eh(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=Uc.includes(r.type)?r.type:Lo,o=[];if(Array.isArray(r.links))for(let c of r.links){if(!c||typeof c!="object")continue;let l=c;AE(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 bl(t){let e=[`key: ${t.key}`,`title: ${JSON.stringify(t.title)}`,`type: ${t.type}`,`status: ${JSON.stringify(t.status)}`];if(t.assignee&&e.push(`assignee: ${JSON.stringify(t.assignee)}`),t.links.length>0){e.push("links:");for(let r of t.links)e.push(` - type: ${r.type}`,` target: ${r.targetKey}`)}return e.push(`created: ${t.created}`,`updated: ${t.updated}`),e.join(`
47
48
  `)+`
48
- `}function Fo(t,e){let r=Te(t,xn(e));return mr(r)?rE(Dn(r,"utf-8")):null}function Um(t){let e=pl(t,"tasks");if(!mr(e))return[];let r=[];for(let n of Nm(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Fo(t,n.name);o&&r.push(o)}return r}function nE(t,e){let r=Te(t,`tasks/${e}/task.md`);if(mr(r))return _o(Dn(r,"utf-8"))}function Go(t,e,r={}){let n=r.withDescription?nE(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:oE(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function oE(t){return t.charAt(0).toUpperCase()+t.slice(1)}function iE(t){let e=Te(t,$n);if(!mr(e))return 0;let r=Number.parseInt(Dn(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function sE(t,e){let r=pl(t,"tasks");if(!mr(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of Nm(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 aE(t,e){return Math.max(iE(t),sE(t,e))+1}async function Bm(t,e,r,n){return ll(t,()=>cE(t,e,r,n))}async function cE(t,e,r,n){if(!mr(pl(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Bo(t);let o=null;for(let i=0;i<jm;i++){let s=aE(t,e),a=`${e}-${s}`,c=[...r(a),{path:$n,content:fl(s)}];try{return await ul(t,c,n(a)),a}catch(l){if(o=l,await uE(t,n(a)),await Bo(t),lE(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${jm} attempts: ${o instanceof Error?o.message:String(o)}`)}function lE(t,e){for(let r of e){let n=Te(t,r.path);if(!mr(n)||(r.encoding==="base64"?Dn(n).toString("base64"):Dn(n,"utf-8"))!==r.content)return!1}return!0}async function Bo(t){let e=Om(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 uE(t,e){let r=Om(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
49
+ `}function Vo(t,e){let r=Te(t,Pn(e));return wr(r)?_E(Kn(r,"utf-8")):null}function nh(t){let e=yl(t,"tasks");if(!wr(e))return[];let r=[];for(let n of Zm(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=Vo(t,n.name);o&&r.push(o)}return r}function jE(t,e){let r=Te(t,`tasks/${e}/task.md`);if(wr(r))return Do(Kn(r,"utf-8"))}function zo(t,e,r={}){let n=r.withDescription?jE(t,e.key):void 0;return{id:e.key,key:e.key,title:e.title,status:e.status,updatedAt:e.updated,issueType:NE(e.type),...e.assignee?{assignee:e.assignee}:{},...e.links.length>0?{links:e.links}:{},...n?{description:n}:{}}}function NE(t){return t.charAt(0).toUpperCase()+t.slice(1)}function OE(t){let e=Te(t,Cn);if(!wr(e))return 0;let r=Number.parseInt(Kn(e,"utf-8").trim(),10);return Number.isFinite(r)&&r>=0?r:0}function LE(t,e){let r=yl(t,"tasks");if(!wr(r))return 0;let n=new RegExp(`^${e}-(\\d+)$`),o=0;for(let i of Zm(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 ME(t,e){return Math.max(OE(t),LE(t,e))+1}async function oh(t,e,r,n){return Oe(t,()=>DE(t,e,r,n))}async function DE(t,e,r,n){if(!wr(yl(t,".git")))throw new Error(`context repo clone not found at ${t}`);await Yo(t);let o=null;for(let i=0;i<Jm;i++){let s=ME(t,e),a=`${e}-${s}`,c=[...r(a),{path:Cn,content:wl(s)}];try{return await qe(t,c,n(a)),a}catch(l){if(o=l,await BE(t,n(a)),await Yo(t),UE(t,c))return a}}throw new Error(`internal tracker: key allocation failed after ${Jm} attempts: ${o instanceof Error?o.message:String(o)}`)}function UE(t,e){for(let r of e){let n=Te(t,r.path);if(!wr(n)||(r.encoding==="base64"?Kn(n).toString("base64"):Kn(n,"utf-8"))!==r.content)return!1}return!0}async function Yo(t){let e=Qm(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 BE(t,e){let r=Qm(t);try{if(await r.rebase(["--abort"]).catch(()=>{}),(await r.raw(["log","-1","--pretty=%s"])).trim()!==e.split(`
49
50
  `)[0]||!(await r.raw(["log","@{u}..HEAD","--pretty=%s"]).catch(()=>"")).trim().split(`
50
51
  `).some(i=>i.trim()===e.split(`
51
- `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var jm,ns=E(()=>{"use strict";M();ft();jm=5});function Un(t,e,r,n){return[{path:"README.md",content:SE(t,e)},{path:".gitignore",content:gE()},{path:"CLAUDE.md",content:wE(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:yE()},{path:"knowledge/README.md",content:bE()},{path:"knowledge/build.yaml",content:xE()},{path:"actions/README.md",content:kE()},{path:"roles/README.md",content:vE()},{path:"skills/README.md",content:$E()},{path:"model/README.md",content:dE()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:hE()},{path:"adr/README.md",content:pE()},{path:"adr/0000-template.md",content:fE()},{path:"adr/INDEX.md",content:mE()},{path:xt,content:ko()},...t.trackerProvider==="internal"?[{path:Ao,content:Dm(t.youtrackProjectKey??Ni)},{path:$n,content:fl()}]:[]]}function dE(){return`# model/ \u2014 the project map
52
+ `)[0]))return;await r.raw(["reset","--hard","HEAD~1"])}catch{}}var Jm,ms=E(()=>{"use strict";M();Le();Jm=5});function Hn(t,e,r,n){let o=t.trackerProvider==="internal";return[{path:"README.md",content:eR(t,e)},{path:".gitignore",content:qE()},{path:"project.yaml",content:o?ih(t):uh(t,n)},{path:"CLAUDE.md",content:VE(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:YE()},{path:"knowledge/README.md",content:zE()},{path:"knowledge/build.yaml",content:QE()},{path:"actions/README.md",content:XE()},{path:"roles/README.md",content:JE()},{path:"skills/README.md",content:ZE()},{path:"model/README.md",content:FE()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:WE()},{path:"adr/README.md",content:GE()},{path:"adr/0000-template.md",content:KE()},{path:"adr/INDEX.md",content:HE()},{path:Tt,content:Ro()},...t.trackerProvider==="internal"?[{path:Mo,content:rh(t.youtrackProjectKey??Ki)},{path:Cn,content:wl()}]:[]]}function FE(){return`# model/ \u2014 the project map
52
53
 
53
54
  A graph of the project built from **git history and task artifacts**: files
54
55
  and directories connected by the fact of changing together and the fact of
@@ -75,7 +76,7 @@ asset \u2014 treat it like \`knowledge/\`.
75
76
 
76
77
  Every YAML file carries \`modelFormatVersion\`; a reader that meets a
77
78
  different version treats it as "rebuild needed", not as an error.
78
- `}function pE(){return`# ADR \u2014 architecture decision records
79
+ `}function GE(){return`# ADR \u2014 architecture decision records
79
80
 
80
81
  Accepted architectural decisions of this project \u2014 its **framework**. The
81
82
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -103,7 +104,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
103
104
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
104
105
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
105
106
  open a PR to this repository.
106
- `}function fE(){return`# ADR-NNNN: <title>
107
+ `}function KE(){return`# ADR-NNNN: <title>
107
108
 
108
109
  - **Status:** accepted | superseded by ADR-NNNN
109
110
  - **Date:** YYYY-MM-DD
@@ -125,12 +126,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
125
126
  ## Alternatives considered
126
127
 
127
128
  - **<alternative>** \u2014 why it was rejected.
128
- `}function mE(){return`# ADR index
129
+ `}function HE(){return`# ADR index
129
130
 
130
131
  <!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
131
132
 
132
133
  (no accepted ADRs yet)
133
- `}function hE(){return`# Audit
134
+ `}function WE(){return`# Audit
134
135
 
135
136
  Pipeline event logs. Naming is per-writer: each codepipe
136
137
  project appends only to its own file \u2014
@@ -139,14 +140,13 @@ project appends only to its own file \u2014
139
140
 
140
141
  \u2014 so several team members' CLIs never contend on one file. Do not create a
141
142
  shared aggregate here.
142
- `}function Lt(t,e,r,n,o=tt,i){let s=t.trackerProvider==="internal";return{projectYaml:s?EE(t):RE(t,r,n),regimenYaml:TE(t.automationLevel,s?!0:e,s,o,i)}}function gE(){return`# codepipe project config is local to each member's workspace
143
- project.yaml
144
- regimen.yaml
143
+ `}function _t(t,e,r,n,o=it,i){let s=t.trackerProvider==="internal";return{localYaml:tR(t.automationLevel,s?!0:e,s,o,i,s?void 0:n)}}function qE(){return`# codepipe personal config is local to each member's workspace
144
+ local.yaml
145
145
 
146
146
  # codepipe runtime
147
147
  session.log
148
148
  apply-queue.json
149
- `}function yE(){return`# Index prompt
149
+ `}function YE(){return`# Index prompt
150
150
 
151
151
  You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
152
152
  navigation map of this project's repositories and save it to the Context Repo, so
@@ -203,7 +203,7 @@ current working directory; write nothing else under the Context Repo.
203
203
  Keep both durable and skimmable \u2014 they are read at the start of every future
204
204
  task. Prefer structure (headings, bullet lists) over prose. If a repository is
205
205
  empty or unavailable, say so briefly rather than inventing content.
206
- `}function wE(t){return`# Project context for the CodePipe agent
206
+ `}function VE(t){return`# Project context for the CodePipe agent
207
207
 
208
208
  Instructions for AI agents working on **${t.name}** tasks. Claude Code
209
209
  auto-loads this file when the Context Repo is mounted. Keep it short and
@@ -231,7 +231,7 @@ project's architectural invariants: read them at the start of a task and treat
231
231
  them as binding. New or changed decisions do **not** go here directly \u2014 during
232
232
  analysis you draft them as task artifacts, and they are promoted into \`adr/\`
233
233
  only after the analysis is approved.
234
- `}function bE(){return`# Knowledge
234
+ `}function zE(){return`# Knowledge
235
235
 
236
236
  Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
237
237
  **memory** across tasks. Architectural decisions, domain rules,
@@ -248,7 +248,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
248
248
  concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
249
249
  REGENERATED from the entries by the index job: don't hand-edit it, and treat
250
250
  any merge conflict in it as noise (either side converges on the next run).
251
- `}function kE(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
251
+ `}function XE(){return`# actions/ \u2014 custom project actions (the dashboard's RUN tab)
252
252
 
253
253
  One \`<id>.yml\` per action. Every file here appears as a button on the
254
254
  project's **RUN** tab; an action with \`params\` opens a small wizard first.
@@ -287,7 +287,7 @@ steps:
287
287
  Parameter values are passed to the commands **only as env vars** \u2014 reference
288
288
  them as \`$INPUT_<NAME>\` in \`run\`; they are never substituted into the
289
289
  command text itself.
290
- `}function vE(){return`# roles/ \u2014 who reviews your work
290
+ `}function JE(){return`# roles/ \u2014 who reviews your work
291
291
 
292
292
  A **role** is a critic with a narrow view and its own curated context: one
293
293
  \`<name>.md\` per role. Roles review a plan before the work starts, review the
@@ -315,7 +315,7 @@ You are the security critic. \u2026the body is the role's prompt\u2026
315
315
 
316
316
  Keep \`refs\` short and specific: the value of a role is a NARROW view, and
317
317
  "give it everything" is exactly the failure this design avoids.
318
- `}function $E(){return`# skills/ \u2014 procedures the agent can invoke
318
+ `}function ZE(){return`# skills/ \u2014 procedures the agent can invoke
319
319
 
320
320
  A **skill** is a directory with a \`SKILL.md\`: a description of when to use it,
321
321
  a body with the steps, and any files the steps need beside it (scripts,
@@ -374,7 +374,7 @@ A third-party marketplace **must** name a full commit sha: its skills run beside
374
374
  your checked-out code with the agent's credentials, and a branch would let that
375
375
  code change between two runs of the same task. Nothing from a marketplace is
376
376
  active until it is listed in \`plugins\`.
377
- `}function xE(){return`# BUILD phase config. Discovered & maintained by the agent.
377
+ `}function QE(){return`# BUILD phase config. Discovered & maintained by the agent.
378
378
  # Steps run in a rootless Podman container in the SANDBOX, before the PR.
379
379
  # Success = every step exits 0. Credentials are NOT available inside the container.
380
380
  #
@@ -390,7 +390,7 @@ active until it is listed in \`plugins\`.
390
390
  # - name: test
391
391
  # run: npm test
392
392
  # timeout_sec: 600 # per-step timeout (optional, default 600)
393
- `}function SE(t,e){return`# ${e.name}
393
+ `}function eR(t,e){return`# ${e.name}
394
394
 
395
395
  Context Repo for the **${t.name}** project (CodePipe).
396
396
 
@@ -407,16 +407,18 @@ machine. It carries:
407
407
  - \`tasks/<ISSUE-ID>/\` \u2014 synced task data, artifacts, patches, audit.
408
408
  - \`audit/\` \u2014 project-wide event log.
409
409
 
410
- The codepipe project config (\`project.yaml\`/\`regimen.yaml\`) is **not** part of
411
- this repository: it lives untracked next to each member's clone.
410
+ The team-shared project config (\`project.yaml\`) **is** part of this repository:
411
+ it is tracked, reviewed and versioned. Each member's personal config
412
+ (\`local.yaml\` \u2014 automation level, LLM binding, assignee filter) lives untracked
413
+ next to their own clone and never enters this history.
412
414
 
413
- You can edit \`CLAUDE.md\`, \`prompts/\`, \`knowledge/\` and \`adr/\` through
415
+ You can edit \`project.yaml\`, \`CLAUDE.md\`, \`prompts/\`, \`knowledge/\` and \`adr/\` through
414
416
  PRs to this repository (and the agent also writes to \`knowledge/\` and
415
417
  \`CLAUDE.md\`). Files under \`tasks/\` are written by the CLI on behalf of the
416
418
  pipeline \u2014 don't edit them by hand.
417
419
 
418
420
  Automation level: **${t.automationLevel}**.
419
- `}function EE(t){return`# Project description for CodePipe.
421
+ `}function ih(t){return`# Project description for CodePipe.
420
422
  id: ${t.projectId}
421
423
  name: ${t.name}
422
424
 
@@ -441,9 +443,9 @@ adapters:
441
443
  # Branch (must keep the <TASK_ID> placeholder).
442
444
  branch:
443
445
  pattern: codepipe/<TASK_ID>
444
- ${Fm()}${Gm(t)}
446
+ ${sh()}${ch(t)}
445
447
  repos:
446
- ${Km(t)}
448
+ ${lh(t)}
447
449
  # A repo may declare a mirror \u2014 a repository CodePipe owns that stands in for
448
450
  # origin for the whole pipeline: task branches, PRs and merges happen there and
449
451
  # your own repository is never written. All-or-nothing: either every repo
@@ -453,7 +455,7 @@ ${Km(t)}
453
455
  # host: github
454
456
  # owner: your-org
455
457
  # repo: <project>-api-mirror
456
- `}function Fm(){return`
458
+ ${ah()}`}function sh(){return`
457
459
  # Git workflow. Omit this whole section for the default single-branch flow
458
460
  # (\`simple\`) \u2014 nothing changes from today. Presets bind branch ROLES to your
459
461
  # real branch names (names differ across projects: develop vs dev, main vs a
@@ -468,177 +470,8 @@ ${Km(t)}
468
470
  # integration: develop
469
471
  # stable: master
470
472
  # # release_pattern: "release/*" # with flow: release
471
- `}function Gm(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
472
- # Languages the agent writes in, per area. \`auto\` = mirror the language of
473
- # the user's material. Also editable from the dashboard: project card \u2192
474
- # Settings \u2192 Language.
475
- language:
476
- ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
477
- `)}
478
- `}function Km(t){return t.repos.length===0?` [] # add repos here
479
- `:t.repos.map(e=>` - name: ${e.name}
480
- host: ${e.host}
481
- owner: ${e.owner}
482
- repo: ${e.repoName}
483
- mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
484
- default_branch: ${e.defaultBranch}`:"")).join(`
485
- `)}function RE(t,e,r){let n=e?`
486
- tracker_url: ${e}`:`
487
- # tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
488
- assignee: ${r}`:`require_assignee: false
489
- # assignee: your.youtrack.login`,i=t.youtrackProjectKey?` project_key: ${t.youtrackProjectKey}${n}
490
- poll_interval_sec: 60
491
- # Name of the YT workflow field the board is driven by. Default: Stage
492
- # (custom field); YouTrack's standard configuration uses State.
493
- # stage_field: State
494
- # Values of the workflow field above. A task in one of these stages enters
495
- # the QUEUE section of the dashboard's TODO tab. With gates.require_approval
496
- # off it is taken into work immediately (conveyor); with it on it waits in
497
- # QUEUE for the operator's single CONFIRM.
498
- source_columns:
499
- - Develop
500
- # Tasks from this YT column land in the BACKLOG section of the TODO tab \u2014
501
- # they sync, but do not enter the QUEUE until moved there (Add to queue) or
502
- # dragged into a source_columns stage. Optional: remove to disable BACKLOG.
503
- backlog_column: Backlog
504
- # Optional: backlog role scope. personal (default, or key missing) \u2014 only
505
- # tasks assigned to the assignee below. shared \u2014 any unaccepted tracker task
506
- # in backlog_column, for a board that IS the team's shared queue.
507
- # backlog_scope: shared
508
- # Optional: YT stages meaning the task is completed. A task in one of these
509
- # stages is synced to DONE and leaves the board (must not overlap the stages
510
- # above). Its open PR is left untouched. Remove the key to disable.
511
- # done_columns:
512
- # - Done
513
- # Optional: YT stages that request an EXTERNAL code review. When a human
514
- # developer moves an issue into one of these stages, CodePipe finds the
515
- # developer's branch (any name) and the agent reviews it \u2014 posting the
516
- # findings per regimen.yaml code_review.external.mode. Remove to disable.
517
- # review_columns:
518
- # - Code Review
519
- # Optional: statuses offered for manual switching from the task card (a
520
- # per-project allow-list; can include statuses outside the pipeline roles
521
- # above). Remove/empty to hide the manual switcher.
522
- # status_columns:
523
- # - Develop
524
- # - In Progress
525
- # - Review
526
- # - Done
527
- # Sync gate on assignee. require_assignee=false (or the key missing) \u2014
528
- # behavior unchanged. When true, CodePipe only pulls tasks of the given
529
- # assignee (YT login) into the pipeline; without assignee \u2014 any task with a
530
- # non-empty assignee. assignee only takes effect when require_assignee=true.
531
- ${o}`:` # project_key: \u2026
532
- # tracker_url: https://your.youtrack.cloud
533
- poll_interval_sec: 60`,s=Km(t);return`# Project description for CodePipe.
534
- id: ${t.projectId}
535
- name: ${t.name}
536
-
537
- youtrack:
538
- ${i}
539
-
540
- adapters:
541
- tracker: youtrack
542
-
543
- # How approved changes reach the project repos:
544
- # auto \u2014 HUB dispatches the apply plan; CLI pushes a branch and opens a PR.
545
- # local \u2014 HUB waits; you apply the patch into your local checkout via the
546
- # CLI REPL (/apply or /unstash) and commit/push yourself.
547
- # Who merges the pull request:
548
- # off (default) \u2014 you do, from the task card (or @codepipe approve).
549
- # on_ci_green \u2014 CodePipe merges as soon as the PR is open, conflict-free
550
- # and its CI is green. Full automation only; the host's
551
- # branch protection still applies.
552
- # auto_merge: off
553
-
554
- # How the agent's code changes reach the repo: a single git-native
555
- # transport. The SANDBOX pushes a self-contained delivery commit to the Context
556
- # Repo (codepipe/deliveries/\u2026) \u2014 never the project repo \u2014 and the CLI fetches it,
557
- # re-parents it on the base, and applies it (push + PR for apply.mode: auto, or
558
- # into local clones for apply.mode: local). No per-project knob to configure.
559
-
560
- # Task-branch name template. <TASK_ID> \u2192 lower-cased tracker key (e.g.
561
- # codepipe/dev-109). Also editable from the dashboard: project card \u2192 Settings \u2192
562
- # Branch (must keep the <TASK_ID> placeholder).
563
- branch:
564
- pattern: codepipe/<TASK_ID>
565
- ${Fm()}${Gm(t)}
566
- repos:
567
- ${s}
568
- `}function TE(t,e,r=!1,n=tt,o){let i=t==="full",s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
569
- # model in the recommended per-role split, so CodePipe set a single default
570
- # your subscription can serve for all roles. Tune per role later from the
571
- # dashboard (Project Settings \u2192 llm.models) or by editing this file.
572
- models:
573
- default: ${o}`:` # Per-role model selection. COMMENTED OUT on purpose: models come from
574
- # the workflow preset above (explicit keys here would override the preset \u2014
575
- # that is exactly what this section is for when you need it). Values are
576
- # aliases (opus | sonnet | haiku) \u2014 Claude Code resolves each to the current
577
- # version of that tier \u2014 or a pinned id (e.g. claude-opus-4-8). 'default'
578
- # is a catch-all that overrides the preset and the recommended defaults for
579
- # every role not spelled out.
580
- # models:
581
- # default: sonnet
582
- # analyze: opus # architectural analysis of the task
583
- # implement: opus # writing the implementation
584
- # resolve-conflict: opus # resolving merge conflicts is code reasoning
585
- # rework: opus # re-implementing after rework feedback
586
- # estimate: sonnet # informational implementation estimate
587
- # build: haiku # mechanical run of the recorded build steps
588
- # build-discovery: opus # first BUILD: discover tooling, write build.yaml
589
- # code-review: opus # reviewing the change before the PR
590
- # code-review-verify: sonnet # verifying findings is narrower \u2014 cheaper
591
- # draft: sonnet # drafting a new issue from the Quick-task panel
592
- # index: opus # one-shot repository indexing at registration
593
- # backfill: opus # retrospective ADR backfill \u2014 deep reasoning
594
- # analysis: opus # decomposing a context into a package of tasks
595
- # chat: opus # the interactive draft chat
596
- # config: opus # the project-configuration chat
597
- # observer: opus # reads a whole batch \u2014 runs once per batch
598
- # council: opus # unblocks a task; a wrong answer compounds
599
- # testing: opus # deriving how a human would check the change`;return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
600
- automation:
601
- level: ${t}
602
-
603
- youtrack:
604
- ${r?` # The built-in tracker is CodePipe's own \u2014 these switches stay on (there
605
- # is no external system to protect with a read-only mode). The block keeps
606
- # the same keys as a YouTrack project so the settings machinery is shared.`:` # Master switch. With enabled=false CodePipe never writes to YouTrack,
607
- # regardless of the per-action flags below.
608
- # These flags are set from a dedicated 'codepipe init' question and do
609
- # NOT depend on automation.level \u2014 the two are orthogonal axes (writes vs gates).`}
610
- writes:
611
- enabled: ${s}
612
- status_changes: ${s}
613
- pr_comment: ${s}
614
- # Mirror dashboard comments back into YouTrack. Off without enabled.
615
- dashboard_mirror: ${s}
616
- # YT column (Stage) for new drafts published from PLAN.
617
- # Backlog by default \u2192 the task shows up in the TODO section, not straight in WORK.
618
- draft_target_status: Backlog
619
- # YT stage (Stage) that CodePipe moves a task to when it enters TRACKING
620
- # (PR opened / ready for review). Applies only with writes.enabled
621
- # + status_changes. Review by default.
622
- review_status: Review
623
-
624
- gates:
625
- # G1..G4 are Reserved \u2014 NOT consumed yet. The G1\u2013G4 gates are driven by
626
- # automation.level (an editable dashboard setting): 'full' auto-passes G1..G4,
627
- # 'assisted' requires a manual Run/Approve at each. Names and modes mirror
628
- # docs/PIPELINE.md so a future per-gate parser stays config-compatible.
629
- # Modes: always | auto_below_hours | never.
630
- G1_estimate: { mode: ${i?"never":"always"} }
631
- G2_solution: { mode: ${i?"never":"always"} }
632
- G3_implementation: { mode: ${i?"never":"always"} }
633
- G4_apply: { mode: ${i?"never":"always"} }
634
- # The first ACTUALLY consumed key of the gates block. When true (the
635
- # default), a task taken from a source stage lands in the QUEUE section
636
- # (QUEUED) and waits for a single Confirm; the Confirm pulls in the
637
- # dependency closure (depends on) and topologically orders the queue, then
638
- # the whole queue enters the pipeline. Set false for conveyor mode: each
639
- # task starts the pipeline immediately. Orthogonal to automation.level.
640
- require_approval: true
641
-
473
+ `}function ah(){return`
474
+ # --- Team pipeline settings (shared, reviewed; tweak via PR) ---
642
475
  workflow:
643
476
  # How much pipeline a task gets. A preset is a LAYER of defaults \u2014 any
644
477
  # explicit setting in this file always wins over it.
@@ -688,7 +521,7 @@ code_review:
688
521
  # Cap on CODE_REVIEW\u2194IMPLEMENTING remarks rounds before NEEDS_MANUAL.
689
522
  max_iterations: 2
690
523
  # External review (a task a human developer moved into a review-role tracker
691
- # column \u2014 see review_columns in project.yaml). What to do with the findings:
524
+ # column \u2014 see review_columns above). What to do with the findings:
692
525
  # comment \u2014 post them on the developer's PR (or into the tracker
693
526
  # issue when no open PR is found), then the task is done;
694
527
  # fix_in_branch \u2014 commit the fixes directly on top of the developer's
@@ -755,11 +588,158 @@ rework:
755
588
  archive_window_days: 14
756
589
 
757
590
  llm:
758
- # LLM backend for this project. Currently only \`claude\` is supported;
759
- # this line is the anchor for future providers.
760
- provider: ${n}
761
- ${a}
762
- # Per-role reasoning effort (low | medium | high | xhigh). Only the
591
+ # Per-role reasoning effort (low | medium | high | xhigh) \u2014 a TEAM cost
592
+ # policy (the member-personal provider/models binding lives in local.yaml). Only the mechanical roles are lowered \u2014 an unlisted role keeps
593
+ # Claude Code's own default effort. Values below are the recommended defaults
594
+ # and apply even when this section is omitted. Ignored (with a log) by a
595
+ # Claude Code too old to support --effort.
596
+ effort:
597
+ # Mechanical run of the recorded build steps.
598
+ build: low
599
+ # Informational estimate \u2014 nothing depends on it.
600
+ estimate: low
601
+ # Templated issue drafting.
602
+ draft: medium
603
+ # Navigation map, not deep reasoning.
604
+ index: medium
605
+ # Verifying existing review findings is narrower than finding them.
606
+ code-review-verify: medium
607
+
608
+ # Concurrency is not a per-project setting: it is the operator-set per-account
609
+ # sandbox quota (how many runners the account may occupy), enforced by the HUB
610
+ # and sized on the farm. A solo 'codepipe up' runs one worker.
611
+ `}function ch(t){let e=t.language;return!e||Object.keys(e).length===0?"":`
612
+ # Languages the agent writes in, per area. \`auto\` = mirror the language of
613
+ # the user's material. Also editable from the dashboard: project card \u2192
614
+ # Settings \u2192 Language.
615
+ language:
616
+ ${Object.entries(e).map(([n,o])=>` ${n}: ${o}`).join(`
617
+ `)}
618
+ `}function lh(t){return t.repos.length===0?` [] # add repos here
619
+ `:t.repos.map(e=>` - name: ${e.name}
620
+ host: ${e.host}
621
+ owner: ${e.owner}
622
+ repo: ${e.repoName}
623
+ mount_as: ${e.mountAs??e.name}`+(e.defaultBranch?`
624
+ default_branch: ${e.defaultBranch}`:"")).join(`
625
+ `)}function hs(t,e){return t.trackerProvider==="internal"?ih(t):uh(t,e)}function uh(t,e){let r=e?`
626
+ tracker_url: ${e}`:`
627
+ # tracker_url: https://your.youtrack.cloud`,n=t.youtrackProjectKey?` project_key: ${t.youtrackProjectKey}${r}
628
+ poll_interval_sec: 60
629
+ # Name of the YT workflow field the board is driven by. Default: Stage
630
+ # (custom field); YouTrack's standard configuration uses State.
631
+ # stage_field: State
632
+ # Values of the workflow field above. A task in one of these stages enters
633
+ # the QUEUE section of the dashboard's TODO tab. With gates.require_approval
634
+ # off it is taken into work immediately (conveyor); with it on it waits in
635
+ # QUEUE for the operator's single CONFIRM.
636
+ source_columns:
637
+ - Develop
638
+ # Tasks from this YT column land in the BACKLOG section of the TODO tab \u2014
639
+ # they sync, but do not enter the QUEUE until moved there (Add to queue) or
640
+ # dragged into a source_columns stage. Optional: remove to disable BACKLOG.
641
+ backlog_column: Backlog
642
+ # Optional: backlog role scope. personal (default, or key missing) \u2014 only
643
+ # tasks assigned to the assignee below. shared \u2014 any unaccepted tracker task
644
+ # in backlog_column, for a board that IS the team's shared queue.
645
+ # backlog_scope: shared
646
+ # Optional: YT stages meaning the task is completed. A task in one of these
647
+ # stages is synced to DONE and leaves the board (must not overlap the stages
648
+ # above). Its open PR is left untouched. Remove the key to disable.
649
+ # done_columns:
650
+ # - Done
651
+ # Optional: YT stages that request an EXTERNAL code review. When a human
652
+ # developer moves an issue into one of these stages, CodePipe finds the
653
+ # developer's branch (any name) and the agent reviews it \u2014 posting the
654
+ # findings per code_review.external.mode. Remove to disable.
655
+ # review_columns:
656
+ # - Code Review
657
+ # Optional: statuses offered for manual switching from the task card (a
658
+ # per-project allow-list; can include statuses outside the pipeline roles
659
+ # above). Remove/empty to hide the manual switcher.
660
+ # status_columns:
661
+ # - Develop
662
+ # - In Progress
663
+ # - Review
664
+ # - Done
665
+ # YT column (Stage) for new drafts published from PLAN. Backlog by default \u2192
666
+ # the task shows up in the TODO section, not straight in WORK.
667
+ draft_target_status: Backlog
668
+ # YT stage (Stage) that CodePipe moves a task to when it enters TRACKING (PR
669
+ # opened / ready for review). Applies only with writes.enabled + status_changes.
670
+ review_status: Review
671
+ # The personal assignee filter (youtrack.assignee / require_assignee) and the
672
+ # YouTrack write switches (youtrack.writes) live in .codepipe/local.yaml \u2014
673
+ # they are per-member and NOT part of this shared, reviewed file.`:` # project_key: \u2026
674
+ # tracker_url: https://your.youtrack.cloud
675
+ poll_interval_sec: 60`,o=lh(t);return`# Project description for CodePipe (team-shared, tracked in the Context Repo).
676
+ id: ${t.projectId}
677
+ name: ${t.name}
678
+
679
+ youtrack:
680
+ ${n}
681
+
682
+ adapters:
683
+ tracker: youtrack
684
+
685
+ # How approved changes reach the project repos:
686
+ # auto \u2014 HUB dispatches the apply plan; CLI pushes a branch and opens a PR.
687
+ # local \u2014 HUB waits; you apply the patch into your local checkout via the
688
+ # CLI REPL (/apply or /unstash) and commit/push yourself.
689
+ # Who merges the pull request:
690
+ # off (default) \u2014 you do, from the task card (or @codepipe approve).
691
+ # on_ci_green \u2014 CodePipe merges as soon as the PR is open, conflict-free
692
+ # and its CI is green. Full automation only; the host's
693
+ # branch protection still applies.
694
+ # auto_merge: off
695
+
696
+ # How the agent's code changes reach the repo: a single git-native
697
+ # transport. The SANDBOX pushes a self-contained delivery commit to the Context
698
+ # Repo (codepipe/deliveries/\u2026) \u2014 never the project repo \u2014 and the CLI fetches it,
699
+ # re-parents it on the base, and applies it (push + PR for apply.mode: auto, or
700
+ # into local clones for apply.mode: local). No per-project knob to configure.
701
+
702
+ # Task-branch name template. <TASK_ID> \u2192 lower-cased tracker key (e.g.
703
+ # codepipe/dev-109). Also editable from the dashboard: project card \u2192 Settings \u2192
704
+ # Branch (must keep the <TASK_ID> placeholder).
705
+ branch:
706
+ pattern: codepipe/<TASK_ID>
707
+ ${sh()}${ch(t)}
708
+ repos:
709
+ ${o}
710
+ ${ah()}`}function tR(t,e,r=!1,n=it,o,i){let s=e?"true":"false",a=o?` # Model selection. This project's Claude subscription did not include every
711
+ # model in the recommended per-role split, so CodePipe set a single default
712
+ # your subscription can serve for all roles. Tune per role later from the
713
+ # dashboard (Project Settings \u2192 llm.models) or by editing this file.
714
+ models:
715
+ default: ${o}`:` # Per-role model selection. COMMENTED OUT on purpose: models come from
716
+ # the workflow preset (workflow.preset in the shared project.yaml; explicit
717
+ # keys here would override the preset \u2014
718
+ # that is exactly what this section is for when you need it). Values are
719
+ # aliases (opus | sonnet | haiku) \u2014 Claude Code resolves each to the current
720
+ # version of that tier \u2014 or a pinned id (e.g. claude-opus-4-8). 'default'
721
+ # is a catch-all that overrides the preset and the recommended defaults for
722
+ # every role not spelled out.
723
+ # models:
724
+ # default: sonnet
725
+ # analyze: opus # architectural analysis of the task
726
+ # implement: opus # writing the implementation
727
+ # resolve-conflict: opus # resolving merge conflicts is code reasoning
728
+ # rework: opus # re-implementing after rework feedback
729
+ # estimate: sonnet # informational implementation estimate
730
+ # build: haiku # mechanical run of the recorded build steps
731
+ # build-discovery: opus # first BUILD: discover tooling, write build.yaml
732
+ # code-review: opus # reviewing the change before the PR
733
+ # code-review-verify: sonnet # verifying findings is narrower \u2014 cheaper
734
+ # draft: sonnet # drafting a new issue from the Quick-task panel
735
+ # index: opus # one-shot repository indexing at registration
736
+ # backfill: opus # retrospective ADR backfill \u2014 deep reasoning
737
+ # analysis: opus # decomposing a context into a package of tasks
738
+ # chat: opus # the interactive draft chat
739
+ # config: opus # the project-configuration chat
740
+ # observer: opus # reads a whole batch \u2014 runs once per batch
741
+ # council: opus # unblocks a task; a wrong answer compounds
742
+ # testing: opus # deriving how a human would check the change`,c=` # Per-role reasoning effort (low | medium | high | xhigh). Only the
763
743
  # mechanical roles are lowered \u2014 an unlisted role keeps Claude Code's own
764
744
  # default effort. Values below are the recommended defaults and apply even
765
745
  # when this section is omitted. Ignored (with a log) by a Claude Code too
@@ -774,42 +754,76 @@ ${a}
774
754
  # Navigation map, not deep reasoning.
775
755
  index: medium
776
756
  # Verifying existing review findings is narrower than finding them.
777
- code-review-verify: medium
757
+ code-review-verify: medium`,l=r?` # The built-in tracker is CodePipe's own \u2014 these switches stay on (there
758
+ # is no external system to protect with a read-only mode). The block keeps
759
+ # the same keys as a YouTrack project so the settings machinery is shared.`:` # Master switch. With enabled=false CodePipe never writes to YouTrack,
760
+ # regardless of the per-action flags below.
761
+ # These flags are set from a dedicated 'codepipe init' question and do
762
+ # NOT depend on automation.level \u2014 the two are orthogonal axes (writes vs gates).`,u=r?"":i?` # Sync gate on assignee: only tasks of this YouTrack login enter the pipeline.
763
+ require_assignee: true
764
+ assignee: ${i}
765
+ `:` # Sync gate on assignee. Set require_assignee=true to only pull tasks of the
766
+ # login below (leave assignee unset to pull any assigned task).
767
+ # require_assignee: false
768
+ # assignee: your.youtrack.login
769
+ `;return`# CodePipe personal config (local.yaml) \u2014 UNTRACKED, per member.
770
+ # Only these allow-listed personal keys have effect here; team settings live in
771
+ # the tracked project.yaml. Values here override project.yaml one level deep.
778
772
 
779
- # Concurrency is not a per-project setting: it is the operator-set per-account
780
- # sandbox quota (how many runners the account may occupy), enforced by the HUB
781
- # and sized on the farm. A solo 'codepipe up' runs one worker. (ADR-0030)
773
+ automation:
774
+ # assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass.
775
+ level: ${t}
776
+
777
+ gates:
778
+ # When on (default), a task taken from a source stage waits in the QUEUE for a
779
+ # single Confirm before the pipeline starts. Off \u21D2 conveyor. Orthogonal to
780
+ # automation.level.
781
+ require_approval: true
782
+
783
+ youtrack:
784
+ ${u}${l}
785
+ writes:
786
+ enabled: ${s}
787
+ status_changes: ${s}
788
+ pr_comment: ${s}
789
+ # Mirror dashboard comments back into YouTrack. Off without enabled.
790
+ dashboard_mirror: ${s}
782
791
 
783
- `}var Hr=E(()=>{"use strict";M();ns()});function Xm(t){zm=t}function mt(t,e="info"){zm(t,e)}var zm,is=E(()=>{"use strict";zm=t=>console.log(t)});import{homedir as KE,tmpdir as jL}from"node:os";import{existsSync as HE,mkdirSync as WE,mkdtempSync as OL,rmSync as LL}from"node:fs";import{join as gl}from"node:path";import{simpleGit as yl}from"simple-git";function Oe(t,e,r){let n=r??gl(KE(),".codepipe","repos");return gl(n,t,e)}async function hr(t,e,r={}){let n=Oe(t,e.name,r.baseDir),o=r.cloneUrlOverride??bl(e);if(!HE(gl(n,".git"))){WE(n,{recursive:!0});let c=yl();mt(`[git] clone ${o} \u2192 ${n}`);try{await c.clone(o,n)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`git clone failed: ${o}
784
- ${u.trim()}`)}}let i=yl(n),s=(await i.remote(["get-url","origin"]).catch(()=>"")||"").toString().trim();s&&s!==o&&(mt(`[git] ${e.name}: origin ${s} \u2192 ${o} (spec changed)`),await i.remote(["set-url","origin",o]));try{await i.fetch()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git fetch failed in ${n}
785
- ${l.trim()}`)}let a=e.defaultBranch??"main";return await i.checkout(["-B",a,`origin/${a}`]).catch(()=>{}),i}async function Bn(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function qE(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&&mt(`[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 Bn(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Bn(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([...wl,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function YE(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await Bn(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Bn(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 Zm(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 YE(t,i,()=>qE(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let f=`origin/${c}`;await Bn(t,f)||(f=`origin/${u??c}`);let m=(await t.revparse([f])).trim(),y=0;if(m===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{y=parseInt((await t.raw(["rev-list","--count",`${s}..${m}`]).catch(()=>"1")).trim(),10)||1,await t.checkout(["-B",a,f]);try{await t.raw([...wl,"cherry-pick",d])}catch(k){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let x=k instanceof Error?k.message:String(k);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
786
- ${x.trim()}`)}}let b=(await t.revparse(["HEAD"])).trim(),w=r.push!==!1;if(w){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:b,pushed:w,...y>0?{baseMoved:y}:{}}}async function Qm(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 eh(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await Bn(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(`
792
+ llm:
793
+ # LLM backend for this project. Currently only \`claude\` is supported;
794
+ # this line is the anchor for future providers.
795
+ provider: ${n}
796
+ ${a}
797
+ `}var Zr=E(()=>{"use strict";M();ms()});function yh(t){gh=t}function bt(t,e="info"){gh(t,e)}var gh,ys=E(()=>{"use strict";gh=t=>console.log(t)});import{homedir as fR,tmpdir as uM}from"node:os";import{existsSync as mR,mkdirSync as hR,mkdtempSync as pM,rmSync as fM}from"node:fs";import{join as El}from"node:path";import{simpleGit as Rl}from"simple-git";function Ue(t,e,r){let n=r??El(fR(),".codepipe","repos");return El(n,t,e)}async function br(t,e,r={}){let n=Ue(t,e.name,r.baseDir),o=r.cloneUrlOverride??Il(e);if(!mR(El(n,".git"))){hR(n,{recursive:!0});let c=Rl();bt(`[git] clone ${o} \u2192 ${n}`);try{await c.clone(o,n)}catch(l){let u=l instanceof Error?l.message:String(l);throw new Error(`git clone failed: ${o}
798
+ ${u.trim()}`)}}let i=Rl(n),s=(await i.remote(["get-url","origin"]).catch(()=>"")||"").toString().trim();s&&s!==o&&(bt(`[git] ${e.name}: origin ${s} \u2192 ${o} (spec changed)`),await i.remote(["set-url","origin",o]));try{await i.fetch()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git fetch failed in ${n}
799
+ ${l.trim()}`)}let a=e.defaultBranch??"main";return await i.checkout(["-B",a,`origin/${a}`]).catch(()=>{}),i}async function Wn(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}async function gR(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&&bt(`[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 Wn(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Wn(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([...Tl,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function yR(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await Wn(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Wn(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 bh(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 yR(t,i,()=>gR(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));p&&await t.raw(["branch","-D",a]).catch(()=>{});let f=`origin/${c}`;await Wn(t,f)||(f=`origin/${u??c}`);let m=(await t.revparse([f])).trim(),y=0;if(m===s)await t.raw(["branch","-f",a,d]),await t.checkout(a);else{y=parseInt((await t.raw(["rev-list","--count",`${s}..${m}`]).catch(()=>"1")).trim(),10)||1,await t.checkout(["-B",a,f]);try{await t.raw([...Tl,"cherry-pick",d])}catch(k){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let x=k instanceof Error?k.message:String(k);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
800
+ ${x.trim()}`)}}let b=(await t.revparse(["HEAD"])).trim(),w=r.push!==!1;if(w){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:b,pushed:w,...y>0?{baseMoved:y}:{}}}async function kh(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 vh(t,e,r){let{branchName:n,dropTaskKeys:o}=r,i=`origin/${n}`;if(!await Wn(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(`
787
801
  `).map(f=>f.trim()).filter(f=>f.length>0),l=new Set(o.map(f=>f.toUpperCase())),u=[],p=0;for(let f of c)(await t.raw(["show","-s","--format=%(trailers:key=CodePipe-Task,valueonly)",f])).split(`
788
- `).map(b=>b.trim().toUpperCase()).filter(b=>b.length>0).some(b=>l.has(b))?p++:u.push(f);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let f of u)try{await t.raw([...wl,"cherry-pick","--allow-empty","--keep-redundant-commits",f])}catch(m){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let y=m instanceof Error?m.message:String(m);throw new Error(`rewrite_cluster_branch: replaying ${f.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
789
- ${y.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function th(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 bl(t){return t.mirror?Jm(t.mirror.host,t.mirror.owner,t.mirror.repoName):Jm(t.host,t.owner,t.repoName)}function Jm(t,e,r){return t==="github"?`git@github.com:${e}/${r}.git`:t==="gitlab"?`git@gitlab.com:${e}/${r}.git`:`git@bitbucket.org:${e}/${r}.git`}function Fn(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 ss(t){return(await yl().listRemote(["--heads",t])).split(`
790
- `).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 rh(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var wl,Gn=E(()=>{"use strict";is();wl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as VE,createDecipheriv as zE,createHash as XE,createPrivateKey as JE,createPublicKey as kl,diffieHellman as nh,generateKeyPairSync as oh,hkdfSync as ih,randomBytes as ZE}from"node:crypto";function as(){let{publicKey:t,privateKey:e}=oh("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ze(t){let e=Buffer.from(t,"base64");return(XE("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Zt(t,e){let r=kl({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=oh("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=nh({privateKey:o,publicKey:r}),c=Buffer.from(ih("sha256",a,Buffer.concat([i,s]),sh,32)),l=ZE(12),u=VE("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),f=u.getAuthTag(),m={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:f.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(m),"utf-8").toString("base64")}function Kn(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=JE({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=kl({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=kl(n).export({type:"spki",format:"der"}),a=nh({privateKey:n,publicKey:o}),c=Buffer.from(ih("sha256",a,Buffer.concat([i,s]),sh,32)),l=zE("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 sh,ht=E(()=>{"use strict";sh=Buffer.from("devpipe-sealedbox-v1","utf-8")});function Ho(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 Wo(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 qo(t,e=process.env){if(!t)return!1;let r=`https://${qt}:${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 vl(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 ch(t,e=process.env){return vl(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Ho(t,e),e)}function lh(t,e=process.env){return vl(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Wo(t,e),e)}function uh(t,e=process.env){return vl(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${qt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>qo(t,e),e)}var cs=E(()=>{"use strict";M()});import{existsSync as vh,readFileSync as $h,writeFileSync as xh}from"node:fs";import{join as Sh}from"node:path";import{isMap as kh,parseDocument as Eh}from"yaml";async function Rh(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||!rr(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let o=Sh(t,"project.yaml");if(!vh(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=Eh($h(o,"utf-8"));return ls(i,r).set("default_branch",n),xh(o,i.toString()),{repoName:r,defaultBranch:n}}function Th(t,e,r){let n=Sh(t,"project.yaml");if(!vh(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=Eh($h(n,"utf-8"));ls(o,e).set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}),xh(n,o.toString())}function ls(t,e){let r=t.get("repos"),o=(r&&typeof r=="object"&&"items"in r?r.items:[]).find(i=>kh(i)&&String(i.get("name")??i.get("repo")??"")===e);if(!kh(o))throw new Error(`repo "${e}" not found in project.yaml repos[]`);return o}var us=E(()=>{"use strict";M()});import{existsSync as Rl,readFileSync as Tl}from"node:fs";import{join as Il}from"node:path";import{simpleGit as jh}from"simple-git";import{parse as Cl}from"yaml";function Oh(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(wR.source,"g")}function Lh(t){let e=Il(t,"project.yaml");if(Rl(e))try{let o=Cl(Tl(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=Il(t,"tracker","config.yaml");if(Rl(r))try{let o=Cl(Tl(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function Mh(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 bR(t,e,r){let o=await jh(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
791
- `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),f=l.slice(2),m=Pl.exec(u)??Nh.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:m?Number(m[1]):null,isMerge:f.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:Mh(c[3]),churn:l+u})}return i}async function kR(t,e){let n=await jh(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
792
- `)){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:Mh(s[3]),churn:a+c})}return o}function vR(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(Pl,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Pl,"").replace(Nh,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let f=new Map;for(let b of c.files){let w=o.get(b.path)??b.path;s(w)||f.set(w,(f.get(w)??0)+b.churn)}if(f.size===0)continue;let y=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(y.title=p),c.timeSec>0&&(y.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),y.commits.push(c.sha);for(let[b,w]of f){let k=be("code",e,b),x=y.files.find(h=>h.key===k);if(x)x.churn=(x.churn??0)+w;else{let h=i.get(k);y.files.push({key:k,...h?{entityId:h}:{},churn:w})}}if(d.length>0){let b=new Set([...y.links?.tasks??[],...d]);b.delete(u),y.links={...y.links??{},tasks:[...b].sort()}}a.set(u,y)}return a}function _h(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 Dh(t){let e=await bR(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 kR(t.repoDir,r.sha))}return vR({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function Uh(t,e){let r=new Map;for(let i of e)for(let[s,a]of i){let c=r.get(s);r.set(s,c?_h(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=_h(fs(t,i),s);if(!a){o++;continue}n.push({path:_r(i),content:hn(a)})}return{files:n,skippedPipeline:o}}function fs(t,e){let r=Il(t,_r(e));if(!Rl(r))return null;try{let n=Kt(Cl(Tl(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var wR,Pl,Nh,Al=E(()=>{"use strict";M();wR=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Pl=/\(#(\d+)\)\s*$/,Nh=/^Merge pull request #(\d+)\b/});import{simpleGit as $R}from"simple-git";async function Fh(t,e,r){let o=await $R(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
793
- `))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 ms(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=re(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=re(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function Gh(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let k=new Set;for(let R of w.files){let v=o.get(R)??R;!i.has(v)||s(v)||k.add(v)}if(k.size<2||k.size>a.commitFileCap)continue;let x=Math.max(0,r-w.timeSec),h=Math.pow(.5,x/c),T=[...k].sort();for(let R of T)l.set(R,(l.get(R)??0)+h);for(let R=0;R<T.length;R++)for(let v=R+1;v<T.length;v++){let _=`${T[R]}\0${T[v]}`;u.set(_,(u.get(_)??0)+h),p.set(_,(p.get(_)??0)+1)}}let d=[],f=a.jaccardMinPct/100;for(let[w,k]of u){if((p.get(w)??0)<a.supportMin)continue;let[x,h]=w.split("\0"),T=(l.get(x)??0)+(l.get(h)??0)-k,R=T>0?k/T:0;R<f||d.push({a:x,b:h,weight:Math.round(R*Bh)/Bh})}let m=new Map;for(let w of d)for(let k of[w.a,w.b])m.has(k)||m.set(k,[]),m.get(k).push(w);let y=new Map;for(let[,w]of m)w.sort((k,x)=>x.weight-k.weight||(k.a<x.a?-1:k.a>x.a?1:k.b<x.b?-1:1)).slice(0,a.topK).forEach(k=>y.set(k,(y.get(k)??0)+1));return[...y.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:be("code",e,w.a),to:be("code",e,w.b),weight:w.weight})).sort((w,k)=>w.from<k.from?-1:w.from>k.from?1:w.to<k.to?-1:1)}var Wn,Bh,hs=E(()=>{"use strict";M();Wn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];Bh=1e4});import{createHash as xR}from"node:crypto";function ER(t,e,r,n){for(let o=0;;o++){let s=`e_${xR("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function Kh(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,f=[],m=new Map,y=(v,_)=>{d.add(_),m.set(_,v.entityId),f.push(v)},b=[];for(let v of u)l.has(v.currentKey)&&!d.has(v.currentKey)?y({...v,status:"active",lastSeen:r},v.currentKey):b.push(v);let w=[],k=[];for(let v of b){let _=re(v.currentKey),N=_?i.get(_.path):void 0;if(_&&N){let G=be(_.level,e,N.finalPath);if(l.has(G)&&!d.has(G)){w.push({entity:v,newKey:G,untilCommit:N.commit}),d.add(G);continue}}k.push(v)}let x=[];if(s){let v=new Map;for(let N of c){if(d.has(N))continue;let G=re(N);if(G?.level!=="code")continue;let W=a.get(G.path);W&&v.set(W,v.has(W)?null:N)}let _=new Map;for(let N of k){let G=re(N.currentKey);if(G?.level!=="code")continue;let W=s.get(G.path);W&&_.set(W,_.has(W)?null:N)}for(let N of k){let G=re(N.currentKey),W=G?.level==="code"?s.get(G.path):void 0,C=W?v.get(W):void 0;W&&C&&_.get(W)===N&&!d.has(C)?(w.push({entity:N,newKey:C,untilCommit:r}),d.add(C)):x.push(N)}}else x.push(...k);let h=new Map;for(let v of w){let _=re(v.entity.currentKey),N=re(v.newKey);if(_?.level!=="code"||!N)continue;let G=_.path,W=N.path;for(let C=G.lastIndexOf("/");C>0;C=G.lastIndexOf("/",C-1)){let g=G.slice(0,C),B=G.slice(C+1);if(!W.endsWith(`/${B}`))continue;let L=W.slice(0,W.length-B.length-1);if(L===g)continue;let q=`${g}\0${L}`,te=h.get(q);h.set(q,{count:(te?.count??0)+1,commit:te&&te.commit>v.untilCommit?te.commit:v.untilCommit})}}let T=[...h.entries()].filter(([,v])=>v.count>=SR).map(([v,_])=>{let[N,G]=v.split("\0");return{from:N,to:G,commit:_.commit}}).sort((v,_)=>_.from.length-v.from.length||(v.from<_.from?-1:1)),R=[];for(let v of x){let _=re(v.currentKey),N=!1;if(_?.level==="component")for(let G of T){let W=null;if(_.path===G.from?W=G.to:_.path.startsWith(`${G.from}/`)&&(W=G.to+_.path.slice(G.from.length)),W===null)continue;let C=be("component",e,W);l.has(C)&&!d.has(C)&&(w.push({entity:v,newKey:C,untilCommit:G.commit}),d.add(C),N=!0);break}N||R.push(v)}for(let v of w.sort((_,N)=>_.newKey<N.newKey?-1:1))y({...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 R)f.push({...v,status:"orphaned"});for(let v of c){if(d.has(v))continue;let _=ER(e,v,r,p);p.add(_),y({entityId:_,currentKey:v,firstSeen:n,lastSeen:r,status:"active"},v)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:f},byKey:m}}var SR,Hh=E(()=>{"use strict";M();SR=5});import{simpleGit as RR}from"simple-git";async function Wh(t,e,r){let n=RR(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
794
- `).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 qh(t){let e=new Map,r=new Map;for(let n of t){let o=r.get(n.fromPath)??n.fromPath;r.delete(n.fromPath),r.set(n.toPath,o),e.set(o,{finalPath:n.toPath,commit:n.commit})}for(let[n,o]of e)o.finalPath===n&&e.delete(n);return e}var Yh=E(()=>{"use strict"});function gs(t){return be("container",t,TR)}function Vh(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function zh(t,e,r,n){let o=[],i=u=>{let p=be("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:Vh(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,IR)}},s=(u,p)=>{let d=be("component",t,u),f=n.get(d);return{key:d,level:"component",label:Vh(u),...f?{entityId:f}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let f=r.filesByDir.get(d)??[],m=r.childDirs.get(d)??[],y=[p,...f.map(i)],b=[...f.map(w=>({kind:"contains",from:p.key,to:be("code",t,w.path)})),...m.map(w=>({kind:"contains",from:p.key,to:be("component",t,w)}))];c(u,y,b)},c=(u,p,d)=>{let f={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},m=Gt(f);if(!m.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${m.errors.join("; ")}`);o.push({path:Ma(t,u),content:Ka(f)})},l={key:gs(t),level:"container",label:t,...n.get(gs(t))?{entityId:n.get(gs(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 Xh(t,e){let r=[gs(t)];for(let n of e.components)r.push(be("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(be("code",t,o.path));return r.sort()}var TR,IR,Jh=E(()=>{"use strict";M();TR=".";IR=12});import{simpleGit as Qh}from"simple-git";function Wr(t){let e=new Set,r=[],n=new Set;for(let o of t){let i=o.trim();if(i)if(i.endsWith("/"))e.add(i.slice(0,-1));else if(i.includes("*")){let s=i.replace(/[.*+?^${}()|[\]\\]/g,a=>a==="*"?"\0":`\\${a}`).replace(/\0/g,".*");r.push(new RegExp(`^${s}$`))}else n.add(i)}return o=>{let i=o.split("/"),s=i[i.length-1]??o;if(n.has(o))return!0;for(let a of i)if(e.has(a)||n.has(a))return!0;return r.some(a=>a.test(s))}}async function tg(t,e="HEAD"){let r=Qh(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 Yo(t,n)}}async function Yo(t,e){let n=await Qh(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 Zh(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function rg(t,e){let r=[...t].sort((m,y)=>m.path<y.path?-1:m.path>y.path?1:0),n=new Map,o=new Map;for(let m of r){let y=Zh(m.path);n.has(y)||n.set(y,[]),n.get(y).push(m);let b=y;for(;b!=="";){let w=Zh(b);o.has(w)||o.set(w,new Set),o.get(w).add(b),b=w}}let i=m=>[...o.get(m)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let m=l.shift(),y=(n.get(m)??[]).length+i(m).length;if(y<=s)s-=y,c.add(m),l.push(...i(m));else{if(m==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(m)}}let u=[],p=new Map,d=new Map,f=0;for(let m of[...c].sort()){let y=n.get(m)??[];p.set(m,y),d.set(m,i(m)),f+=y.length,m!==""&&u.push(m)}for(let m of a)u.push(m);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:f}}}var eg,Vo=E(()=>{"use strict";eg=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as ng,readFileSync as og}from"node:fs";import{join as ig}from"node:path";import{simpleGit as CR}from"simple-git";import{parse as sg}from"yaml";function qr(t){let e={ignore:eg,containerNodeCap:PR,cochange:{...lt},issueKeyPattern:null,enabled:!0},r=ig(t,"regimen.yaml");if(!ng(r))return e;let n;try{n=sg(og(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(f=>typeof f=="string"&&f.trim().length>0):e.ignore,c=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>0?f:m,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled!==!1}}function _l(t,e){let r=ig(t,$o(e));if(!ng(r))return null;let n=sg(og(r,"utf-8")),o=So(n);if(!o.ok)throw new Error(`model: ${$o(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function jl(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await tg(r,t.ref??"HEAD"),s=Wr(o.ignore),a=i.files.filter(k=>!s(k.path)),c=rg(a,o.containerNodeCap),l=_l(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await CR(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=qh(await Wh(r,l.builtFromCommit,i.commit)),p=new Map((await Yo(r,l.builtFromCommit)).map(h=>[h.path,h.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(k=>[k.path,k.blobHash])));let d=new Map(a.map(k=>[k.path,k.blobHash])),f=Kh({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:Xh(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),m=zh(e,i.commit,c,f.byKey),y=Wr([...o.ignore,...Wn]),b=Gh({repo:e,headTimeSec:i.commitTimeSec,filesets:await Fh(r,i.commit,o.cochange.windowCommits),pathToCurrent:ms(f.table),currentPaths:new Set(a.map(k=>k.path)),ignored:y,settings:o.cochange}),w=[{path:$o(e),content:Ha(f.table)},...m.files.map(k=>({path:k.path,content:k.content})),{path:Oa(e),content:jr({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:b})}];return{repo:e,headCommit:i.commit,files:w,emittedShardPaths:new Set(m.files.map(k=>k.path)),counts:{...m.counts,correlates:b.length},identityTable:f.table,entityByKey:f.byKey}}var PR,Nl=E(()=>{"use strict";M();hs();Hh();Yh();Jh();Vo();PR=1500});import{existsSync as cg,readFileSync as lg,readdirSync as AR}from"node:fs";import{join as Ol}from"node:path";import{parse as ug}from"yaml";function _R(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 dg(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<Ua)return null;let s=i/Math.min(n.size,o.size),a=_R(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*ag)/ag;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[Re(t.taskKey),Re(e.taskKey)]:[Re(e.taskKey),Re(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function pg(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=dg(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 fg(t,e,r,n){let o=Re(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=dg(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 ys(t){let e=Ol(t,"model/facts/events");if(!cg(e))return[];let r=[];for(let n of AR(e).sort())if(n.endsWith(".yaml"))try{let o=Kt(ug(lg(Ol(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function mg(t){let e=Ol(t,Ar);if(!cg(e))return[];try{let r=xo(ug(lg(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function ws(t){return jr({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var ag,Ll=E(()=>{"use strict";M();ag=1e4});var zo={};Ne(zo,{collectSearchRows:()=>gg,readContextIndexHub:()=>jR,rebuildSearchIndex:()=>yg,searchIndexPath:()=>$s,searchModelIndex:()=>NR,toFtsQuery:()=>wg});import{existsSync as Yn,readFileSync as qn,readdirSync as ks}from"node:fs";import{join as It}from"node:path";import{parse as vs}from"yaml";function $s(t){return It(t,".git","codepipe-model-index.sqlite")}function jR(t){let e=It(t,"regimen.yaml");if(!Yn(e))return"off";try{let n=vs(qn(e,"utf-8"))?.context,o=n&&typeof n=="object"?n.index:null;return(o&&typeof o=="object"?o.hub:null)==="metadata"?"metadata":"off"}catch{return"off"}}async function hg(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function bs(t){return t.length>Ti?t.slice(0,Ti):t}function Ml(t){if(!Yn(t))return[];let e=[];for(let r of ks(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=It(t,r.name);r.isDirectory()?e.push(...Ml(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function gg(t){let e=[];for(let i of Ml(It(t,"model/derived/structure"))){let s;try{s=vs(qn(i,"utf-8"))}catch{continue}let a=Gt(s);if(a.ok)for(let c of a.value.nodes){let l=re(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:bs(`${l.path} ${c.label??""}`.trim())})}}let r=It(t,"model/facts/events");if(Yn(r)){for(let i of ks(r).sort())if(i.endsWith(".yaml"))try{let s=Kt(vs(qn(It(r,i),"utf-8")));if(!s.ok)continue;let a=s.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:bs(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=It(t,"model/facts/annotations");if(Yn(n)){let i=new Map;for(let s of Ml(It(t,"model/facts/identity")))try{let a=vs(qn(s,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&i.set(c.entityId,c.currentKey)}catch{}for(let s of ks(n).sort())if(s.endsWith(".md"))try{let a=qn(It(n,s),"utf-8"),c=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(a);if(!c)continue;e.push({nodeId:i.get(c[1])??c[1],kind:"annotation",text:bs(c[2].trim())})}catch{}}let o=It(t,"adr");if(Yn(o))for(let i of ks(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=qn(It(o,i),"utf-8").split(`
795
- `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:bs(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function yg(t){let e=gg(t),r=await hg();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync($s(t));try{n.exec("DROP TABLE IF EXISTS model_fts"),n.exec("CREATE VIRTUAL TABLE model_fts USING fts5(node_id UNINDEXED, kind UNINDEXED, text)");let o=n.prepare("INSERT INTO model_fts (node_id, kind, text) VALUES (?, ?, ?)");for(let i of e)o.run(i.nodeId,i.kind,i.text)}finally{n.close()}return{rows:e,indexed:!0}}function wg(t){let e=t.match(/[\p{L}\p{N}_./-]+/gu)??[];return e.length===0?null:e.map((r,n)=>`"${r.replace(/"/g,"")}"${n===e.length-1?"*":""}`).join(" ")}async function NR(t,e,r){let n=await hg();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");Yn($s(t))||await yg(t);let o=wg(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),Fa),s=new n.DatabaseSync($s(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
802
+ `).map(b=>b.trim().toUpperCase()).filter(b=>b.length>0).some(b=>l.has(b))?p++:u.push(f);if(p===0)return{commit:(await t.revparse([i])).trim(),dropped:0};await t.checkout(["-B",n,a]);for(let f of u)try{await t.raw([...Tl,"cherry-pick","--allow-empty","--keep-redundant-commits",f])}catch(m){await t.raw(["cherry-pick","--abort"]).catch(()=>{}),await t.checkout(["-B",n,i]).catch(()=>{});let y=m instanceof Error?m.message:String(m);throw new Error(`rewrite_cluster_branch: replaying ${f.slice(0,10)} after dropping ${o.join(", ")} hit conflicts
803
+ ${y.trim()}`)}let d=(await t.revparse(["HEAD"])).trim();return await t.push(["--force-with-lease","-u","origin",n]),{commit:d,dropped:p}}async function $h(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 Il(t){return t.mirror?wh(t.mirror.host,t.mirror.owner,t.mirror.repoName):wh(t.host,t.owner,t.repoName)}function wh(t,e,r){return t==="github"?`git@github.com:${e}/${r}.git`:t==="gitlab"?`git@gitlab.com:${e}/${r}.git`:`git@bitbucket.org:${e}/${r}.git`}function qn(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 ws(t){return(await Rl().listRemote(["--heads",t])).split(`
804
+ `).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 xh(t,e){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-zA-Z0-9])${r}($|[^0-9])`,"i").test(t)}var Tl,Yn=E(()=>{"use strict";ys();Tl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"]});import{createCipheriv as wR,createDecipheriv as bR,createHash as kR,createPrivateKey as vR,createPublicKey as Cl,diffieHellman as Sh,generateKeyPairSync as Eh,hkdfSync as Rh,randomBytes as $R}from"node:crypto";function bs(){let{publicKey:t,privateKey:e}=Eh("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Qe(t){let e=Buffer.from(t,"base64");return(kR("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function tr(t,e){let r=Cl({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Eh("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Sh({privateKey:o,publicKey:r}),c=Buffer.from(Rh("sha256",a,Buffer.concat([i,s]),Th,32)),l=$R(12),u=wR("aes-256-gcm",c,l),p=typeof e=="string"?Buffer.from(e,"utf-8"):e,d=Buffer.concat([u.update(p),u.final()]),f=u.getAuthTag(),m={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:f.toString("base64"),ct:d.toString("base64")};return Buffer.from(JSON.stringify(m),"utf-8").toString("base64")}function Vn(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=vR({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Cl({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Cl(n).export({type:"spki",format:"der"}),a=Sh({privateKey:n,publicKey:o}),c=Buffer.from(Rh("sha256",a,Buffer.concat([i,s]),Th,32)),l=bR("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 Th,kt=E(()=>{"use strict";Th=Buffer.from("devpipe-sealedbox-v1","utf-8")});function Jo(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 Zo(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 Qo(t,e=process.env){if(!t)return!1;let r=`https://${Xt}:${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 Pl(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 Ch(t,e=process.env){return Pl(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Jo(t,e),e)}function Ph(t,e=process.env){return Pl(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Zo(t,e),e)}function Ah(t,e=process.env){return Pl(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Xt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Qo(t,e),e)}var ks=E(()=>{"use strict";M()});import{existsSync as NR,readFileSync as OR}from"node:fs";import{join as LR}from"node:path";import{isMap as Hh,parseDocument as MR}from"yaml";async function Wh(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||!or(n))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);return await Oe(t,async()=>{let o=Yh(t,r,i=>i.set("default_branch",n));await qe(t,[{path:"project.yaml",content:o}],`chore(config): set ${r} default branch to ${n}`)}),{repoName:r,defaultBranch:n}}async function qh(t,e,r){await Oe(t,async()=>{let n=Yh(t,e,o=>o.set("mirror",{host:r.host,owner:r.owner,repo:r.repoName}));await qe(t,[{path:"project.yaml",content:n}],`chore(config): set ${e} mirror`)})}function Yh(t,e,r){let n=LR(t,"project.yaml");if(!NR(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=MR(OR(n,"utf-8"));return r(Al(o,e)),o.toString()}function Al(t,e){let r=t.get("repos"),o=(r&&typeof r=="object"&&"items"in r?r.items:[]).find(i=>Hh(i)&&String(i.get("name")??i.get("repo")??"")===e);if(!Hh(o))throw new Error(`repo "${e}" not found in project.yaml repos[]`);return o}var vs=E(()=>{"use strict";M();Le()});import{existsSync as Ml,readFileSync as Dl}from"node:fs";import{join as Ul}from"node:path";import{simpleGit as Qh}from"simple-git";import{parse as Bl}from"yaml";function tg(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(HR.source,"g")}function rg(t){let e=Ul(t,"project.yaml");if(Ml(e))try{let o=Bl(Dl(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=Ul(t,"tracker","config.yaml");if(Ml(r))try{let o=Bl(Dl(r,"utf-8"))?.prefix;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return null}function ng(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 WR(t,e,r){let o=await Qh(t).raw(["log","--numstat","--format=@@@ %H %ct %P %x09%s","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
805
+ `))if(a.startsWith("@@@ ")){let c=a.indexOf(" "),l=(c>=0?a.slice(4,c):a.slice(4)).trim().split(/\s+/),u=c>=0?a.slice(c+1):"",p=l[0]??"",d=Number(l[1]??0),f=l.slice(2),m=Fl.exec(u)??eg.exec(u);s={sha:p,timeSec:d,subject:u,files:[],prNumber:m?Number(m[1]):null,isMerge:f.length>1},i.push(s)}else if(a.trim()&&s){let c=/^(\d+|-)\t(\d+|-)\t(.+)$/.exec(a);if(!c)continue;let l=c[1]==="-"?0:Number(c[1]),u=c[2]==="-"?0:Number(c[2]);s.files.push({path:ng(c[3]),churn:l+u})}return i}async function qR(t,e){let n=await Qh(t).raw(["diff","--numstat",`${e}^1`,e]).catch(()=>""),o=[];for(let i of n.split(`
806
+ `)){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:ng(s[3]),churn:a+c})}return o}function YR(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(Fl,"").trim();else if(c.prNumber!==null){if((t.trackerProjectKey??"").toUpperCase()==="PR")continue;u=`PR-${c.prNumber}`,p=c.subject.replace(Fl,"").replace(eg,"").replace(/^from\s+/,"").trim()||c.subject}else continue;if(!/^[A-Za-z0-9._-]+$/.test(u))continue;let f=new Map;for(let b of c.files){let w=o.get(b.path)??b.path;s(w)||f.set(w,(f.get(w)??0)+b.churn)}if(f.size===0)continue;let y=a.get(u)??{modelFormatVersion:2,taskKey:u,origin:"bootstrap",title:"",commits:[],files:[]};p&&(y.title=p),c.timeSec>0&&(y.date=new Date(c.timeSec*1e3).toISOString().slice(0,10)),y.commits.push(c.sha);for(let[b,w]of f){let k=be("code",e,b),x=y.files.find(h=>h.key===k);if(x)x.churn=(x.churn??0)+w;else{let h=i.get(k);y.files.push({key:k,...h?{entityId:h}:{},churn:w})}}if(d.length>0){let b=new Set([...y.links?.tasks??[],...d]);b.delete(u),y.links={...y.links??{},tasks:[...b].sort()}}a.set(u,y)}return a}function Zh(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 og(t){let e=await WR(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 qR(t.repoDir,r.sha))}return YR({repo:t.repo,issueKeyRe:t.issueKeyRe,commits:e,pathToCurrent:t.pathToCurrent,entityByKey:t.entityByKey,ignored:t.ignored,trackerProjectKey:t.trackerProjectKey??null})}function ig(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?Zh(c,a)??c:a)}let n=[],o=0;for(let[i,s]of[...r.entries()].sort(([a],[c])=>a<c?-1:1)){let a=Zh(xs(t,i),s);if(!a){o++;continue}n.push({path:Dr(i),content:xn(a)})}return{files:n,skippedPipeline:o}}function xs(t,e){let r=Ul(t,Dr(e));if(!Ml(r))return null;try{let n=Yt(Bl(Dl(r,"utf-8")));return n.ok?n.value:null}catch{return null}}var HR,Fl,eg,Gl=E(()=>{"use strict";M();HR=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g,Fl=/\(#(\d+)\)\s*$/,eg=/^Merge pull request #(\d+)\b/});import{simpleGit as VR}from"simple-git";async function ag(t,e,r){let o=await VR(t).raw(["log","--no-merges","--name-only","--format=@@@ %H %ct","-n",String(r),e]),i=[],s=null;for(let a of o.split(`
807
+ `))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 Ss(t){let e=new Map;for(let r of t.entities){if(r.status!=="active"||!r.aliases)continue;let n=re(r.currentKey);if(n?.level==="code")for(let o of r.aliases){let i=re(o.key);i?.level==="code"&&e.set(i.path,n.path)}}return e}function cg(t){let{repo:e,headTimeSec:r,filesets:n,pathToCurrent:o,currentPaths:i,ignored:s,settings:a}=t,c=a.halfLifeDays*86400,l=new Map,u=new Map,p=new Map;for(let w of n){let k=new Set;for(let R of w.files){let v=o.get(R)??R;!i.has(v)||s(v)||k.add(v)}if(k.size<2||k.size>a.commitFileCap)continue;let x=Math.max(0,r-w.timeSec),h=Math.pow(.5,x/c),T=[...k].sort();for(let R of T)l.set(R,(l.get(R)??0)+h);for(let R=0;R<T.length;R++)for(let v=R+1;v<T.length;v++){let P=`${T[R]}\0${T[v]}`;u.set(P,(u.get(P)??0)+h),p.set(P,(p.get(P)??0)+1)}}let d=[],f=a.jaccardMinPct/100;for(let[w,k]of u){if((p.get(w)??0)<a.supportMin)continue;let[x,h]=w.split("\0"),T=(l.get(x)??0)+(l.get(h)??0)-k,R=T>0?k/T:0;R<f||d.push({a:x,b:h,weight:Math.round(R*sg)/sg})}let m=new Map;for(let w of d)for(let k of[w.a,w.b])m.has(k)||m.set(k,[]),m.get(k).push(w);let y=new Map;for(let[,w]of m)w.sort((k,x)=>x.weight-k.weight||(k.a<x.a?-1:k.a>x.a?1:k.b<x.b?-1:1)).slice(0,a.topK).forEach(k=>y.set(k,(y.get(k)??0)+1));return[...y.entries()].filter(([,w])=>w===2).map(([w])=>w).map(w=>({kind:"correlates",from:be("code",e,w.a),to:be("code",e,w.b),weight:w.weight})).sort((w,k)=>w.from<k.from?-1:w.from>k.from?1:w.to<k.to?-1:1)}var Xn,sg,Es=E(()=>{"use strict";M();Xn=["package-lock.json","pnpm-lock.yaml","yarn.lock"];sg=1e4});import{createHash as zR}from"node:crypto";function JR(t,e,r,n){for(let o=0;;o++){let s=`e_${zR("sha256").update(`${t}\0${e}\0${r}\0${o}`).digest("hex").slice(0,8)}`;if(!n.has(s))return s}}function lg(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,f=[],m=new Map,y=(v,P)=>{d.add(P),m.set(P,v.entityId),f.push(v)},b=[];for(let v of u)l.has(v.currentKey)&&!d.has(v.currentKey)?y({...v,status:"active",lastSeen:r},v.currentKey):b.push(v);let w=[],k=[];for(let v of b){let P=re(v.currentKey),N=P?i.get(P.path):void 0;if(P&&N){let G=be(P.level,e,N.finalPath);if(l.has(G)&&!d.has(G)){w.push({entity:v,newKey:G,untilCommit:N.commit}),d.add(G);continue}}k.push(v)}let x=[];if(s){let v=new Map;for(let N of c){if(d.has(N))continue;let G=re(N);if(G?.level!=="code")continue;let W=a.get(G.path);W&&v.set(W,v.has(W)?null:N)}let P=new Map;for(let N of k){let G=re(N.currentKey);if(G?.level!=="code")continue;let W=s.get(G.path);W&&P.set(W,P.has(W)?null:N)}for(let N of k){let G=re(N.currentKey),W=G?.level==="code"?s.get(G.path):void 0,C=W?v.get(W):void 0;W&&C&&P.get(W)===N&&!d.has(C)?(w.push({entity:N,newKey:C,untilCommit:r}),d.add(C)):x.push(N)}}else x.push(...k);let h=new Map;for(let v of w){let P=re(v.entity.currentKey),N=re(v.newKey);if(P?.level!=="code"||!N)continue;let G=P.path,W=N.path;for(let C=G.lastIndexOf("/");C>0;C=G.lastIndexOf("/",C-1)){let g=G.slice(0,C),B=G.slice(C+1);if(!W.endsWith(`/${B}`))continue;let L=W.slice(0,W.length-B.length-1);if(L===g)continue;let q=`${g}\0${L}`,te=h.get(q);h.set(q,{count:(te?.count??0)+1,commit:te&&te.commit>v.untilCommit?te.commit:v.untilCommit})}}let T=[...h.entries()].filter(([,v])=>v.count>=XR).map(([v,P])=>{let[N,G]=v.split("\0");return{from:N,to:G,commit:P.commit}}).sort((v,P)=>P.from.length-v.from.length||(v.from<P.from?-1:1)),R=[];for(let v of x){let P=re(v.currentKey),N=!1;if(P?.level==="component")for(let G of T){let W=null;if(P.path===G.from?W=G.to:P.path.startsWith(`${G.from}/`)&&(W=G.to+P.path.slice(G.from.length)),W===null)continue;let C=be("component",e,W);l.has(C)&&!d.has(C)&&(w.push({entity:v,newKey:C,untilCommit:G.commit}),d.add(C),N=!0);break}N||R.push(v)}for(let v of w.sort((P,N)=>P.newKey<N.newKey?-1:1))y({...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 R)f.push({...v,status:"orphaned"});for(let v of c){if(d.has(v))continue;let P=JR(e,v,r,p);p.add(P),y({entityId:P,currentKey:v,firstSeen:n,lastSeen:r,status:"active"},v)}return{table:{modelFormatVersion:2,repo:e,builtFromCommit:r,entities:f},byKey:m}}var XR,ug=E(()=>{"use strict";M();XR=5});import{simpleGit as ZR}from"simple-git";async function dg(t,e,r){let n=ZR(t),o=(await n.raw(["rev-list","--reverse","--no-merges",`${e}..${r}`])).split(`
808
+ `).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 pg(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 fg=E(()=>{"use strict"});function Rs(t){return be("container",t,QR)}function mg(t){let e=t.lastIndexOf("/");return e<0?t:t.slice(e+1)}function hg(t,e,r,n){let o=[],i=u=>{let p=be("code",t,u.path),d=n.get(p);return{key:p,level:"code",label:mg(u.path),...d?{entityId:d}:{},contentHash:u.blobHash.slice(0,eT)}},s=(u,p)=>{let d=be("component",t,u),f=n.get(d);return{key:d,level:"component",label:mg(u),...f?{entityId:f}:{},...p?{aggregate:!0}:{}}},a=(u,p,d)=>{let f=r.filesByDir.get(d)??[],m=r.childDirs.get(d)??[],y=[p,...f.map(i)],b=[...f.map(w=>({kind:"contains",from:p.key,to:be("code",t,w.path)})),...m.map(w=>({kind:"contains",from:p.key,to:be("component",t,w)}))];c(u,y,b)},c=(u,p,d)=>{let f={modelFormatVersion:2,repo:t,builtFromCommit:e,nodes:p,edges:d},m=qt(f);if(!m.ok)throw new Error(`model build produced an invalid shard (${u||"root"}): ${m.errors.join("; ")}`);o.push({path:Wa(t,u),content:Ja(f)})},l={key:Rs(t),level:"container",label:t,...n.get(Rs(t))?{entityId:n.get(Rs(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 gg(t,e){let r=[Rs(t)];for(let n of e.components)r.push(be("component",t,n));for(let[,n]of e.filesByDir)for(let o of n)r.push(be("code",t,o.path));return r.sort()}var QR,eT,yg=E(()=>{"use strict";M();QR=".";eT=12});import{simpleGit as bg}from"simple-git";function Qr(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 vg(t,e="HEAD"){let r=bg(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 ei(t,n)}}async function ei(t,e){let n=await bg(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 wg(t){let e=t.lastIndexOf("/");return e<0?"":t.slice(0,e)}function $g(t,e){let r=[...t].sort((m,y)=>m.path<y.path?-1:m.path>y.path?1:0),n=new Map,o=new Map;for(let m of r){let y=wg(m.path);n.has(y)||n.set(y,[]),n.get(y).push(m);let b=y;for(;b!=="";){let w=wg(b);o.has(w)||o.set(w,new Set),o.get(w).add(b),b=w}}let i=m=>[...o.get(m)??[]].sort(),s=Math.max(e,1)-1,a=new Set,c=new Set,l=[""];for(;l.length>0;){let m=l.shift(),y=(n.get(m)??[]).length+i(m).length;if(y<=s)s-=y,c.add(m),l.push(...i(m));else{if(m==="")return{components:[],collapsed:new Set,filesByDir:new Map,childDirs:new Map,counts:{component:0,code:0}};a.add(m)}}let u=[],p=new Map,d=new Map,f=0;for(let m of[...c].sort()){let y=n.get(m)??[];p.set(m,y),d.set(m,i(m)),f+=y.length,m!==""&&u.push(m)}for(let m of a)u.push(m);return u.sort(),{components:u,collapsed:a,filesByDir:p,childDirs:d,counts:{component:u.length,code:f}}}var kg,ti=E(()=>{"use strict";kg=["dist/","build/","coverage/","*.lock","*.generated.*","__snapshots__/","vendor/","node_modules/"]});import{existsSync as xg,readFileSync as Sg}from"node:fs";import{join as Eg}from"node:path";import{simpleGit as tT}from"simple-git";import{parse as Rg}from"yaml";function en(t){let e={ignore:kg,containerNodeCap:rT,cochange:{...mt},issueKeyPattern:null,enabled:!0},r=Eg(t,"project.yaml");if(!xg(r))return e;let n;try{n=Rg(Sg(r,"utf-8"))}catch{return e}let o=n?.context,i=o&&typeof o=="object"?o.model:void 0;if(!i||typeof i!="object")return e;let s=i,a=Array.isArray(s.ignore)?s.ignore.filter(f=>typeof f=="string"&&f.trim().length>0):e.ignore,c=(f,m)=>typeof f=="number"&&Number.isInteger(f)&&f>0?f:m,l=c(s.container_node_cap,e.containerNodeCap),u=s.cochange&&typeof s.cochange=="object"?s.cochange:{},p={windowCommits:c(u.window_commits,e.cochange.windowCommits),commitFileCap:c(u.commit_file_cap,e.cochange.commitFileCap),supportMin:c(u.support_min,e.cochange.supportMin),jaccardMinPct:typeof u.jaccard_min_pct=="number"&&Number.isInteger(u.jaccard_min_pct)&&u.jaccard_min_pct>=0&&u.jaccard_min_pct<=100?u.jaccard_min_pct:e.cochange.jaccardMinPct,halfLifeDays:c(u.half_life_days,e.cochange.halfLifeDays),topK:c(u.top_k,e.cochange.topK)},d=typeof s.issue_key_pattern=="string"&&s.issue_key_pattern.trim().length>0?s.issue_key_pattern.trim():null;return{ignore:a,containerNodeCap:l,cochange:p,issueKeyPattern:d,enabled:s.enabled!==!1}}function Kl(t,e){let r=Eg(t,Io(e));if(!xg(r))return null;let n=Rg(Sg(r,"utf-8")),o=Po(n);if(!o.ok)throw new Error(`model: ${Io(e)} is malformed (${o.errors[0]}) \u2014 refusing to rebuild identity from scratch; fix or remove the file explicitly`);return o.value}async function Hl(t){let{repo:e,repoDir:r,contextDir:n,settings:o}=t,i=await vg(r,t.ref??"HEAD"),s=Qr(o.ignore),a=i.files.filter(k=>!s(k.path)),c=$g(a,o.containerNodeCap),l=Kl(n,e),u=new Map,p=null;l?.builtFromCommit&&l.builtFromCommit!==i.commit?await tT(r).raw(["cat-file","-e",`${l.builtFromCommit}^{commit}`]).then(()=>!0).catch(()=>!1)&&(u=pg(await dg(r,l.builtFromCommit,i.commit)),p=new Map((await ei(r,l.builtFromCommit)).map(h=>[h.path,h.blobHash]))):l?.builtFromCommit===i.commit&&(p=new Map(a.map(k=>[k.path,k.blobHash])));let d=new Map(a.map(k=>[k.path,k.blobHash])),f=lg({repo:e,headCommit:i.commit,headDate:i.commitDate,prev:l,currentKeys:gg(e,c),renameChains:u,prevBlobByPath:p,headBlobByPath:d}),m=hg(e,i.commit,c,f.byKey),y=Qr([...o.ignore,...Xn]),b=cg({repo:e,headTimeSec:i.commitTimeSec,filesets:await ag(r,i.commit,o.cochange.windowCommits),pathToCurrent:Ss(f.table),currentPaths:new Set(a.map(k=>k.path)),ignored:y,settings:o.cochange}),w=[{path:Io(e),content:Za(f.table)},...m.files.map(k=>({path:k.path,content:k.content})),{path:Ka(e),content:Ur({modelFormatVersion:2,repo:e,builtFromCommit:i.commit,edges:b})}];return{repo:e,headCommit:i.commit,files:w,emittedShardPaths:new Set(m.files.map(k=>k.path)),counts:{...m.counts,correlates:b.length},identityTable:f.table,entityByKey:f.byKey}}var rT,Wl=E(()=>{"use strict";M();Es();ug();fg();yg();ti();rT=1500});import{existsSync as Ig,readFileSync as Cg,readdirSync as nT}from"node:fs";import{join as ql}from"node:path";import{parse as Pg}from"yaml";function oT(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 Ag(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<Ya)return null;let s=i/Math.min(n.size,o.size),a=oT(t.date,e.date),c=a===null?1:Math.pow(.5,a/r),l=Math.round(s*c*Tg)/Tg;if(l<=0)return null;let[u,p]=t.taskKey<e.taskKey?[Re(t.taskKey),Re(e.taskKey)]:[Re(e.taskKey),Re(t.taskKey)];return{kind:"relates",from:u,to:p,weight:l}}function _g(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=Ag(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 jg(t,e,r,n){let o=Re(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=Ag(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 Ts(t){let e=ql(t,"model/facts/events");if(!Ig(e))return[];let r=[];for(let n of nT(e).sort())if(n.endsWith(".yaml"))try{let o=Yt(Pg(Cg(ql(e,n),"utf-8")));o.ok&&r.push(o.value)}catch{}return r}function Ng(t){let e=ql(t,Mr);if(!Ig(e))return[];try{let r=Co(Pg(Cg(e,"utf-8")));return r.ok?r.value.edges:[]}catch{return[]}}function Is(t){return Ur({modelFormatVersion:2,repo:"",builtFromCommit:"",edges:t})}var Tg,Yl=E(()=>{"use strict";M();Tg=1e4});var ri={};Me(ri,{collectSearchRows:()=>Lg,readContextIndexHub:()=>iT,rebuildSearchIndex:()=>Mg,searchIndexPath:()=>_s,searchModelIndex:()=>sT,toFtsQuery:()=>Dg});import{existsSync as Zn,readFileSync as Jn,readdirSync as Ps}from"node:fs";import{join as jt}from"node:path";import{parse as As}from"yaml";function _s(t){return jt(t,".git","codepipe-model-index.sqlite")}function iT(t){let e=jt(t,"project.yaml");if(!Zn(e))return"off";try{let n=As(Jn(e,"utf-8"))?.context,o=n&&typeof n=="object"?n.index:null;return(o&&typeof o=="object"?o.hub:null)==="metadata"?"metadata":"off"}catch{return"off"}}async function Og(){try{let{createRequire:t}=await import("node:module");return t(import.meta.url)("node:sqlite")}catch{return null}}function Cs(t){return t.length>Ni?t.slice(0,Ni):t}function Vl(t){if(!Zn(t))return[];let e=[];for(let r of Ps(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=jt(t,r.name);r.isDirectory()?e.push(...Vl(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function Lg(t){let e=[];for(let i of Vl(jt(t,"model/derived/structure"))){let s;try{s=As(Jn(i,"utf-8"))}catch{continue}let a=qt(s);if(a.ok)for(let c of a.value.nodes){let l=re(c.key);l&&e.push({nodeId:c.key,kind:l.level,text:Cs(`${l.path} ${c.label??""}`.trim())})}}let r=jt(t,"model/facts/events");if(Zn(r)){for(let i of Ps(r).sort())if(i.endsWith(".yaml"))try{let s=Yt(As(Jn(jt(r,i),"utf-8")));if(!s.ok)continue;let a=s.value,c=[...a.links?.adr??[],...a.links?.tasks??[]].join(" ");e.push({nodeId:`task::${a.taskKey}`,kind:"task",text:Cs(`${a.taskKey} ${a.title??""} ${c}`.trim())})}catch{}}let n=jt(t,"model/facts/annotations");if(Zn(n)){let i=new Map;for(let s of Vl(jt(t,"model/facts/identity")))try{let a=As(Jn(s,"utf-8"));for(let c of a?.entities??[])c.status==="active"&&c.entityId&&c.currentKey&&i.set(c.entityId,c.currentKey)}catch{}for(let s of Ps(n).sort())if(s.endsWith(".md"))try{let a=Jn(jt(n,s),"utf-8"),c=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(a);if(!c)continue;e.push({nodeId:i.get(c[1])??c[1],kind:"annotation",text:Cs(c[2].trim())})}catch{}}let o=jt(t,"adr");if(Zn(o))for(let i of Ps(o).sort()){let s=/^(\d{4})-/.exec(i)?.[1];if(!(!s||!i.endsWith(".md")))try{let a=Jn(jt(o,i),"utf-8").split(`
809
+ `).slice(0,6);e.push({nodeId:`adr::ADR-${s}`,kind:"adr",text:Cs(a.filter(c=>c.trim()).join(" "))})}catch{}}return e}async function Mg(t){let e=Lg(t),r=await Og();if(!r)return{rows:e,indexed:!1};let n=new r.DatabaseSync(_s(t));try{n.exec("DROP TABLE IF EXISTS model_fts"),n.exec("CREATE VIRTUAL TABLE model_fts USING fts5(node_id UNINDEXED, kind UNINDEXED, text)");let o=n.prepare("INSERT INTO model_fts (node_id, kind, text) VALUES (?, ?, ?)");for(let i of e)o.run(i.nodeId,i.kind,i.text)}finally{n.close()}return{rows:e,indexed:!0}}function Dg(t){let e=t.match(/[\p{L}\p{N}_./-]+/gu)??[];return e.length===0?null:e.map((r,n)=>`"${r.replace(/"/g,"")}"${n===e.length-1?"*":""}`).join(" ")}async function sT(t,e,r){let n=await Og();if(!n)throw new Error("model search needs Node with built-in sqlite (>= 22.13) on this CLI");Zn(_s(t))||await Mg(t);let o=Dg(e);if(!o)return[];let i=Math.min(Math.max(r??20,1),za),s=new n.DatabaseSync(_s(t));try{return s.prepare(`SELECT node_id AS nodeId, kind, snippet(model_fts, 2, '[', ']', '\u2026', 10) AS snippet,
796
810
  bm25(model_fts) AS rank
797
- FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,i).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{s.close()}}var Xo=E(()=>{"use strict";M()});var Es={};Ne(Es,{mirrorLag:()=>JR,syncUpstream:()=>XR});import{simpleGit as Ig}from"simple-git";async function XR(t,e,r,n){let o=Ig(e),i=t.defaultBranch??"main",s=n?.upstream??Cg(t);if(!s)return{repo:t.name,upstreamHead:null,updated:!1,error:"repo spec has no host/owner/repo"};try{await o.fetch(s,`+refs/heads/*:${Yr}/*`,["--prune"]);let a=(await o.revparse([`${Yr}/${i}`]).catch(()=>"")).trim()||null;if(!a)return{repo:t.name,upstreamHead:null,updated:!1,error:`upstream has no branch '${i}'`};let c=n?.mirror??(t.mirror?Pg(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await ZR(o),u=await Fl(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let f=(await o.revparse([`${Yr}/${d}`]).catch(()=>"")).trim();!f||u.get(d)===f||p.push(`+${f}:refs/heads/${d}`)}return p.length===0?{repo:t.name,upstreamHead:a,updated:!1}:(await o.push([c,...p]),r.info(`${t.name}: mirror \u2190 ${p.length} branch(es), ${i} @ ${a.slice(0,10)}`),{repo:t.name,upstreamHead:a,updated:!0})}catch(a){let c=a instanceof Error?a.message.split(`
798
- `)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function JR(t,e,r){let n=r?.mirror??(t.mirror?Pg(t.mirror):null);if(!n)return null;let o=r?.upstream??Cg(t);if(!o)return null;let i=Ig(e),s=t.defaultBranch??"main";try{let a=(await Fl(i,n,s)).get(s);if(!a)return null;let c=(await Fl(i,o,s)).get(s);if(!c)return null;if(c===a)return 0;let l=async()=>{let p=await i.raw(["rev-list","--count",`${a}..${c}`]).catch(()=>null);if(p===null)return null;let d=parseInt(p.trim(),10);return Number.isFinite(d)?d:null},u=await l();return u!==null?u:(await i.fetch(o,`+refs/heads/${s}:${Yr}/${s}`),await l())}catch{return null}}function Cg(t){return!t.host||!t.owner||!t.repoName?null:t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}function Pg(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}async function ZR(t){return(await t.raw(["for-each-ref",Yr,"--format=%(refname)"]).catch(()=>"")).split(`
799
- `).map(r=>r.trim()).filter(r=>r.startsWith(`${Yr}/`)).map(r=>r.slice(Yr.length+1))}async function Fl(t,e,r){let n=r?["--heads",e,r]:["--heads",e],o=await t.listRemote(n),i=new Map;for(let s of o.split(`
800
- `)){let[a,c]=s.trim().split(/\s+/);!a||!c||!/^[0-9a-f]{40}$/.test(a)||c.startsWith("refs/heads/")&&i.set(c.slice(11),a)}return i}var Yr,Rs=E(()=>{"use strict";Yr="refs/codepipe/upstream"});import{homedir as QR}from"node:os";import{existsSync as eT,mkdirSync as tT,readFileSync as rT,writeFileSync as nT}from"node:fs";import{dirname as oT,join as iT}from"node:path";function Gl(){return ee("FARM_PINS")??iT(QR(),".codepipe","farm-pins.json")}function jg(){let t=Gl();if(!eT(t))return{};try{return JSON.parse(rT(t,"utf-8"))}catch{return{}}}function sT(t){let e=Gl();tT(oT(e),{recursive:!0}),nT(e,JSON.stringify(t,null,2)+`
801
- `,{mode:384})}function aT(t){return jg()[t]}function Is(t,e){let r=jg();r[t]=e,sT(r)}function Cs(t,e){let r=ze(e),n=aT(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 ${Gl()}.`);return r}var Kl=E(()=>{"use strict";Ye();ht()});import{setTimeout as cT}from"node:timers/promises";import lT from"ws";function Ps(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new lT(r)}async function gr(t,e,r){return yr(t,e,"/projects",r)}async function Ng(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new J(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function As(t,e,r,n){return yr(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Og(t,e,r,n){return yr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function Lg(t,e,r,n){return yr(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function Mg(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 J(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function _s(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new J(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Hl(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new J(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function Dg(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await Hl(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 cT(r.delayMs??1500)}throw o}async function Ug(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new ti(e)}if(!r.ok)throw new J(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Bg(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new J(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Fg(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new J(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Gg(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 J(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function Kg(t,e,r,n,o){return yr(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function ri(t,e,r,n){return yr(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Wl(t,e,r,n){await yr(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Hg(t,e,r,n){return yr(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Wg(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 J(o.status,s,a)}return s}async function se(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new J(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function yr(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 J(o.status,s,a)}return s}async function js(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new J(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var J,ti,Le=E(()=>{"use strict";J=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};ti=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{existsSync as fy,readFileSync as PT,readdirSync as AT}from"node:fs";import{join as my}from"node:path";import{simpleGit as _T}from"simple-git";import{parse as jT}from"yaml";function Us(t){let e=new Map,r=my(t,Ei);if(!fy(r))return e;let n;try{n=jT(PT(r,"utf-8"))}catch{return e}let o=n?.repos;if(!o||typeof o!="object")return e;for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object")continue;let a=s,c=a.counts??{};typeof a.builtFromCommit=="string"&&e.set(i,{builtFromCommit:a.builtFromCommit,counts:{component:typeof c.component=="number"?c.component:0,code:typeof c.code=="number"?c.code:0,correlates:typeof c.correlates=="number"?c.correlates:0}})}return e}function NT(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return Or({modelFormatVersion:2,repos:e})}function hy(t,e){let r=my(t,e);if(!fy(r))return[];let n=[];for(let o of AT(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...hy(t,i)):n.push(i)}return n}async function Bs(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let f=`model/derived/structure/${d.repo}`;for(let m of hy(t,f))d.emittedShardPaths.has(m)||(n.push({path:m,content:"",deleted:!0}),o++)}let i=Us(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:Ei,content:NT(i)});let s=ys(t),a=pg(s,r.halfLifeDays??lt.halfLifeDays);n.push({path:Ar,content:ws(a)});for(let d of e){let f=[];for(let m of s)for(let y of m.files)re(y.key)?.repo===d.repo&&f.push({kind:"touched_by",from:Re(m.taskKey),to:y.key,...y.churn!==void 0?{weight:y.churn}:{}});n.push({path:La(d.repo),content:jr({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:f})})}let c=_T(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Pe(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(Xo(),zo));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var gy=E(()=>{"use strict";M();Ll();ft()});var Ks={};Ne(Ks,{bootstrapDaemonModel:()=>LT,bootstrapModelForTargets:()=>eu,bootstrapWorkspaceModel:()=>vy,modelBootstrapCommand:()=>Ql,modelBuildCommand:()=>Zl,modelIndexExists:()=>xy,rebuildWorkspaceModelIfStale:()=>DT,shouldAutoBootstrapModel:()=>MT,syncWorkspaceMirrors:()=>$y});import{existsSync as Gs}from"node:fs";import{join as wr}from"node:path";import{cancel as OT,intro as yy,log as zl,outro as Xl}from"@clack/prompts";import{simpleGit as Jl}from"simple-git";function Fs(t){OT(t),process.exit(1)}function wy(t,e,r){let n=t.spec.repos.filter(i=>!e||i.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let i of n){let s=i.mountAs==="."?t.root:wr(t.root,i.mountAs);if(!Gs(wr(s,".git"))){r(`${i.name}: no local clone at ${s} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:i.name,dir:s,defaultBranch:i.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function by(t){let e=Jl(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function ky(t,e,r,n){let o=[];for(let i of e)try{let s=await jl({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await by(i)});o.push(s),n(`${i.name}: ${s.counts.code} files, ${s.counts.component} components, ${s.counts.correlates} co-change edges @ ${s.headCommit.slice(0,10)}`)}catch(s){throw new Error(`${i.name}: ${s instanceof Error?s.message:String(s)}`)}return o}async function Zl(t){yy("codepipe model build");let e=je();e||Fs("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=qr(e.contextDir),n=wy(e,t.repo,s=>zl.warn(s)),o=await ky(e.contextDir,n,r,s=>zl.info(s)),i=await Bs(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?Xl(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):Xl("model already up to date (no changes)")}catch(r){Fs(r instanceof Error?r.message:String(r))}}async function Ql(t){yy("codepipe model bootstrap");let e=je();e||Fs("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await vy(e,t.repo,{onLog:r=>zl.info(r)})}catch(r){Fs(r instanceof Error?r.message:String(r))}Xl("bootstrap complete")}async function vy(t,e,r){let n=wy(t,e,r.onLog);return eu(t.contextDir,n,r)}async function eu(t,e,r){let n=qr(t),o=await ky(t,e,n,r.onLog),i=Lh(t),s=Oh(n.issueKeyPattern,i),a=Wr([...n.ignore,...Wn]),c=[];for(let p of o){let d=e.find(m=>m.name===p.repo),f=await Dh({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:ms(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(f),r.onLog(`${p.repo}: ${f.size} task events mined from history`)}let{files:l,skippedPipeline:u}=Uh(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Pe(t,l,`model: bootstrap ${l.length} task events from history`),await Bs(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function LT(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let s of r){let a=s.mountAs??s.name,c=a==="."?e.root:wr(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&Gs(wr(c,".git"))?(await Jl(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await hr(t,s),o.push({name:s.name,dir:Oe(t,s.name),defaultBranch:l}))}let i=await eu(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function $y(t,e){let r=new Map;for(let n of t.repos){if(!n.mirror)continue;let o=n.mountAs==="."?t.root:wr(t.root,n.mountAs);if(!Gs(wr(o,".git")))continue;let{syncUpstream:i}=await Promise.resolve().then(()=>(Rs(),Es)),s=await i(n,o,{info:a=>e(`[mirror] ${a}`),warn:a=>e(`[mirror] ${a}`)});if(s.error||!s.upstreamHead){e(`[mirror] ${n.name}: sync failed (${s.error??"no upstream head"})`);continue}r.set(n.name,s.upstreamHead)}return r}function xy(t){return Us(t).size>0}function MT(t){return qr(t).enabled&&!xy(t)}async function DT(t,e={}){let r=e.onLog??(()=>{}),n=qr(t.contextDir),o=await $y(t,r);if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=Us(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:wr(t.root,l.mountAs);if(!Gs(wr(u,".git")))continue;let p=Jl(u),d=l.defaultBranch||"main",f=null;if(l.mirror){if(f=o.get(l.name)??null,!f){r(`[mirror] ${l.name}: map not rebuilt \u2014 sync did not complete`);continue}}else e.fetch&&await p.fetch(["origin",d]).catch(()=>{});let m=f??await by({name:l.name,dir:u,defaultBranch:d}),y=(await p.revparse([m]).catch(()=>"")).trim();if(y){if(a.get(l.name)?.builtFromCommit===y){s.push(l.name);continue}try{c.push(await jl({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:y})),i.push(l.name)}catch(b){r(`[model] rebuild of ${l.name} failed: ${b instanceof Error?b.message:String(b)}`)}}}return c.length>0&&(await Bs(t.contextDir,c,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${i.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:i,skipped:s}}var ni=E(()=>{"use strict";ft();gy();Nl();Al();hs();Vo();Gn();Et()});var Ey={};Ne(Ey,{computeDriftReport:()=>KT,supersededAdrIds:()=>Sy});import{existsSync as tu,readFileSync as ru,readdirSync as nu}from"node:fs";import{join as Vn}from"node:path";import{parse as UT}from"yaml";import{simpleGit as BT}from"simple-git";function GT(t,e){let r=Vn(t,`model/derived/structure/${e}`),n=[],o="";if(!tu(r))return{nodes:n,builtFromCommit:o};for(let i of nu(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=Gt(UT(ru(Vn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=re(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function Sy(t){let e=new Set,r=Vn(t,"adr");if(!tu(r))return e;for(let n of nu(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=ru(Vn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function KT(t,e,r){let{nodes:n,builtFromCommit:o}=GT(e,r),i=(await BT(t).revparse(["HEAD"])).trim(),s=await Yo(t,i),a=new Map(s.map(k=>[k.path,k.blobHash])),c=[],l=[],u=new Set,p=[];for(let k of n){if(k.level==="component"){p.push(k);continue}u.add(k.path);let x=a.get(k.path);x?k.contentHash&&x.slice(0,FT)!==k.contentHash&&c.push(k.key):l.push(k.key)}let d=0,f=new Map,m=new Set;for(let k of s){let x=k.path.lastIndexOf("/"),h=x<0?"":k.path.slice(0,x);f.has(h)||f.set(h,new Set),f.get(h).add(k.path),u.has(k.path)||d++;let T=h;for(;T!==""&&!m.has(T);)m.add(T),T=T.includes("/")?T.slice(0,T.lastIndexOf("/")):""}let y=new Map;for(let k of u){let x=k.lastIndexOf("/"),h=x<0?"":k.slice(0,x);y.has(h)||y.set(h,new Set),y.get(h).add(k)}for(let k of p){if(!m.has(k.path)){l.push(k.key);continue}let x=y.get(k.path)??new Set,h=f.get(k.path)??new Set;(x.size!==h.size||[...x].some(R=>!h.has(R)))&&c.push(k.key)}let b=[],w=Sy(e);if(w.size>0){let k=Vn(e,"model/facts/annotations"),x=new Map(n.filter(h=>h.entityId).map(h=>[h.entityId,h.key]));if(tu(k))for(let h of nu(k).sort()){if(!h.endsWith(".md"))continue;let T=h.replace(/\.md$/,""),R=x.get(T);if(R)try{(ru(Vn(k,h),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(N=>`ADR-${N.slice(4).padStart(4,"0")}`).some(N=>w.has(N))&&b.push(R)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(b)].sort(),newFiles:d}}var FT,Ry=E(()=>{"use strict";M();Vo();FT=12});import{execFileSync as ZT}from"node:child_process";import{mkdtempSync as QT,mkdirSync as eI,readFileSync as Iy,rmSync as tI,writeFileSync as rI}from"node:fs";import{tmpdir as nI}from"node:os";import{dirname as oI,join as Cy}from"node:path";function Py(t="codepipe-context"){let e=QT(Cy(nI(),"codepipe-ssh-")),r=Cy(e,"id_ed25519");try{return ZT("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Iy(r,"utf-8"),publicKey:Iy(`${r}.pub`,"utf-8").trim()}}finally{tI(e,{recursive:!0,force:!0})}}async function Ay(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 _y(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 jy(t,e){eI(oI(t),{recursive:!0});let r=e.endsWith(`
811
+ FROM model_fts WHERE model_fts MATCH ? ORDER BY bm25(model_fts), node_id LIMIT ?`).all(o,i).map(c=>({nodeId:c.nodeId,kind:c.kind,score:-c.rank,snippet:c.snippet}))}finally{s.close()}}var ni=E(()=>{"use strict";M()});var Os={};Me(Os,{mirrorLag:()=>xT,syncUpstream:()=>$T});import{simpleGit as Vg}from"simple-git";async function $T(t,e,r,n){let o=Vg(e),i=t.defaultBranch??"main",s=n?.upstream??zg(t);if(!s)return{repo:t.name,upstreamHead:null,updated:!1,error:"repo spec has no host/owner/repo"};try{await o.fetch(s,`+refs/heads/*:${tn}/*`,["--prune"]);let a=(await o.revparse([`${tn}/${i}`]).catch(()=>"")).trim()||null;if(!a)return{repo:t.name,upstreamHead:null,updated:!1,error:`upstream has no branch '${i}'`};let c=n?.mirror??(t.mirror?Xg(t.mirror):null);if(!c)return{repo:t.name,upstreamHead:a,updated:!1};let l=await ST(o),u=await Zl(o,c),p=[];for(let d of l){if(d==="codepipe"||d.startsWith("codepipe/"))continue;let f=(await o.revparse([`${tn}/${d}`]).catch(()=>"")).trim();!f||u.get(d)===f||p.push(`+${f}:refs/heads/${d}`)}return p.length===0?{repo:t.name,upstreamHead:a,updated:!1}:(await o.push([c,...p]),r.info(`${t.name}: mirror \u2190 ${p.length} branch(es), ${i} @ ${a.slice(0,10)}`),{repo:t.name,upstreamHead:a,updated:!0})}catch(a){let c=a instanceof Error?a.message.split(`
812
+ `)[0]:String(a);return{repo:t.name,upstreamHead:null,updated:!1,error:c}}}async function xT(t,e,r){let n=r?.mirror??(t.mirror?Xg(t.mirror):null);if(!n)return null;let o=r?.upstream??zg(t);if(!o)return null;let i=Vg(e),s=t.defaultBranch??"main";try{let a=(await Zl(i,n,s)).get(s);if(!a)return null;let c=(await Zl(i,o,s)).get(s);if(!c)return null;if(c===a)return 0;let l=async()=>{let p=await i.raw(["rev-list","--count",`${a}..${c}`]).catch(()=>null);if(p===null)return null;let d=parseInt(p.trim(),10);return Number.isFinite(d)?d:null},u=await l();return u!==null?u:(await i.fetch(o,`+refs/heads/${s}:${tn}/${s}`),await l())}catch{return null}}function zg(t){return!t.host||!t.owner||!t.repoName?null:t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}function Xg(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 ST(t){return(await t.raw(["for-each-ref",tn,"--format=%(refname)"]).catch(()=>"")).split(`
813
+ `).map(r=>r.trim()).filter(r=>r.startsWith(`${tn}/`)).map(r=>r.slice(tn.length+1))}async function Zl(t,e,r){let n=r?["--heads",e,r]:["--heads",e],o=await t.listRemote(n),i=new Map;for(let s of o.split(`
814
+ `)){let[a,c]=s.trim().split(/\s+/);!a||!c||!/^[0-9a-f]{40}$/.test(a)||c.startsWith("refs/heads/")&&i.set(c.slice(11),a)}return i}var tn,Ls=E(()=>{"use strict";tn="refs/codepipe/upstream"});import{homedir as ET}from"node:os";import{existsSync as RT,mkdirSync as TT,readFileSync as IT,writeFileSync as CT}from"node:fs";import{dirname as PT,join as AT}from"node:path";function Ql(){return ee("FARM_PINS")??AT(ET(),".codepipe","farm-pins.json")}function Qg(){let t=Ql();if(!RT(t))return{};try{return JSON.parse(IT(t,"utf-8"))}catch{return{}}}function _T(t){let e=Ql();TT(PT(e),{recursive:!0}),CT(e,JSON.stringify(t,null,2)+`
815
+ `,{mode:384})}function jT(t){return Qg()[t]}function Ds(t,e){let r=Qg();r[t]=e,_T(r)}function Us(t,e){let r=Qe(e),n=jT(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 ${Ql()}.`);return r}var eu=E(()=>{"use strict";Je();kt()});import{setTimeout as NT}from"node:timers/promises";import OT from"ws";function Bs(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new OT(r)}async function vr(t,e,r){return $r(t,e,"/projects",r)}async function ey(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new J(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Fs(t,e,r,n){return $r(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function ty(t,e,r,n){return $r(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function ry(t,e,r,n){return $r(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function ny(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 J(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function Gs(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new J(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function tu(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new J(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}async function oy(t,e,r={}){let n=r.attempts??3,o;for(let i=0;i<n;i++)try{let s=await tu(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 NT(r.delayMs??1500)}throw o}async function iy(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 ci(e)}if(!r.ok)throw new J(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function sy(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new J(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function ay(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new J(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function cy(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 J(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function ly(t,e,r,n,o){return $r(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function li(t,e,r,n){return $r(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function ru(t,e,r,n){await $r(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function uy(t,e,r,n){return $r(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function dy(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 J(o.status,s,a)}return s}async function se(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new J(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function $r(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 J(o.status,s,a)}return s}async function Ks(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/deliverables`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new J(n.status,null,`GET /deliverables HTTP ${n.status}`);return(await n.json()).deliverables}var J,ci,Be=E(()=>{"use strict";J=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};ci=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}}});import{existsSync as jy,readFileSync as rI,readdirSync as nI}from"node:fs";import{join as Ny}from"node:path";import{simpleGit as oI}from"simple-git";import{parse as iI}from"yaml";function zs(t){let e=new Map,r=Ny(t,_i);if(!jy(r))return e;let n;try{n=iI(rI(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 sI(t){let e={};for(let[r,n]of t)e[r]={builtFromCommit:n.builtFromCommit,counts:n.counts};return Fr({modelFormatVersion:2,repos:e})}function Oy(t,e){let r=Ny(t,e);if(!jy(r))return[];let n=[];for(let o of nI(r,{withFileTypes:!0})){let i=`${e}/${o.name}`;o.isDirectory()?n.push(...Oy(t,i)):n.push(i)}return n}async function Xs(t,e,r={}){let n=[],o=0;for(let d of e){n.push(...d.files);let f=`model/derived/structure/${d.repo}`;for(let m of Oy(t,f))d.emittedShardPaths.has(m)||(n.push({path:m,content:"",deleted:!0}),o++)}let i=zs(t);for(let d of e)i.set(d.repo,{builtFromCommit:d.headCommit,counts:d.counts});n.push({path:_i,content:sI(i)});let s=Ts(t),a=_g(s,r.halfLifeDays??mt.halfLifeDays);n.push({path:Mr,content:Is(a)});for(let d of e){let f=[];for(let m of s)for(let y of m.files)re(y.key)?.repo===d.repo&&f.push({kind:"touched_by",from:Re(m.taskKey),to:y.key,...y.churn!==void 0?{weight:y.churn}:{}});n.push({path:Ha(d.repo),content:Ur({modelFormatVersion:2,repo:d.repo,builtFromCommit:d.headCommit,edges:f})})}let c=oI(t),l=(await c.revparse(["HEAD"]).catch(()=>"")).trim(),u=`model: build ${e.map(d=>`${d.repo}@${d.headCommit.slice(0,10)}`).join(", ")}`;await Pe(t,n,u);let p=(await c.revparse(["HEAD"]).catch(()=>"")).trim();if(p!==l){let{rebuildSearchIndex:d}=await Promise.resolve().then(()=>(ni(),ri));await d(t).catch(()=>{})}return{committed:p!==l,filesWritten:n.filter(d=>!d.deleted).length,filesDeleted:o}}var Ly=E(()=>{"use strict";M();Yl();Le()});var Qs={};Me(Qs,{bootstrapDaemonModel:()=>cI,bootstrapModelForTargets:()=>du,bootstrapWorkspaceModel:()=>Fy,modelBootstrapCommand:()=>uu,modelBuildCommand:()=>lu,modelIndexExists:()=>Ky,rebuildWorkspaceModelIfStale:()=>uI,shouldAutoBootstrapModel:()=>lI,syncWorkspaceMirrors:()=>Gy});import{existsSync as Zs}from"node:fs";import{join as xr}from"node:path";import{cancel as aI,intro as My,log as su,outro as au}from"@clack/prompts";import{simpleGit as cu}from"simple-git";function Js(t){aI(t),process.exit(1)}function Dy(t,e,r){let n=t.spec.repos.filter(i=>!e||i.name===e);if(n.length===0)throw new Error(e?`repo "${e}" is not part of this project (see project.yaml)`:"the project has no repos configured");let o=[];for(let i of n){let s=i.mountAs==="."?t.root:xr(t.root,i.mountAs);if(!Zs(xr(s,".git"))){r(`${i.name}: no local clone at ${s} \u2014 skipped (run \`codepipe clone\` first)`);continue}o.push({name:i.name,dir:s,defaultBranch:i.defaultBranch||"main"})}if(o.length===0)throw new Error("nothing to do \u2014 no repo clones found");return o}async function Uy(t){let e=cu(t.dir),r=`origin/${t.defaultBranch}`;return await e.raw(["rev-parse","--verify",r]).then(()=>!0).catch(()=>!1)?r:"HEAD"}async function By(t,e,r,n){let o=[];for(let i of e)try{let s=await Hl({repo:i.name,repoDir:i.dir,contextDir:t,settings:r,ref:await Uy(i)});o.push(s),n(`${i.name}: ${s.counts.code} files, ${s.counts.component} components, ${s.counts.correlates} co-change edges @ ${s.headCommit.slice(0,10)}`)}catch(s){throw new Error(`${i.name}: ${s instanceof Error?s.message:String(s)}`)}return o}async function lu(t){My("codepipe model build");let e=Ne();e||Js("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{let r=en(e.contextDir),n=Dy(e,t.repo,s=>su.warn(s)),o=await By(e.contextDir,n,r,s=>su.info(s)),i=await Xs(e.contextDir,o,{halfLifeDays:r.cochange.halfLifeDays});i.committed?au(`model updated: ${i.filesWritten} files written, ${i.filesDeleted} stale removed`):au("model already up to date (no changes)")}catch(r){Js(r instanceof Error?r.message:String(r))}}async function uu(t){My("codepipe model bootstrap");let e=Ne();e||Js("not inside a project workspace \u2014 run from a folder with .codepipe/ (see `codepipe init`)");try{await Fy(e,t.repo,{onLog:r=>su.info(r)})}catch(r){Js(r instanceof Error?r.message:String(r))}au("bootstrap complete")}async function Fy(t,e,r){let n=Dy(t,e,r.onLog);return du(t.contextDir,n,r)}async function du(t,e,r){let n=en(t),o=await By(t,e,n,r.onLog),i=rg(t),s=tg(n.issueKeyPattern,i),a=Qr([...n.ignore,...Xn]),c=[];for(let p of o){let d=e.find(m=>m.name===p.repo),f=await og({repo:p.repo,repoDir:d.dir,headCommit:p.headCommit,windowCommits:n.cochange.windowCommits,issueKeyRe:s,pathToCurrent:Ss(p.identityTable),entityByKey:p.entityByKey,ignored:a,trackerProjectKey:i});c.push(f),r.onLog(`${p.repo}: ${f.size} task events mined from history`)}let{files:l,skippedPipeline:u}=ig(t,c);return u>0&&r.onLog(`${u} events already recorded by the live pipeline \u2014 left untouched`),l.length>0&&await Pe(t,l,`model: bootstrap ${l.length} task events from history`),await Xs(t,o,{halfLifeDays:n.cochange.halfLifeDays}),{events:l.length}}async function cI(t,e,r,n){if(r.length===0)throw new Error("the project has no repos configured");let o=[];for(let s of r){let a=s.mountAs??s.name,c=a==="."?e.root:xr(e.root,a),l=s.defaultBranch||"main";c!==e.contextDir&&Zs(xr(c,".git"))?(await cu(c).fetch(["origin",l]).catch(()=>{}),o.push({name:s.name,dir:c,defaultBranch:l})):(n(`${s.name}: materializing clone in the daemon layout`),await br(t,s),o.push({name:s.name,dir:Ue(t,s.name),defaultBranch:l}))}let i=await du(e.contextDir,o,{onLog:n});return{repos:o.length,events:i.events}}async function Gy(t,e){let r=new Map;for(let n of t.repos){if(!n.mirror)continue;let o=n.mountAs==="."?t.root:xr(t.root,n.mountAs);if(!Zs(xr(o,".git")))continue;let{syncUpstream:i}=await Promise.resolve().then(()=>(Ls(),Os)),s=await i(n,o,{info:a=>e(`[mirror] ${a}`),warn:a=>e(`[mirror] ${a}`)});if(s.error||!s.upstreamHead){e(`[mirror] ${n.name}: sync failed (${s.error??"no upstream head"})`);continue}r.set(n.name,s.upstreamHead)}return r}function Ky(t){return zs(t).size>0}function lI(t){return en(t).enabled&&!Ky(t)}async function uI(t,e={}){let r=e.onLog??(()=>{}),n=en(t.contextDir),o=await Gy(t,r);if(!n.enabled)return{rebuilt:[],skipped:[]};let i=[],s=[],a=zs(t.contextDir),c=[];for(let l of t.repos){let u=l.mountAs==="."?t.root:xr(t.root,l.mountAs);if(!Zs(xr(u,".git")))continue;let p=cu(u),d=l.defaultBranch||"main",f=null;if(l.mirror){if(f=o.get(l.name)??null,!f){r(`[mirror] ${l.name}: map not rebuilt \u2014 sync did not complete`);continue}}else e.fetch&&await p.fetch(["origin",d]).catch(()=>{});let m=f??await Uy({name:l.name,dir:u,defaultBranch:d}),y=(await p.revparse([m]).catch(()=>"")).trim();if(y){if(a.get(l.name)?.builtFromCommit===y){s.push(l.name);continue}try{c.push(await Hl({repo:l.name,repoDir:u,contextDir:t.contextDir,settings:n,ref:y})),i.push(l.name)}catch(b){r(`[model] rebuild of ${l.name} failed: ${b instanceof Error?b.message:String(b)}`)}}}return c.length>0&&(await Xs(t.contextDir,c,{halfLifeDays:n.cochange.halfLifeDays}),r(`[model] release-path rebuild: ${i.join(", ")} (skipped up-to-date: ${s.join(", ")||"\u2014"})`)),{rebuilt:i,skipped:s}}var ui=E(()=>{"use strict";Le();Ly();Wl();Gl();Es();ti();Yn();Ct()});var Wy={};Me(Wy,{computeDriftReport:()=>hI,supersededAdrIds:()=>Hy});import{existsSync as pu,readFileSync as fu,readdirSync as mu}from"node:fs";import{join as Qn}from"node:path";import{parse as dI}from"yaml";import{simpleGit as pI}from"simple-git";function mI(t,e){let r=Qn(t,`model/derived/structure/${e}`),n=[],o="";if(!pu(r))return{nodes:n,builtFromCommit:o};for(let i of mu(r).sort()){if(!i.endsWith(".yaml"))continue;let s;try{let a=qt(dI(fu(Qn(r,i),"utf-8")));if(!a.ok)continue;s=a.value}catch{continue}o=s.builtFromCommit;for(let a of s.nodes){let c=re(a.key);!c||c.level!=="code"&&c.level!=="component"||n.push({key:a.key,path:c.path,level:c.level,contentHash:a.contentHash,entityId:a.entityId})}}return{nodes:n,builtFromCommit:o}}function Hy(t){let e=new Set,r=Qn(t,"adr");if(!pu(r))return e;for(let n of mu(r).sort()){let o=/^(\d{4})-/.exec(n)?.[1];if(!(!o||!n.endsWith(".md")))try{let i=fu(Qn(r,n),"utf-8").slice(0,600).toLowerCase();/status[^\n]*superseded/.test(i)&&e.add(`ADR-${o}`)}catch{}}return e}async function hI(t,e,r){let{nodes:n,builtFromCommit:o}=mI(e,r),i=(await pI(t).revparse(["HEAD"])).trim(),s=await ei(t,i),a=new Map(s.map(k=>[k.path,k.blobHash])),c=[],l=[],u=new Set,p=[];for(let k of n){if(k.level==="component"){p.push(k);continue}u.add(k.path);let x=a.get(k.path);x?k.contentHash&&x.slice(0,fI)!==k.contentHash&&c.push(k.key):l.push(k.key)}let d=0,f=new Map,m=new Set;for(let k of s){let x=k.path.lastIndexOf("/"),h=x<0?"":k.path.slice(0,x);f.has(h)||f.set(h,new Set),f.get(h).add(k.path),u.has(k.path)||d++;let T=h;for(;T!==""&&!m.has(T);)m.add(T),T=T.includes("/")?T.slice(0,T.lastIndexOf("/")):""}let y=new Map;for(let k of u){let x=k.lastIndexOf("/"),h=x<0?"":k.slice(0,x);y.has(h)||y.set(h,new Set),y.get(h).add(k)}for(let k of p){if(!m.has(k.path)){l.push(k.key);continue}let x=y.get(k.path)??new Set,h=f.get(k.path)??new Set;(x.size!==h.size||[...x].some(R=>!h.has(R)))&&c.push(k.key)}let b=[],w=Hy(e);if(w.size>0){let k=Qn(e,"model/facts/annotations"),x=new Map(n.filter(h=>h.entityId).map(h=>[h.entityId,h.key]));if(pu(k))for(let h of mu(k).sort()){if(!h.endsWith(".md"))continue;let T=h.replace(/\.md$/,""),R=x.get(T);if(R)try{(fu(Qn(k,h),"utf-8").match(/\bADR-(\d{3,4})\b/g)??[]).map(N=>`ADR-${N.slice(4).padStart(4,"0")}`).some(N=>w.has(N))&&b.push(R)}catch{}}}return{repo:r,builtFromCommit:o,headCommit:i,stale:[...new Set(c)].sort(),orphaned:[...new Set(l)].sort(),superseded:[...new Set(b)].sort(),newFiles:d}}var fI,qy=E(()=>{"use strict";M();ti();fI=12});import{execFileSync as SI}from"node:child_process";import{mkdtempSync as EI,mkdirSync as RI,readFileSync as Vy,rmSync as TI,writeFileSync as II}from"node:fs";import{tmpdir as CI}from"node:os";import{dirname as PI,join as zy}from"node:path";function Xy(t="codepipe-context"){let e=EI(zy(CI(),"codepipe-ssh-")),r=zy(e,"id_ed25519");try{return SI("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Vy(r,"utf-8"),publicKey:Vy(`${r}.pub`,"utf-8").trim()}}finally{TI(e,{recursive:!0,force:!0})}}async function Jy(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 Zy(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 Qy(t,e){RI(PI(t),{recursive:!0});let r=e.endsWith(`
802
816
  `)?e:e+`
803
- `;return rI(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var au=E(()=>{"use strict"});import{existsSync as Ny,mkdirSync as Oy}from"node:fs";import{dirname as Ly}from"node:path";import{simpleGit as zn}from"simple-git";function iI(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 sI(t,e){return e?.contextWrite?.token?{user:jo(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:qt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function My(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 Ws))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 qs(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await se(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new Ws(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=sI(Ur(s.cloneUrl),r);if(a){let c=await aI({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 cI({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 aI(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=iI(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(Ny(`${r}/.git`)){let l=zn(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=il(r);await l.reset(["--hard",`origin/${s}`]),sl(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Oy(Ly(r),{recursive:!0}),await zn().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Dy(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 cI(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=jy(i,n),a=_y(e.cloneUrl),c=e.branch;try{if(Ny(`${r}/.git`)){let l=zn(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=il(r);await l.reset(["--hard",`origin/${c}`]),sl(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Oy(Ly(r),{recursive:!0}),await zn().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await zn(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Dy(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 Dy(t){let e=zn(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 Ws,cu=E(()=>{"use strict";M();Le();Jt();au();Ws=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as lI}from"node:child_process";function uI(){try{return lI("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function By(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:uI(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var Fy=E(()=>{"use strict"});import{homedir as dI}from"node:os";import{mkdirSync as pI,readFileSync as fI,writeFileSync as mI,existsSync as Gy}from"node:fs";import{dirname as hI,join as uu}from"node:path";function gI(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Ct(t){let e=ee("SANDBOX_CONFIG");if(e)return e;let r=uu(dI(),".codepipe","worker");return t?uu(r,"profiles",t,"config.json"):uu(r,"config.json")}function Ky(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Ke(t){let e=Ct(t),r=null;return Gy(e)&&(r=JSON.parse(fI(e,"utf-8"))),r?(r.planningLane=gI(),r):null}function Hy(t,e){let r=Ct(e);pI(hI(r),{recursive:!0}),mI(r,JSON.stringify(t,null,2)+`
804
- `,{mode:384})}var Ys=E(()=>{"use strict";Ye();Gy(".env")&&process.loadEnvFile(".env")});import yI from"ws";var Xn,du=E(()=>{"use strict";Xn=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()}`)}async reportAgentAuth(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/sandbox/agent-auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});return r.ok?(await r.json()).probe===!0:!1}async reportAgentAuthResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/sandbox/agent-auth/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`agent-auth result failed: ${r.status} ${await r.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 yI(e)}}});import{hostname as wI}from"node:os";async function zr(t){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 ${Ct(t.profile)}.`),process.exit(1));let r=t.name??wI(),n=By({projects:t.projects??[],llm:t.llm??null}),o=new Xn(t.hub.replace(/\/$/,"")),i=as(),s=ze(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});Hy({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Ct(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 Wy=E(()=>{"use strict";ht();Fy();Ys();du()});function qy(t){return t?`Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in ${t}, regardless of the language the user writes in (the project pinned ${t} for the chat).`:"Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in the language of the user's most recent chat message. When the user switches language mid-conversation, switch with them. Judge the language by the human prose only: ignore code snippets, file paths and identifiers. If a message is too short to tell (a bare keyword, pure code), keep the language of the conversation so far."}function Vs(t){return t?`Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in ${t} (the project's configured language), unless your prompt pins a different language for a specific output. In-repo content (code, code comments, commit messages) follows the project's existing conventions and any explicit instructions in your prompt.`:"Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in the language of the task description and user input embedded in your prompt, NOT the language the surrounding instructions are written in. Judge that language by the human prose only, ignoring code snippets, file paths and identifiers. In-repo content (code, code comments, commit messages) follows the project's existing conventions instead."}function Yy(t){return t?`[Session note: the instructions from the start of this conversation remain in force. Reply in ${t} \u2014 including the brief status notes between tool calls.]`:"[Session note: the instructions from the start of this conversation remain in force. Reply in the language of the user's message above \u2014 including the brief status notes between tool calls. Judge the language by the human prose, ignoring code snippets and identifiers.]"}function Jn(t){let e=t?.responseLanguage;if(typeof e!="string")return;let r=e.trim();return r.length>0&&r.toLowerCase()!=="auto"?r:void 0}var zs=E(()=>{"use strict"});import{spawn as bI}from"node:child_process";function pu(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function vI(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 $I(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Xr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function fu(t,e){let r=[{type:"text",text:t}];return e&&r.push({type:"text",text:e}),JSON.stringify({type:"user",message:{role:"user",content:r}})+`
805
- `}async function Jy(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Pt;let r=Jn(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",qy(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim()),e.effort&&e.effort.trim().length>0&&(await mu(t)?n.push("--effort",e.effort.trim()):console.warn(`[claude] effort '${e.effort.trim()}' requested but this Claude Code does not support --effort \u2014 running at the default effort`));for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,i=l=>{if(o)try{o(l)}catch{}},s=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let f of d?.content??[]){let m=f.type;if(m==="text"){let y=String(f.text??"").trim();y&&i({ts:u,kind:"text",author:"agent",text:pu(y,Vy)})}else if(m==="tool_use"){let y=String(f.name??""),b=f.input?.file_path??f.input?.path,w=vI(b,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:y,...w?{file:w}:{}})}}return}if(p==="user"){let d=l.message;for(let f of d?.content??[])if(f.type==="tool_result"){let m=f.is_error===!0,y=m?pu($I(f.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:m,...y?{text:y}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();i({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&i({ts:u,kind:"system",author:"agent",text:d})}};return i({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=bI(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,f=!1,m=null,y=()=>{d=!0,p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),zy)};e.signal?.addEventListener("abort",y,{once:!0});let b=null,w=()=>{b&&clearTimeout(b),b=setTimeout(()=>{f=!0,console.warn(`[claude:chat] idle for ${Xy}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),zy)},Xy)},k=()=>{m&&clearTimeout(m),b&&clearTimeout(b),e.signal?.removeEventListener("abort",y)},x=!0,h=v=>{if(!(!x||p.stdin.destroyed))try{p.stdin.write(v)}catch{}};h(fu(e.prompt)),w(),(async()=>{try{for await(let v of e.interactive.inbox){if(d||!x)break;if(w(),v.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:pu(v.text,Vy)}),h(fu(v.text,Yy(r)));else{h(fu(kI)),x=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let T="",R=v=>{let _;try{_=JSON.parse(v)}catch{return}c(_)};p.stdout.on("data",v=>{s.push(v),w(),T+=v;let _;for(;(_=T.indexOf(`
806
- `))!==-1;){let N=T.slice(0,_).trim();T=T.slice(_+1),N&&R(N)}}),p.stderr.on("data",v=>{s.push(v);for(let _ of v.split(`
807
- `)){let N=_.trim();N&&console.warn(`[claude:chat:stderr] ${N}`)}}),p.on("error",v=>{k(),u(v)}),p.on("close",v=>{if(k(),d){u(new Pt);return}if(f){u(new Error("chat session ended: idle for too long without a reply"));return}T.trim()&&R(T.trim()),console.log(`[claude:chat] exit code=${v}`),l({artifactPaths:[],log:s.join(""),usage:xI(a)})})})}function xI(t){let e=ut();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=Xr(r.input_tokens),e.outputTokens=Xr(r.output_tokens),e.cacheReadInputTokens=Xr(r.cache_read_input_tokens),e.cacheCreationInputTokens=Xr(r.cache_creation_input_tokens)),e.totalCostUsd=Xr(t.total_cost_usd),e.numTurns=Xr(t.num_turns),e.durationMs=Xr(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Vy,zy,Xy,kI,Zy=E(()=>{"use strict";M();br();zs();Vy=16e3,zy=5e3,Xy=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),kI="The user has finished the conversation. Now, based on everything discussed, write the DRAFT.md file in your current working directory following the contract from your instructions (line 1 \u2014 the issue title, \u2264 80 chars; line 2 \u2014 blank; lines 3+ \u2014 the body in Markdown), in the language of the conversation, and end your turn. Write nothing else."});import{execFile as SI,spawn as EI}from"node:child_process";import{existsSync as RI}from"node:fs";function TI(t,e,r,n){let o=e??"",i=/hit your (session|weekly|usage) limit/i.exec(o);if(t!==429&&!i)return null;let s={};if(/weekly limit/i.test(o)||r?.rateLimitType==="seven_day"?s.kind="weekly":(/session limit/i.test(o)||r?.rateLimitType==="five_hour")&&(s.kind="session"),r&&r.resetsAt>0){let u=Math.round(r.resetsAt*1e3);if(u>n)return s.resetAtMs=u,s}let a=/resets(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s*\(UTC\)/i.exec(o);if(a){let u=Number(a[1])%12;a[3].toLowerCase()==="pm"&&(u+=12);let p=a[2]?Number(a[2]):0,d=new Date(n);return d.setUTCHours(u,p,0,0),d.getTime()<=n&&d.setUTCDate(d.getUTCDate()+1),s.resetAtMs=d.getTime(),s}let c=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(o),l=c?Number(c[1]??c[2]):NaN;return Number.isFinite(l)&&l>0&&(s.resetAtMs=n+l*1e3),s}function CI(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function mu(t){let e=hu.get(t);return e||(e=new Promise(r=>{SI(t,["--help"],{timeout:15e3},(n,o,i)=>{if(n){hu.delete(t),r(!1);return}r(`${o}
808
- ${i}`.includes("--effort"))})}),hu.set(t,e)),e}function Qy(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: ${kr(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=_I(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=tw(o.content);console.log(`[claude] tool_result (error)${i?`: ${kr(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)} ${kr(JSON.stringify(e),200)}`),e}function PI(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(kr(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(kr(r.trim().split(`
817
+ `;return II(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}var wu=E(()=>{"use strict"});import{existsSync as ew,mkdirSync as tw}from"node:fs";import{dirname as rw}from"node:path";import{simpleGit as eo}from"simple-git";function AI(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 _I(t,e){return e?.contextWrite?.token?{user:Uo(t),secret:e.contextWrite.token}:t===An.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===An.bitbucket?e?.bitbucket?.apiToken?{user:Xt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function nw(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 ta))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 ra(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await se(e.hubUrl,e.cliToken,e.projectId)}catch(c){throw new ta(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=_I(Wr(s.cloneUrl),r);if(a){let c=await jI({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 NI({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 jI(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=AI(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(ew(`${r}/.git`)){let l=eo(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=fl(r);await l.reset(["--hard",`origin/${s}`]),ml(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else tw(rw(r),{recursive:!0}),await eo().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await ow(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 NI(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Qy(i,n),a=Zy(e.cloneUrl),c=e.branch;try{if(ew(`${r}/.git`)){let l=eo(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=fl(r);await l.reset(["--hard",`origin/${c}`]),ml(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else tw(rw(r),{recursive:!0}),await eo().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await eo(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await ow(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 ow(t){let e=eo(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 ta,bu=E(()=>{"use strict";M();Be();Bt();wu();ta=class extends Error{constructor(e){super(`could not fetch project summary: ${e instanceof Error?e.message:String(e)}`),this.name="HubSummaryUnreachableError"}}});import{spawnSync as OI}from"node:child_process";function LI(){try{return OI("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function sw(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:LI(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}var aw=E(()=>{"use strict"});import{homedir as MI}from"node:os";import{mkdirSync as DI,readFileSync as UI,writeFileSync as BI,existsSync as cw}from"node:fs";import{dirname as FI,join as vu}from"node:path";function GI(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Nt(t){let e=ee("SANDBOX_CONFIG");if(e)return e;let r=vu(MI(),".codepipe","worker");return t?vu(r,"profiles",t,"config.json"):vu(r,"config.json")}function lw(t,e,r){return t?`sandbox-${t}`:r?`sandbox-${e}`:"sandbox"}function Ve(t){let e=Nt(t),r=null;return cw(e)&&(r=JSON.parse(UI(e,"utf-8"))),r?(r.planningLane=GI(),r):null}function uw(t,e){let r=Nt(e);DI(FI(r),{recursive:!0}),BI(r,JSON.stringify(t,null,2)+`
818
+ `,{mode:384})}var na=E(()=>{"use strict";Je();cw(".env")&&process.loadEnvFile(".env")});import KI from"ws";var to,$u=E(()=>{"use strict";to=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()}`)}async reportAgentAuth(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/sandbox/agent-auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});return r.ok?(await r.json()).probe===!0:!1}async reportAgentAuthResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/sandbox/agent-auth/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`agent-auth result failed: ${r.status} ${await r.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 KI(e)}}});import{hostname as HI}from"node:os";async function nn(t){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 ${Nt(t.profile)}.`),process.exit(1));let r=t.name??HI(),n=sw({projects:t.projects??[],llm:t.llm??null}),o=new to(t.hub.replace(/\/$/,"")),i=bs(),s=Qe(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});uw({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Nt(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}var dw=E(()=>{"use strict";kt();aw();na();$u()});function pw(t){return t?`Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in ${t}, regardless of the language the user writes in (the project pinned ${t} for the chat).`:"Write ALL user-visible text \u2014 full replies and the brief status notes you emit between tool calls alike \u2014 in the language of the user's most recent chat message. When the user switches language mid-conversation, switch with them. Judge the language by the human prose only: ignore code snippets, file paths and identifiers. If a message is too short to tell (a bare keyword, pure code), keep the language of the conversation so far."}function oa(t){return t?`Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in ${t} (the project's configured language), unless your prompt pins a different language for a specific output. In-repo content (code, code comments, commit messages) follows the project's existing conventions and any explicit instructions in your prompt.`:"Write ALL user-facing prose \u2014 brief status notes between tool calls, questions, summaries and the bodies of Markdown artifacts you produce for humans \u2014 in the language of the task description and user input embedded in your prompt, NOT the language the surrounding instructions are written in. Judge that language by the human prose only, ignoring code snippets, file paths and identifiers. In-repo content (code, code comments, commit messages) follows the project's existing conventions instead."}function fw(t){return t?`[Session note: the instructions from the start of this conversation remain in force. Reply in ${t} \u2014 including the brief status notes between tool calls.]`:"[Session note: the instructions from the start of this conversation remain in force. Reply in the language of the user's message above \u2014 including the brief status notes between tool calls. Judge the language by the human prose, ignoring code snippets and identifiers.]"}function ro(t){let e=t?.responseLanguage;if(typeof e!="string")return;let r=e.trim();return r.length>0&&r.toLowerCase()!=="auto"?r:void 0}var ia=E(()=>{"use strict"});import{spawn as WI}from"node:child_process";function xu(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function YI(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 VI(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function on(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Su(t,e){let r=[{type:"text",text:t}];return e&&r.push({type:"text",text:e}),JSON.stringify({type:"user",message:{role:"user",content:r}})+`
819
+ `}async function yw(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Ot;let r=ro(e.metadata),n=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",pw(r)];e.model&&e.model.trim().length>0&&n.push("--model",e.model.trim()),e.effort&&e.effort.trim().length>0&&(await Eu(t)?n.push("--effort",e.effort.trim()):console.warn(`[claude] effort '${e.effort.trim()}' requested but this Claude Code does not support --effort \u2014 running at the default effort`));for(let l of e.addDirs??[])n.push("--add-dir",l);let o=e.onActivity,i=l=>{if(o)try{o(l)}catch{}},s=[],a=null,c=l=>{let u=Date.now(),p=l.type;if(p==="assistant"){let d=l.message;for(let f of d?.content??[]){let m=f.type;if(m==="text"){let y=String(f.text??"").trim();y&&i({ts:u,kind:"text",author:"agent",text:xu(y,mw)})}else if(m==="tool_use"){let y=String(f.name??""),b=f.input?.file_path??f.input?.path,w=YI(b,e.workspaceDir);i({ts:u,kind:"tool",author:"agent",tool:y,...w?{file:w}:{}})}}return}if(p==="user"){let d=l.message;for(let f of d?.content??[])if(f.type==="tool_result"){let m=f.is_error===!0,y=m?xu(VI(f.content),200):"";i({ts:u,kind:"tool_result",author:"agent",isError:m,...y?{text:y}:{}})}return}if(p==="result"){a=l;let d=String(l.subtype??"").trim();i({ts:u,kind:"result",author:"agent",...d?{text:d}:{}});return}if(p==="system"){let d=String(l.subtype??"").trim();d&&i({ts:u,kind:"system",author:"agent",text:d})}};return i({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((l,u)=>{let p=WI(t,n,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});p.stdout.setEncoding("utf-8"),p.stderr.setEncoding("utf-8");let d=!1,f=!1,m=null,y=()=>{d=!0,p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),hw)};e.signal?.addEventListener("abort",y,{once:!0});let b=null,w=()=>{b&&clearTimeout(b),b=setTimeout(()=>{f=!0,console.warn(`[claude:chat] idle for ${gw}ms \u2014 ending session`),p.kill("SIGTERM"),m=setTimeout(()=>p.kill("SIGKILL"),hw)},gw)},k=()=>{m&&clearTimeout(m),b&&clearTimeout(b),e.signal?.removeEventListener("abort",y)},x=!0,h=v=>{if(!(!x||p.stdin.destroyed))try{p.stdin.write(v)}catch{}};h(Su(e.prompt)),w(),(async()=>{try{for await(let v of e.interactive.inbox){if(d||!x)break;if(w(),v.kind==="user")i({ts:Date.now(),kind:"text",author:"user",text:xu(v.text,mw)}),h(Su(v.text,fw(r)));else{h(Su(qI)),x=!1;try{p.stdin.end()}catch{}break}}}catch{}})();let T="",R=v=>{let P;try{P=JSON.parse(v)}catch{return}c(P)};p.stdout.on("data",v=>{s.push(v),w(),T+=v;let P;for(;(P=T.indexOf(`
820
+ `))!==-1;){let N=T.slice(0,P).trim();T=T.slice(P+1),N&&R(N)}}),p.stderr.on("data",v=>{s.push(v);for(let P of v.split(`
821
+ `)){let N=P.trim();N&&console.warn(`[claude:chat:stderr] ${N}`)}}),p.on("error",v=>{k(),u(v)}),p.on("close",v=>{if(k(),d){u(new Ot);return}if(f){u(new Error("chat session ended: idle for too long without a reply"));return}T.trim()&&R(T.trim()),console.log(`[claude:chat] exit code=${v}`),l({artifactPaths:[],log:s.join(""),usage:zI(a)})})})}function zI(t){let e=ht();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=on(r.input_tokens),e.outputTokens=on(r.output_tokens),e.cacheReadInputTokens=on(r.cache_read_input_tokens),e.cacheCreationInputTokens=on(r.cache_creation_input_tokens)),e.totalCostUsd=on(t.total_cost_usd),e.numTurns=on(t.num_turns),e.durationMs=on(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var mw,hw,gw,qI,ww=E(()=>{"use strict";M();Sr();ia();mw=16e3,hw=5e3,gw=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),qI="The user has finished the conversation. Now, based on everything discussed, write the DRAFT.md file in your current working directory following the contract from your instructions (line 1 \u2014 the issue title, \u2264 80 chars; line 2 \u2014 blank; lines 3+ \u2014 the body in Markdown), in the language of the conversation, and end your turn. Write nothing else."});import{execFile as XI,spawn as JI}from"node:child_process";import{existsSync as ZI}from"node:fs";function QI(t,e,r,n){let o=e??"",i=/hit your (session|weekly|usage) limit/i.exec(o);if(t!==429&&!i)return null;let s={};if(/weekly limit/i.test(o)||r?.rateLimitType==="seven_day"?s.kind="weekly":(/session limit/i.test(o)||r?.rateLimitType==="five_hour")&&(s.kind="session"),r&&r.resetsAt>0){let u=Math.round(r.resetsAt*1e3);if(u>n)return s.resetAtMs=u,s}let a=/resets(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s*\(UTC\)/i.exec(o);if(a){let u=Number(a[1])%12;a[3].toLowerCase()==="pm"&&(u+=12);let p=a[2]?Number(a[2]):0,d=new Date(n);return d.setUTCHours(u,p,0,0),d.getTime()<=n&&d.setUTCDate(d.getUTCDate()+1),s.resetAtMs=d.getTime(),s}let c=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(o),l=c?Number(c[1]??c[2]):NaN;return Number.isFinite(l)&&l>0&&(s.resetAtMs=n+l*1e3),s}function tC(t){return t.includes("\0")?t.replace(/\u0000/g,""):t}function Eu(t){let e=Ru.get(t);return e||(e=new Promise(r=>{XI(t,["--help"],{timeout:15e3},(n,o,i)=>{if(n){Ru.delete(t),r(!1);return}r(`${o}
822
+ ${i}`.includes("--effort"))})}),Ru.set(t,e)),e}function bw(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: ${Er(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=oC(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=vw(o.content);console.log(`[claude] tool_result (error)${i?`: ${Er(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)} ${Er(JSON.stringify(e),200)}`),e}function rC(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(Er(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(Er(r.trim().split(`
809
823
  `).slice(-5).join(`
810
- `),500)),n.join(" \u2014 ")}function AI(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 tw(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function _I(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=${kr(r,80)}`}return""}function kr(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Xe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function jI(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=Xe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:Xe(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 gu(t,e,r,n){let o=ut(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=Xe(i.input_tokens),o.outputTokens=Xe(i.output_tokens),o.cacheReadInputTokens=Xe(i.cache_read_input_tokens),o.cacheCreationInputTokens=Xe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=Xe(t?.total_cost_usd),o.numTurns=t&&Xe(t.num_turns)>0?Xe(t.num_turns):r,o.durationMs=Xe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function NI(t,e){let r=Date.now(),n=t.type;if(n==="system"){let o=String(t.subtype??"").trim();return o?[{ts:r,kind:"system",text:o}]:[]}if(n==="assistant"){let o=t.message,i=[];for(let s of o?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:kr(c,ew)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=OI(u,e);i.push({ts:r,kind:"tool",tool:c,...p?{file:p}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?kr(tw(s.content),ew):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(n==="result"){let o=String(t.subtype??"").trim(),i=typeof t.num_turns=="number"?t.num_turns:void 0,s=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...o?{text:o}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function OI(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}var Me,Pt,II,hu,ii,ew,br=E(()=>{"use strict";M();Zy();zs();Me=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}};Pt=class extends Error{usage;constructor(e){super("run aborted by pause"),this.usage=e,this.name="ClaudeAbortError"}},II=5e3;hu=new Map;ii=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return Jy(this.binary,e);if(e.signal?.aborted)throw new Pt;let r=["-p",CI(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",Vs(Jn(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());let n=null;e.effort&&e.effort.trim().length>0&&(await mu(this.binary)?(n=e.effort.trim(),r.push("--effort",n)):console.warn(`[claude] effort '${e.effort.trim()}' requested but this Claude Code does not support --effort \u2014 running at the default effort`));for(let y of e.addDirs??[])r.push("--add-dir",y);e.settings&&Object.keys(e.settings).length>0&&r.push("--settings",JSON.stringify(e.settings));let o=[],i=[],s=null,a={input:0,output:0,cacheRead:0,cacheCreate:0},c=0,l="",u=null,p=y=>{if(y){if(y.type==="result"){s=y;return}if(y.type==="rate_limit_event"){let b=jI(y.rate_limit_info);b&&(!u||b.utilization>u.utilization)&&(u=b);return}if(y.type==="assistant"){let b=y.message;typeof b?.model=="string"&&(l=b.model);let w=b?.usage;w&&(c+=1,a.input+=Xe(w.input_tokens),a.output+=Xe(w.output_tokens),a.cacheRead+=Xe(w.cache_read_input_tokens),a.cacheCreate+=Xe(w.cache_creation_input_tokens))}}},d=e.role,f=e.onActivity,m=y=>{if(f)for(let b of NI(y,e.workspaceDir))try{f(b)}catch{}};return f?.({ts:Date.now(),kind:"start",text:`${d} job started`}),console.log(`[claude] spawn ${this.binary} role=${d}`+(e.model?` model=${e.model}`:"")+(n?` effort=${n}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((y,b)=>{let w=EI(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"}});w.stdout.setEncoding("utf-8"),w.stderr.setEncoding("utf-8");let k=!1,x=null,h=()=>{k=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${d}`),w.kill("SIGTERM"),x=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),w.kill("SIGKILL")},II)};e.signal?.addEventListener("abort",h,{once:!0});let T=()=>{x&&clearTimeout(x),e.signal?.removeEventListener("abort",h)},R="";w.stdout.on("data",v=>{o.push(v),R+=v;let _;for(;(_=R.indexOf(`
811
- `))!==-1;){let N=R.slice(0,_).trim();if(R=R.slice(_+1),N){let G=Qy(N);p(G),G&&m(G)}}}),w.stderr.on("data",v=>{o.push(v),i.push(v);for(let _ of v.split(`
812
- `)){let N=_.trim();N&&console.warn(`[claude:stderr] ${N}`)}}),w.on("error",v=>{T(),b(v)}),w.on("close",v=>{if(T(),k){b(new Pt(gu(s,a,c,l)));return}if(R.trim()){let N=Qy(R.trim());p(N),N&&m(N)}let _=s?.is_error===!0;if(v!==0||_){let N=typeof s?.api_error_status=="number"?s.api_error_status:void 0,G=typeof s?.subtype=="string"?s.subtype:void 0,W=typeof s?.result=="string"?s.result:void 0,C=TI(N,W,u,Date.now());b(new Me(PI(v,s,i.join("")),{code:v,apiErrorStatus:N,subtype:G,resultText:W,retryAfterMs:AI(s),...C?{rateLimited:C}:{},usage:gu(s,a,c,l)}));return}console.log("[claude] exit code=0"),y({artifactPaths:[],log:o.join(""),usage:gu(s,a,c,l),...u?{rateLimit:u}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&RI(n))}};ew=200});import{mkdirSync as LI,writeFileSync as Jr}from"node:fs";import{dirname as MI,join as Zr}from"node:path";function rw(t,e,r){let n=Zr(t,e);LI(MI(n),{recursive:!0}),Jr(n,r)}function DI(t,e,r){return`# ${t} \u2014 Estimate
824
+ `),500)),n.join(" \u2014 ")}function nC(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 vw(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function oC(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=${Er(r,80)}`}return""}function Er(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function et(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function iC(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=et(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:et(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 Tu(t,e,r,n){let o=ht(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=et(i.input_tokens),o.outputTokens=et(i.output_tokens),o.cacheReadInputTokens=et(i.cache_read_input_tokens),o.cacheCreationInputTokens=et(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=et(t?.total_cost_usd),o.numTurns=t&&et(t.num_turns)>0?et(t.num_turns):r,o.durationMs=et(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}function sC(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:Er(c,kw)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,p=aC(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?Er(vw(s.content),kw):"";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 aC(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 Fe,Ot,eC,Ru,pi,kw,Sr=E(()=>{"use strict";M();ww();ia();Fe=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}};Ot=class extends Error{usage;constructor(e){super("run aborted by pause"),this.usage=e,this.name="ClaudeAbortError"}},eC=5e3;Ru=new Map;pi=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return yw(this.binary,e);if(e.signal?.aborted)throw new Ot;let r=["-p",tC(e.prompt),"--output-format","stream-json","--verbose","--dangerously-skip-permissions","--append-system-prompt",oa(ro(e.metadata))];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());let n=null;e.effort&&e.effort.trim().length>0&&(await Eu(this.binary)?(n=e.effort.trim(),r.push("--effort",n)):console.warn(`[claude] effort '${e.effort.trim()}' requested but this Claude Code does not support --effort \u2014 running at the default effort`));for(let y of e.addDirs??[])r.push("--add-dir",y);e.settings&&Object.keys(e.settings).length>0&&r.push("--settings",JSON.stringify(e.settings));let o=[],i=[],s=null,a={input:0,output:0,cacheRead:0,cacheCreate:0},c=0,l="",u=null,p=y=>{if(y){if(y.type==="result"){s=y;return}if(y.type==="rate_limit_event"){let b=iC(y.rate_limit_info);b&&(!u||b.utilization>u.utilization)&&(u=b);return}if(y.type==="assistant"){let b=y.message;typeof b?.model=="string"&&(l=b.model);let w=b?.usage;w&&(c+=1,a.input+=et(w.input_tokens),a.output+=et(w.output_tokens),a.cacheRead+=et(w.cache_read_input_tokens),a.cacheCreate+=et(w.cache_creation_input_tokens))}}},d=e.role,f=e.onActivity,m=y=>{if(f)for(let b of sC(y,e.workspaceDir))try{f(b)}catch{}};return f?.({ts:Date.now(),kind:"start",text:`${d} job started`}),console.log(`[claude] spawn ${this.binary} role=${d}`+(e.model?` model=${e.model}`:"")+(n?` effort=${n}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((y,b)=>{let w=JI(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"}});w.stdout.setEncoding("utf-8"),w.stderr.setEncoding("utf-8");let k=!1,x=null,h=()=>{k=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${d}`),w.kill("SIGTERM"),x=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),w.kill("SIGKILL")},eC)};e.signal?.addEventListener("abort",h,{once:!0});let T=()=>{x&&clearTimeout(x),e.signal?.removeEventListener("abort",h)},R="";w.stdout.on("data",v=>{o.push(v),R+=v;let P;for(;(P=R.indexOf(`
825
+ `))!==-1;){let N=R.slice(0,P).trim();if(R=R.slice(P+1),N){let G=bw(N);p(G),G&&m(G)}}}),w.stderr.on("data",v=>{o.push(v),i.push(v);for(let P of v.split(`
826
+ `)){let N=P.trim();N&&console.warn(`[claude:stderr] ${N}`)}}),w.on("error",v=>{T(),b(v)}),w.on("close",v=>{if(T(),k){b(new Ot(Tu(s,a,c,l)));return}if(R.trim()){let N=bw(R.trim());p(N),N&&m(N)}let P=s?.is_error===!0;if(v!==0||P){let N=typeof s?.api_error_status=="number"?s.api_error_status:void 0,G=typeof s?.subtype=="string"?s.subtype:void 0,W=typeof s?.result=="string"?s.result:void 0,C=QI(N,W,u,Date.now());b(new Fe(rC(v,s,i.join("")),{code:v,apiErrorStatus:N,subtype:G,resultText:W,retryAfterMs:nC(s),...C?{rateLimited:C}:{},usage:Tu(s,a,c,l)}));return}console.log("[claude] exit code=0"),y({artifactPaths:[],log:o.join(""),usage:Tu(s,a,c,l),...u?{rateLimit:u}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&ZI(n))}};kw=200});import{mkdirSync as cC,writeFileSync as sn}from"node:fs";import{dirname as lC,join as an}from"node:path";function $w(t,e,r){let n=an(t,e);cC(lC(n),{recursive:!0}),sn(n,r)}function uC(t,e,r){return`# ${t} \u2014 Estimate
813
827
 
814
828
  **Title:** ${e}
815
829
 
@@ -830,7 +844,7 @@ production-grade estimates.)
830
844
  ${r.split(`
831
845
  `).slice(0,8).join(`
832
846
  `).trim()||"(empty)"}
833
- `}function UI(t,e,r,n){let o=n?`
847
+ `}function dC(t,e,r,n){let o=n?`
834
848
  ## Reviewer rework instruction
835
849
 
836
850
  > ${n.split(`
@@ -859,10 +873,10 @@ TBD (mock runner does not yet inspect project code).
859
873
  ${r.split(`
860
874
  `).slice(0,8).join(`
861
875
  `).trim()||"(empty)"}
862
- `}function BI(t){return`# ${t} \u2014 Open questions
876
+ `}function pC(t){return`# ${t} \u2014 Open questions
863
877
 
864
878
  (none \u2014 mock runner did not surface ambiguities.)
865
- `}function FI(t,e,r){let n=r?` (rework: ${r.split(`
879
+ `}function fC(t,e,r){let n=r?` (rework: ${r.split(`
866
880
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
867
881
  index 0000000..1111111 100644
868
882
  --- a/CHANGELOG.md
@@ -873,7 +887,7 @@ index 0000000..1111111 100644
873
887
  +- mock-runner placeholder change for slice 5 testing.
874
888
  +
875
889
  # Changelog
876
- `}function GI(t,e,r){return`# ${t} \u2014 Diff summary
890
+ `}function mC(t,e,r){return`# ${t} \u2014 Diff summary
877
891
 
878
892
  **Title:** ${e}
879
893
  ${r?`
@@ -884,175 +898,175 @@ ${r?`
884
898
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
885
899
 
886
900
  (Mock-runner output. Replace with claude-headless for production patches.)
887
- `}var si,yu=E(()=>{"use strict";M();br();si=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=DI(n,o,i);Jr(Zr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Jr(Zr(e.workspaceDir,"PLAN.md"),UI(n,o,i,a)),s.push("PLAN.md"),Jr(Zr(e.workspaceDir,"QUESTIONS.md"),BI(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;rw(e.workspaceDir,"changes/sample.patch",FI(n,o,a)),s.push("changes/sample.patch"),rw(e.workspaceDir,"SOLUTION.md",GI(n,o,a)),s.push("SOLUTION.md")}else e.role==="rework"&&(Jr(Zr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
888
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:ut()}}async runInteractive(e){let r=e.role==="config",n=e.onActivity,o=s=>{n?.({ts:Date.now(),kind:"text",author:"agent",text:s}),n?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};n?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),o(r?"Hi! Describe the configuration change you'd like to make.":"Hi! Describe the task you'd like to formulate.");let i=r?"Config from chat":"Draft from chat";for await(let s of e.interactive.inbox){if(e.signal?.aborted)throw new Pt;if(s.kind==="user")n?.({ts:Date.now(),kind:"text",author:"user",text:s.text}),s.text.trim()&&(i=s.text.trim().slice(0,80)),o(`Got it: **${s.text.trim()}**. Anything else to clarify?`);else break}if(r){let s={file:"project.yaml",section:["branch"],edits:[{file:"project.yaml",path:["branch","pattern"],value:"codepipe/<TASK_ID>"}],explanation:`Proposed by the interactive config chat (mock runner): ${i}`,diff:[{path:"branch",before:`branch:
901
+ `}var fi,Iu=E(()=>{"use strict";M();Sr();fi=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=uC(n,o,i);sn(an(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;sn(an(e.workspaceDir,"PLAN.md"),dC(n,o,i,a)),s.push("PLAN.md"),sn(an(e.workspaceDir,"QUESTIONS.md"),pC(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;$w(e.workspaceDir,"changes/sample.patch",fC(n,o,a)),s.push("changes/sample.patch"),$w(e.workspaceDir,"SOLUTION.md",mC(n,o,a)),s.push("SOLUTION.md")}else e.role==="rework"&&(sn(an(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
902
+ `),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.role==="config",n=e.onActivity,o=s=>{n?.({ts:Date.now(),kind:"text",author:"agent",text:s}),n?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};n?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),o(r?"Hi! Describe the configuration change you'd like to make.":"Hi! Describe the task you'd like to formulate.");let i=r?"Config from chat":"Draft from chat";for await(let s of e.interactive.inbox){if(e.signal?.aborted)throw new Ot;if(s.kind==="user")n?.({ts:Date.now(),kind:"text",author:"user",text:s.text}),s.text.trim()&&(i=s.text.trim().slice(0,80)),o(`Got it: **${s.text.trim()}**. Anything else to clarify?`);else break}if(r){let s={file:"project.yaml",section:["branch"],edits:[{file:"project.yaml",path:["branch","pattern"],value:"codepipe/<TASK_ID>"}],explanation:`Proposed by the interactive config chat (mock runner): ${i}`,diff:[{path:"branch",before:`branch:
889
903
  pattern: <TASK_ID>
890
904
  `,after:`branch:
891
905
  pattern: codepipe/<TASK_ID>
892
- `}]};return Jr(Zr(e.workspaceDir,"PROPOSAL.json"),JSON.stringify(s,null,2)),{artifactPaths:["PROPOSAL.json"],log:"mock config session finalized PROPOSAL.json",usage:ut()}}return Jr(Zr(e.workspaceDir,"DRAFT.md"),`${i}
906
+ `}]};return sn(an(e.workspaceDir,"PROPOSAL.json"),JSON.stringify(s,null,2)),{artifactPaths:["PROPOSAL.json"],log:"mock config session finalized PROPOSAL.json",usage:ht()}}return sn(an(e.workspaceDir,"DRAFT.md"),`${i}
893
907
 
894
908
  Produced by the interactive chat (mock runner).
895
- `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:ut()}}}});function nw(t){switch(t){case"mock":return new si;case"claude-headless":return new ii;default:return null}}function wu(t,e){let r=e&&e.trim().length>0?e.trim():tt;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var ow=E(()=>{"use strict";M();br();yu();br();yu()});import{execFile as KI}from"node:child_process";function iw(){let t=Vt();return{identity:Gi(t),login:t}}function sw(t="claude"){return new Promise(e=>{KI(t,["-p","ok","--model",HI,"--max-turns","1","--output-format","json","--dangerously-skip-permissions"],{timeout:WI,maxBuffer:4*1024*1024},(n,o)=>{let i=qI(o);if(i)return e(i);let s=n instanceof Error?n.message:String(n??"no output");e({state:"failed",detail:aw(s)})})})}function qI(t){let e=t.trim();if(!e)return null;let r;try{r=JSON.parse(e)}catch{return null}if(r.is_error!==!0)return{state:"ok"};let n=r.api_error_status,i=(typeof r.result=="string"?r.result:"")||(typeof n=="number"?`api_status=${n}`:"agent error");return{state:"failed",detail:aw(i)}}function aw(t){let e=t.replace(/\s+/g," ").trim();return e.length>200?`${e.slice(0,197)}\u2026`:e}var HI,WI,cw=E(()=>{"use strict";Oo();HI="claude-haiku-4-5-20251001",WI=6e4});var $u={};Ne($u,{addUsageInto:()=>Qr,backoffDelayMs:()=>pw,classifyLLMFailure:()=>dw,isAuthFailure:()=>ku,loadRetryPolicy:()=>bu,runAgentWithRetry:()=>vu});function bu(t=process.env){return{maxAttempts:Xs(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Xs(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Xs(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Xs(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function dw(t){if(t instanceof Me){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return VI.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&zI.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!1,reason:"api_status=429 (rate limit)",retryAfterMs:i}:YI.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:lw.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 lw.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function ku(t){if(t instanceof Me){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&uw.test(n)}let e=t instanceof Error?t.message:String(t);return uw.test(e)}function pw(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 vu(t,e,r){let n=r.sleep??(a=>new Promise(c=>setTimeout(c,a))),o=Date.now()+r.policy.totalBudgetMs,i="",s=[];for(let a=1;;a++)try{let c=await t.run(e);for(let l of s)Qr(c.usage,l);return c}catch(c){i=c instanceof Error?c.message:String(c);let l=dw(c),u=a>=r.policy.maxAttempts;if(!l.retryable||u||r.aborted()){if(c instanceof Me){if(c.details.usage)for(let d of s)Qr(c.details.usage,d);throw a>1&&(c.message=`agent failed after ${a} attempts: ${i}`),c}throw a>1?new Error(`agent failed after ${a} attempts: ${i}`):c}let p=pw(a,r.policy,l.retryAfterMs);if(Date.now()+p>o){if(c instanceof Me){if(c.details.usage)for(let d of s)Qr(c.details.usage,d);throw c.message=`agent failed after ${a} attempts (retry budget exhausted): ${i}`,c}throw new Error(`agent failed after ${a} attempts (retry budget exhausted): ${i}`)}c instanceof Me&&c.details.usage&&s.push(c.details.usage),console.warn(`[job] ${r.jobId} agent attempt ${a}/${r.policy.maxAttempts} failed (retryable: ${l.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await n(p)}}function Xs(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}function Qr(t,e){t.inputTokens+=e.inputTokens,t.outputTokens+=e.outputTokens,t.cacheReadInputTokens+=e.cacheReadInputTokens,t.cacheCreationInputTokens+=e.cacheCreationInputTokens,t.totalCostUsd+=e.totalCostUsd,t.numTurns+=e.numTurns}var YI,lw,VI,zI,uw,ai=E(()=>{"use strict";br();YI=new Set([500,502,503,529]),lw=/(\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,VI=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,zI=new Set(["error_max_turns"]);uw=/(not logged in|invalid api key|invalid x-api-key|authentication[ _]error|unauthorized|oauth token (?:expired|revoked|invalid)|token (?:expired|revoked)|please run .{0,20}login|run `?claude\b.{0,20}(?:login|setup-token))/i});import{mkdirSync as XI,writeFileSync as JI}from"node:fs";import{homedir as ZI}from"node:os";import{join as fw}from"node:path";function xu(t,e=process.env){let r=(e.CODEPIPE_DEBUG??"").trim().toLowerCase();return r?r==="1"||r==="true"||r==="all"?!0:r.split(",").map(n=>n.trim()).includes(t):!1}function Su(t,e,r,n){try{let o=fw(ZI(),".codepipe","debug",mw(t));XI(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=fw(o,`${i}-${mw(e)}-${r}.md`);return JI(s,n),s}catch{return null}}var mw,hw=E(()=>{"use strict";mw=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as QI,rmSync as eC,writeFileSync as gw}from"node:fs";import{tmpdir as tC}from"node:os";import{join as Eu}from"node:path";function Js(t){return`[url "https://${t}/"]
909
+ `),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:ht()}}}});function xw(t){switch(t){case"mock":return new fi;case"claude-headless":return new pi;default:return null}}function Cu(t,e){let r=e&&e.trim().length>0?e.trim():it;return t==="mock"?!0:t==="claude-headless"?r==="claude":!1}var Sw=E(()=>{"use strict";M();Sr();Iu();Sr();Iu()});import{execFile as hC}from"node:child_process";function Ew(){let t=Zt();return{identity:Ji(t),login:t}}function Rw(t="claude"){return new Promise(e=>{hC(t,["-p","ok","--model",gC,"--max-turns","1","--output-format","json","--dangerously-skip-permissions"],{timeout:yC,maxBuffer:4*1024*1024},(n,o)=>{let i=wC(o);if(i)return e(i);let s=n instanceof Error?n.message:String(n??"no output");e({state:"failed",detail:Tw(s)})})})}function wC(t){let e=t.trim();if(!e)return null;let r;try{r=JSON.parse(e)}catch{return null}if(r.is_error!==!0)return{state:"ok"};let n=r.api_error_status,i=(typeof r.result=="string"?r.result:"")||(typeof n=="number"?`api_status=${n}`:"agent error");return{state:"failed",detail:Tw(i)}}function Tw(t){let e=t.replace(/\s+/g," ").trim();return e.length>200?`${e.slice(0,197)}\u2026`:e}var gC,yC,Iw=E(()=>{"use strict";Fo();gC="claude-haiku-4-5-20251001",yC=6e4});var ju={};Me(ju,{addUsageInto:()=>cn,backoffDelayMs:()=>_w,classifyLLMFailure:()=>Aw,isAuthFailure:()=>Au,loadRetryPolicy:()=>Pu,runAgentWithRetry:()=>_u});function Pu(t=process.env){return{maxAttempts:sa(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:sa(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:sa(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:sa(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}function Aw(t){if(t instanceof Fe){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return kC.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&vC.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!1,reason:"api_status=429 (rate limit)",retryAfterMs:i}:bC.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Cw.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 Cw.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}function Au(t){if(t instanceof Fe){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&Pw.test(n)}let e=t instanceof Error?t.message:String(t);return Pw.test(e)}function _w(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 _u(t,e,r){let n=r.sleep??(a=>new Promise(c=>setTimeout(c,a))),o=Date.now()+r.policy.totalBudgetMs,i="",s=[];for(let a=1;;a++)try{let c=await t.run(e);for(let l of s)cn(c.usage,l);return c}catch(c){i=c instanceof Error?c.message:String(c);let l=Aw(c),u=a>=r.policy.maxAttempts;if(!l.retryable||u||r.aborted()){if(c instanceof Fe){if(c.details.usage)for(let d of s)cn(c.details.usage,d);throw a>1&&(c.message=`agent failed after ${a} attempts: ${i}`),c}throw a>1?new Error(`agent failed after ${a} attempts: ${i}`):c}let p=_w(a,r.policy,l.retryAfterMs);if(Date.now()+p>o){if(c instanceof Fe){if(c.details.usage)for(let d of s)cn(c.details.usage,d);throw c.message=`agent failed after ${a} attempts (retry budget exhausted): ${i}`,c}throw new Error(`agent failed after ${a} attempts (retry budget exhausted): ${i}`)}c instanceof Fe&&c.details.usage&&s.push(c.details.usage),console.warn(`[job] ${r.jobId} agent attempt ${a}/${r.policy.maxAttempts} failed (retryable: ${l.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await n(p)}}function sa(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}function cn(t,e){t.inputTokens+=e.inputTokens,t.outputTokens+=e.outputTokens,t.cacheReadInputTokens+=e.cacheReadInputTokens,t.cacheCreationInputTokens+=e.cacheCreationInputTokens,t.totalCostUsd+=e.totalCostUsd,t.numTurns+=e.numTurns}var bC,Cw,kC,vC,Pw,mi=E(()=>{"use strict";Sr();bC=new Set([500,502,503,529]),Cw=/(\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,kC=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,vC=new Set(["error_max_turns"]);Pw=/(not logged in|invalid api key|invalid x-api-key|authentication[ _]error|unauthorized|oauth token (?:expired|revoked|invalid)|token (?:expired|revoked)|please run .{0,20}login|run `?claude\b.{0,20}(?:login|setup-token))/i});import{mkdirSync as $C,writeFileSync as xC}from"node:fs";import{homedir as SC}from"node:os";import{join as jw}from"node:path";function Nu(t,e=process.env){let r=(e.CODEPIPE_DEBUG??"").trim().toLowerCase();return r?r==="1"||r==="true"||r==="all"?!0:r.split(",").map(n=>n.trim()).includes(t):!1}function Ou(t,e,r,n){try{let o=jw(SC(),".codepipe","debug",Nw(t));$C(o,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=jw(o,`${i}-${Nw(e)}-${r}.md`);return xC(s,n),s}catch{return null}}var Nw,Ow=E(()=>{"use strict";Nw=t=>t.replace(/[^A-Za-z0-9._-]/g,"_")});import{mkdtempSync as EC,rmSync as RC,writeFileSync as Lw}from"node:fs";import{tmpdir as TC}from"node:os";import{join as Lu}from"node:path";function aa(t){return`[url "https://${t}/"]
896
910
  insteadOf = git@${t}:
897
911
  insteadOf = ssh://git@${t}/
898
- `}function kw(t,e){if(t.length===0)return null;let r=QI(Eu(tC(),"devpipe-gitcreds-")),n=Eu(r,"credentials"),o=Eu(r,"gitconfig");return gw(n,t.join(`
912
+ `}function Bw(t,e){if(t.length===0)return null;let r=EC(Lu(TC(),"devpipe-gitcreds-")),n=Lu(r,"credentials"),o=Lu(r,"gitconfig");return Lw(n,t.join(`
899
913
  `)+`
900
- `,{mode:384}),gw(o,`[credential]
914
+ `,{mode:384}),Lw(o,`[credential]
901
915
  helper = store --file=${n}
902
- `+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{eC(r,{recursive:!0,force:!0})}catch{}}}}function Ru(t){let e=[],r=[];if(t.mirrorWrite?.token){let n=t.mirrorWrite.host;(!n||n==="github")&&(e.push(`https://x-access-token:${t.mirrorWrite.token}@github.com`),r.push(yw)),(!n||n==="gitlab")&&(e.push(`https://oauth2:${t.mirrorWrite.token}@gitlab.com`),r.push(bw)),(!n||n==="bitbucket")&&(e.push(`https://${qt}:${encodeURIComponent(t.mirrorWrite.token)}@bitbucket.org`),r.push(ww))}return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(yw)),t.bitbucket?.apiToken&&(e.push(`https://${qt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(ww)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(bw)),kw(e,r)}function vw(t,e){if(t.contextWrite?.token){let r=Ur(e)??"github.com",n=jo(r);return kw([`https://${n}:${t.contextWrite.token}@${r}`],[Js(r)])}return Ru(t)}var yw,ww,bw,$w=E(()=>{"use strict";M();yw=Js("github.com"),ww=Js("bitbucket.org"),bw=Js("gitlab.com")});import{spawn as Sw}from"node:child_process";import{existsSync as Zs,mkdirSync as ci,readFileSync as rC,rmSync as Tu,symlinkSync as nC}from"node:fs";import{homedir as oC}from"node:os";import{dirname as Qn,join as vr}from"node:path";function Ew(t){let e=vr(oC(),".codepipe-sandbox","repos");return t?vr(e,t):e}function Rw(t,e){let n=(Zn.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Zn.get(t)===o&&Zn.delete(t)},()=>{Zn.get(t)===o&&Zn.delete(t)});return Zn.set(t,o),n}function xw(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 iC(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 Tw(t,e,r,n,o){let i=async c=>{await oe(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await oe(t,["reset","--hard",`origin/${c}`],o),await oe(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!xw(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{Zs(t)&&Tu(t,{recursive:!0,force:!0}),ci(Qn(t),{recursive:!0});try{return await oe(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!xw(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Zs(t)&&Tu(t,{recursive:!0,force:!0}),ci(Qn(t),{recursive:!0}),await oe(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(Zs(vr(t,".git")))try{return await s()}catch(c){if(!iC(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 Iw(t){await oe(t.workspacePath,["reset","--hard",t.baseSha]),await oe(t.workspacePath,["clean","-fdx"])}async function Cw(t,e){let r=t.workspacePath;await oe(r,["add","-A"]);let n=(await Se(r,["write-tree"])).trim(),o=(await Se(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:eo,GIT_AUTHOR_EMAIL:to,GIT_COMMITTER_NAME:eo,GIT_COMMITTER_EMAIL:to};return(await Se(r,["commit-tree",n,"-m",e],i)).trim()}async function Pw(t,e,r,n,o){try{await oe(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Ur(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 Aw(t,e){return Se(t.workspacePath,["diff","--binary",t.baseSha,e])}async function _w(t,e){return(await Se(t.workspacePath,["diff","--name-only",t.baseSha,e])).split(`
903
- `).map(n=>n.trim()).filter(n=>n.length>0)}async function jw(t,e,r,n,o){await oe(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await oe(t.workspacePath,["checkout","--force",r])}async function Nw(t,e,r,n,o,i){let s=t.workspacePath;await oe(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await Se(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=m=>Se(s,["rev-parse","-q","--verify",`${m}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Se(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await oe(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(y=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(y)}`)}),await c(n)||await oe(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:eo,GIT_AUTHOR_EMAIL:to,GIT_COMMITTER_NAME:eo,GIT_COMMITTER_EMAIL:to},u=(await Se(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Se(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await oe(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await oe(s,["cherry-pick","--no-commit",p],l)}catch(m){d=m instanceof Error?m.message:String(m)}let f=(await Se(s,["diff","--name-only","--diff-filter=U"])).split(`
904
- `).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await oe(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return f}async function Iu(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:eo,GIT_AUTHOR_EMAIL:to,GIT_COMMITTER_NAME:eo,GIT_COMMITTER_EMAIL:to};(await Se(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await oe(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await oe(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await oe(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Se(n,["diff","--name-only","--diff-filter=U"])).split(`
905
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await Se(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}async function Lw(t,e){return Se(t.workspacePath,["diff","--unified=0",`${Ow}..HEAD`],e)}async function Cu(t,e,r){await oe(t.workspacePath,["update-ref",Ow,e],r)}async function Mw(t,e,r){let n=t.workspacePath,o=[`+refs/heads/${e}:refs/remotes/origin/${e}`,...t.ref!==e?[`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`]:[]];await oe(n,["fetch","--depth=1","origin",...o],r).catch(a=>{console.warn(`[git] review-base ${t.name}: base fetch failed: ${String(a)}`)});let i=()=>Se(n,["merge-base",`origin/${e}`,"HEAD"],r).then(a=>a.trim()||null).catch(()=>null),s=await i();for(let a of[64,256,1024]){if(s)break;await oe(n,["fetch",`--deepen=${a}`,"origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --deepen=${a} failed: ${String(c)}`)}),s=await i()}return s||(await Se(n,["rev-parse","--is-shallow-repository"],r)).trim()==="true"&&(await oe(n,["fetch","--unshallow","origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --unshallow failed: ${String(c)}`)}),s=await i()),s&&await Cu(t,s,r),s}function oe(t,e,r){return new Promise((n,o)=>{let i=Sw("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}):
906
- ${s.join("").trim()||"(no stderr)"}`))})})}function Se(t,e,r){return new Promise((n,o)=>{let i=Sw("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}):
907
- ${a.join("").trim()||"(no stderr)"}`))})})}function Dw(t,e){Zs(t)&&Tu(t,{recursive:!0,force:!0}),ci(Qn(t),{recursive:!0}),nC(e,t,"dir")}async function Uw(t,e,r){await oe(t,["worktree","prune"]).catch(()=>{}),ci(Qn(r),{recursive:!0}),await oe(t,["worktree","add","--detach",r,`origin/${e}`])}async function sC(t,e,r){ci(Qn(r),{recursive:!0}),await oe(Qn(r),["clone","--quiet","--no-checkout",t,r]),await oe(r,["checkout","--force","--detach",e])}async function Bw(t,e,r,n="worktree",o,i){return r.length===0?[]:Rw(e,async()=>{let s=[];for(let a of r){let c=vr(Ew(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await Tw(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 Se(c,["rev-parse","HEAD"])).trim(),p=vr(t,"code",a.name);n==="direct"?(Dw(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await sC(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await Uw(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 Fw(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return Rw(e,async()=>{let a=vr(Ew(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await Tw(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=vr(t,"context");n==="direct"?(Dw(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await Uw(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Se(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function Gw(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await oe(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Se(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
908
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=rC(vr(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var Zn,eo,to,Ow,Kw=E(()=>{"use strict";M();Zn=new Map;eo="CodePipe Agent",to="codepipe@codepartner.ee";Ow="refs/worktree/codepipe/review-base"});import{existsSync as aC,readFileSync as cC}from"node:fs";import{join as lC}from"node:path";import{parse as uC}from"yaml";function Hw(t){if(!t)return!1;let e=lC(t,Pu);if(!aC(e))return!1;try{let r=uC(cC(e,"utf-8"));if(!r||typeof r!="object")return!1;let n=r.steps;return!Array.isArray(n)||n.length===0?!1:n.some(o=>o!=null&&typeof o=="object"&&typeof o.run=="string"&&o.run.trim().length>0)}catch{return!1}}var Pu,Ww=E(()=>{"use strict";Pu="knowledge/build.yaml"});import{readFileSync as dC}from"node:fs";import{join as pC}from"node:path";function qw(t){let e=pC(t,li),r;try{r=dC(e,"utf-8")}catch{throw new $r(`BUILD produced no ${li} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new $r(`${li} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new $r(`${li} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new $r(`${li}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,f=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||f===null)return[];let m={name:d,exitCode:f};return typeof p.durationMs=="number"&&(m.durationMs=p.durationMs),[m]}),c=typeof o.logTail=="string"?fC(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 fC(t){let e=Buffer.from(t,"utf-8");return e.length<=Au?t:`\u2026 [${e.length-Au} bytes elided] \u2026
909
- `+e.subarray(e.length-Au).toString("utf-8")}var Au,$r,li,Yw=E(()=>{"use strict";Au=8*1024,$r=class extends Error{},li="meta/build-result.json"});var Vw={};Ne(Vw,{REVIEW_RESULT_PATH:()=>en,ReviewVerdictError:()=>Dt,markFindingScope:()=>vC,parseChangedRanges:()=>kC,readCodeReviewResult:()=>_u});import{readFileSync as mC}from"node:fs";import{join as hC}from"node:path";function _u(t){let e=hC(t,en),r;try{r=mC(e,"utf-8")}catch{throw new Dt(`code review produced no ${en} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(l){throw new Dt(`${en} is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!n||typeof n!="object")throw new Dt(`${en} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Dt(`${en}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?xr(o.remarks,gC):"";if(!i&&s.trim().length===0)throw new Dt(`${en}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?xr(o.summary,yC):"",c=bC(o.findings);return{approved:i,remarks:s,summary:a,...c.length>0?{findings:c}:{}}}function bC(t){if(!Array.isArray(t))return[];let e=[];for(let r of t.slice(0,wC)){if(!r||typeof r!="object")continue;let n=r,o=typeof n.title=="string"?xr(n.title,512).trim():"",i=typeof n.problem=="string"?xr(n.problem,Qs).trim():"";if(!o||!i)continue;let s=typeof n.line=="number"&&Number.isInteger(n.line)&&n.line>0?n.line:void 0,a=n.severity==="blocker"||n.severity==="major"||n.severity==="minor"?n.severity:"other",c=typeof n.scenario=="string"&&n.scenario.trim()?xr(n.scenario,Qs):void 0;a==="blocker"&&!c&&(console.warn(`[review] blocker "${o.slice(0,80)}" carries no scenario \u2014 demoted to major`),a="major"),e.push({severity:a,title:o,problem:i,...typeof n.repo=="string"&&n.repo?{repo:n.repo}:{},...typeof n.file=="string"&&n.file?{file:xr(n.file,1024)}:{},...s!==void 0?{line:s}:{},...c?{scenario:c}:{},...typeof n.suggestion=="string"&&n.suggestion.trim()?{suggestion:xr(n.suggestion,Qs)}:{},...n.confidence==="high"||n.confidence==="medium"||n.confidence==="low"?{confidence:n.confidence}:{},...n.rule_source==="adr"||n.rule_source==="convention"||n.rule_source==="build"||n.rule_source==="judgment"?{ruleSource:n.rule_source}:{},...typeof n.out_of_diff_reason=="string"&&n.out_of_diff_reason.trim()?{outOfDiffReason:xr(n.out_of_diff_reason,Qs)}:{}})}return e}function xr(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
910
- \u2026 [${r.length-e} bytes elided]`}function kC(t){let e=new Map,r=null;for(let n of t.split(`
911
- `)){if(n.startsWith("+++ ")){let o=n.slice(4).trim();r=o==="/dev/null"?null:o.replace(/^b\//,""),r&&!e.has(r)&&e.set(r,[]);continue}if(r&&n.startsWith("@@")){let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(n);if(!o)continue;let i=Number(o[1]),s=o[2]!==void 0?Number(o[2]):1,a=s===0?Math.max(1,i):i,c=s===0?Math.max(1,i):i+s-1;e.get(r).push([a,c])}}return e}function vC(t,e,r){for(let n of t.findings??[]){if(!n.file)continue;let o=n.repo??r;if(!o)continue;let i=e.get(o);if(!i)continue;let s=i.get(n.file);if(!s){n.scope="outside";continue}if(n.line===void 0||s.length===0){n.scope="diff";continue}let a=n.line;n.scope=s.some(([c,l])=>a>=c&&a<=l)?"diff":"file"}}var gC,yC,Dt,en,Qs,wC,ju=E(()=>{"use strict";gC=16*1024,yC=4*1024,Dt=class extends Error{},en="meta/review-result.json";Qs=8*1024,wC=50});import{readFileSync as $C,statSync as xC}from"node:fs";import{join as zw}from"node:path";function PC(t){return t.startsWith("meta/")||CC.has(t)}function AC(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 _C(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function Xw(t,e,r){let n=r?.maxBytes??SC,o=r?.totalBytes??EC,i=r?.maxCount??RC,s=e.map((m,y)=>{let b=null;try{b=xC(zw(t,m)).size}catch{}return{path:m,index:y,size:b}}),a=[...s].sort((m,y)=>{let b=w=>PC(w.path)?0:1;return b(m)!==b(y)?b(m)-b(y):(m.size??0)-(y.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((m,y)=>m.index-y.index).map(m=>m.path),u=new Array(s.length),p=[],d=0;for(let m of c){let y=null;if(m.size!==null&&m.size<=n&&d+m.size<=o)try{y=$C(zw(t,m.path))}catch{}if(y!==null){d+=y.length,u[m.index]={path:m.path,contentBase64:y.toString("base64")};continue}let b=m.size===null?_C(m.path):AC(m.path,m.size,n,o),w=Buffer.from(b,"utf-8");d+=w.length,u[m.index]={path:m.path,contentBase64:w.toString("base64")},p.push({path:m.path,bytes:m.size??0})}let f=u.filter(m=>m!==void 0);if(l.length>0){let m=l.slice(0,IC),y=`# Artifacts omitted from upload
916
+ `+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{RC(r,{recursive:!0,force:!0})}catch{}}}}function Mu(t){let e=[],r=[];if(t.mirrorWrite?.token){let n=t.mirrorWrite.host;(!n||n==="github")&&(e.push(`https://x-access-token:${t.mirrorWrite.token}@github.com`),r.push(Mw)),(!n||n==="gitlab")&&(e.push(`https://oauth2:${t.mirrorWrite.token}@gitlab.com`),r.push(Uw)),(!n||n==="bitbucket")&&(e.push(`https://${Xt}:${encodeURIComponent(t.mirrorWrite.token)}@bitbucket.org`),r.push(Dw))}return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Mw)),t.bitbucket?.apiToken&&(e.push(`https://${Xt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Dw)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Uw)),Bw(e,r)}function Fw(t,e){if(t.contextWrite?.token){let r=Wr(e)??"github.com",n=Uo(r);return Bw([`https://${n}:${t.contextWrite.token}@${r}`],[aa(r)])}return Mu(t)}var Mw,Dw,Uw,Gw=E(()=>{"use strict";M();Mw=aa("github.com"),Dw=aa("bitbucket.org"),Uw=aa("gitlab.com")});import{spawn as Hw}from"node:child_process";import{existsSync as ca,mkdirSync as hi,readFileSync as IC,rmSync as Du,symlinkSync as CC}from"node:fs";import{homedir as PC}from"node:os";import{dirname as oo,join as Rr}from"node:path";function Ww(t){let e=Rr(PC(),".codepipe-sandbox","repos");return t?Rr(e,t):e}function qw(t,e){let n=(no.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{no.get(t)===o&&no.delete(t)},()=>{no.get(t)===o&&no.delete(t)});return no.set(t,o),n}function Kw(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 AC(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 Yw(t,e,r,n,o){let i=async c=>{await oe(t,["fetch","--depth=1","origin",`+refs/heads/${c}:refs/remotes/origin/${c}`],o),await oe(t,["reset","--hard",`origin/${c}`],o),await oe(t,["clean","-fdx"],o)},s=async()=>{try{return await i(r),r}catch(c){if(!n||n===r||!Kw(c))throw c;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}},a=async()=>{ca(t)&&Du(t,{recursive:!0,force:!0}),hi(oo(t),{recursive:!0});try{return await oe(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(c){if(!n||n===r||!Kw(c))throw c;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),ca(t)&&Du(t,{recursive:!0,force:!0}),hi(oo(t),{recursive:!0}),await oe(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}};if(ca(Rr(t,".git")))try{return await s()}catch(c){if(!AC(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 Vw(t){await oe(t.workspacePath,["reset","--hard",t.baseSha]),await oe(t.workspacePath,["clean","-fdx"])}async function zw(t,e){let r=t.workspacePath;await oe(r,["add","-A"]);let n=(await Se(r,["write-tree"])).trim(),o=(await Se(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:io,GIT_AUTHOR_EMAIL:so,GIT_COMMITTER_NAME:io,GIT_COMMITTER_EMAIL:so};return(await Se(r,["commit-tree",n,"-m",e],i)).trim()}async function Xw(t,e,r,n,o){try{await oe(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Wr(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 Jw(t,e){return Se(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Zw(t,e){return(await Se(t.workspacePath,["diff","--name-only",t.baseSha,e])).split(`
917
+ `).map(n=>n.trim()).filter(n=>n.length>0)}async function Qw(t,e,r,n,o){await oe(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await oe(t.workspacePath,["checkout","--force",r])}async function eb(t,e,r,n,o,i){let s=t.workspacePath;await oe(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await Se(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=m=>Se(s,["rev-parse","-q","--verify",`${m}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await Se(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await oe(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(y=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(y)}`)}),await c(n)||await oe(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:io,GIT_AUTHOR_EMAIL:so,GIT_COMMITTER_NAME:io,GIT_COMMITTER_EMAIL:so},u=(await Se(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),p=(await Se(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await oe(s,["cherry-pick","--quit"],l).catch(()=>{});let d=null;try{await oe(s,["cherry-pick","--no-commit",p],l)}catch(m){d=m instanceof Error?m.message:String(m)}let f=(await Se(s,["diff","--name-only","--diff-filter=U"])).split(`
918
+ `).map(m=>m.trim()).filter(m=>m.length>0);if(d&&f.length===0)throw await oe(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${d}`);return f}async function Uu(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:io,GIT_AUTHOR_EMAIL:so,GIT_COMMITTER_NAME:io,GIT_COMMITTER_EMAIL:so};(await Se(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await oe(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await oe(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await oe(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await Se(n,["diff","--name-only","--diff-filter=U"])).split(`
919
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await Se(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}async function rb(t,e){return Se(t.workspacePath,["diff","--unified=0",`${tb}..HEAD`],e)}async function Bu(t,e,r){await oe(t.workspacePath,["update-ref",tb,e],r)}async function nb(t,e,r){let n=t.workspacePath,o=[`+refs/heads/${e}:refs/remotes/origin/${e}`,...t.ref!==e?[`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`]:[]];await oe(n,["fetch","--depth=1","origin",...o],r).catch(a=>{console.warn(`[git] review-base ${t.name}: base fetch failed: ${String(a)}`)});let i=()=>Se(n,["merge-base",`origin/${e}`,"HEAD"],r).then(a=>a.trim()||null).catch(()=>null),s=await i();for(let a of[64,256,1024]){if(s)break;await oe(n,["fetch",`--deepen=${a}`,"origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --deepen=${a} failed: ${String(c)}`)}),s=await i()}return s||(await Se(n,["rev-parse","--is-shallow-repository"],r)).trim()==="true"&&(await oe(n,["fetch","--unshallow","origin",...o],r).catch(c=>{console.warn(`[git] review-base ${t.name}: --unshallow failed: ${String(c)}`)}),s=await i()),s&&await Bu(t,s,r),s}function oe(t,e,r){return new Promise((n,o)=>{let i=Hw("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}):
920
+ ${s.join("").trim()||"(no stderr)"}`))})})}function Se(t,e,r){return new Promise((n,o)=>{let i=Hw("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}):
921
+ ${a.join("").trim()||"(no stderr)"}`))})})}function ob(t,e){ca(t)&&Du(t,{recursive:!0,force:!0}),hi(oo(t),{recursive:!0}),CC(e,t,"dir")}async function ib(t,e,r){await oe(t,["worktree","prune"]).catch(()=>{}),hi(oo(r),{recursive:!0}),await oe(t,["worktree","add","--detach",r,`origin/${e}`])}async function _C(t,e,r){hi(oo(r),{recursive:!0}),await oe(oo(r),["clone","--quiet","--no-checkout",t,r]),await oe(r,["checkout","--force","--detach",e])}async function sb(t,e,r,n="worktree",o,i){return r.length===0?[]:qw(e,async()=>{let s=[];for(let a of r){let c=Rr(Ww(i),e,a.name);console.log(`[git] code: ensure ${a.cloneUrl} @ ${a.ref} \u2192 ${c}`);let l;try{l=await Yw(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 Se(c,["rev-parse","HEAD"])).trim(),p=Rr(t,"code",a.name);n==="direct"?(ob(p,c),console.log(`[git] code: linked ${p} \u2192 ${c} @ ${u.slice(0,10)}`)):n==="clone"?(await _C(c,u,p),console.log(`[git] code: clone ${p} \u2190 ${c} @ ${u.slice(0,10)}`)):(await ib(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 ab(t,e,r,n="worktree",o,i){if(!r||!r.cloneUrl)return null;let s=r;return qw(e,async()=>{let a=Rr(Ww(i),e,"_context");console.log(`[git] context: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);try{await Yw(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=Rr(t,"context");n==="direct"?(ob(c,a),console.log(`[git] context: linked ${c} \u2192 ${a}`)):(await ib(a,s.ref,c),console.log(`[git] context: worktree ${c} \u2190 ${a}`));let l=(await Se(a,["rev-parse","HEAD"])).trim();return{workspacePath:c,cachePath:a,baseSha:l}})}async function cb(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await oe(r,["add","-A",...n]).catch(()=>{});let o;try{o=await Se(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
922
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=IC(Rr(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}var no,io,so,tb,lb=E(()=>{"use strict";M();no=new Map;io="CodePipe Agent",so="codepipe@codepartner.ee";tb="refs/worktree/codepipe/review-base"});import{existsSync as jC,readFileSync as NC}from"node:fs";import{join as OC}from"node:path";import{parse as LC}from"yaml";function ub(t){if(!t)return!1;let e=OC(t,Fu);if(!jC(e))return!1;try{let r=LC(NC(e,"utf-8"));if(!r||typeof r!="object")return!1;let n=r.steps;return!Array.isArray(n)||n.length===0?!1:n.some(o=>o!=null&&typeof o=="object"&&typeof o.run=="string"&&o.run.trim().length>0)}catch{return!1}}var Fu,db=E(()=>{"use strict";Fu="knowledge/build.yaml"});import{readFileSync as MC}from"node:fs";import{join as DC}from"node:path";function pb(t){let e=DC(t,gi),r;try{r=MC(e,"utf-8")}catch{throw new Tr(`BUILD produced no ${gi} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Tr(`${gi} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Tr(`${gi} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Tr(`${gi}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let p=u,d=typeof p.name=="string"?p.name:null,f=typeof p.exitCode=="number"?p.exitCode:null;if(d===null||f===null)return[];let m={name:d,exitCode:f};return typeof p.durationMs=="number"&&(m.durationMs=p.durationMs),[m]}),c=typeof o.logTail=="string"?UC(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 UC(t){let e=Buffer.from(t,"utf-8");return e.length<=Gu?t:`\u2026 [${e.length-Gu} bytes elided] \u2026
923
+ `+e.subarray(e.length-Gu).toString("utf-8")}var Gu,Tr,gi,fb=E(()=>{"use strict";Gu=8*1024,Tr=class extends Error{},gi="meta/build-result.json"});var mb={};Me(mb,{REVIEW_RESULT_PATH:()=>ln,ReviewVerdictError:()=>Gt,markFindingScope:()=>YC,parseChangedRanges:()=>qC,readCodeReviewResult:()=>Ku});import{readFileSync as BC}from"node:fs";import{join as FC}from"node:path";function Ku(t){let e=FC(t,ln),r;try{r=BC(e,"utf-8")}catch{throw new Gt(`code review produced no ${ln} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(l){throw new Gt(`${ln} is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(!n||typeof n!="object")throw new Gt(`${ln} must be a JSON object`);let o=n;if(typeof o.approved!="boolean")throw new Gt(`${ln}: "approved" must be a boolean`);let i=o.approved,s=typeof o.remarks=="string"?Ir(o.remarks,GC):"";if(!i&&s.trim().length===0)throw new Gt(`${ln}: "approved" is false but "remarks" is empty \u2014 nothing to rework on`);let a=typeof o.summary=="string"?Ir(o.summary,KC):"",c=WC(o.findings);return{approved:i,remarks:s,summary:a,...c.length>0?{findings:c}:{}}}function WC(t){if(!Array.isArray(t))return[];let e=[];for(let r of t.slice(0,HC)){if(!r||typeof r!="object")continue;let n=r,o=typeof n.title=="string"?Ir(n.title,512).trim():"",i=typeof n.problem=="string"?Ir(n.problem,la).trim():"";if(!o||!i)continue;let s=typeof n.line=="number"&&Number.isInteger(n.line)&&n.line>0?n.line:void 0,a=n.severity==="blocker"||n.severity==="major"||n.severity==="minor"?n.severity:"other",c=typeof n.scenario=="string"&&n.scenario.trim()?Ir(n.scenario,la):void 0;a==="blocker"&&!c&&(console.warn(`[review] blocker "${o.slice(0,80)}" carries no scenario \u2014 demoted to major`),a="major"),e.push({severity:a,title:o,problem:i,...typeof n.repo=="string"&&n.repo?{repo:n.repo}:{},...typeof n.file=="string"&&n.file?{file:Ir(n.file,1024)}:{},...s!==void 0?{line:s}:{},...c?{scenario:c}:{},...typeof n.suggestion=="string"&&n.suggestion.trim()?{suggestion:Ir(n.suggestion,la)}:{},...n.confidence==="high"||n.confidence==="medium"||n.confidence==="low"?{confidence:n.confidence}:{},...n.rule_source==="adr"||n.rule_source==="convention"||n.rule_source==="build"||n.rule_source==="judgment"?{ruleSource:n.rule_source}:{},...typeof n.out_of_diff_reason=="string"&&n.out_of_diff_reason.trim()?{outOfDiffReason:Ir(n.out_of_diff_reason,la)}:{}})}return e}function Ir(t,e){let r=Buffer.from(t,"utf-8");return r.length<=e?t:r.subarray(0,e).toString("utf-8")+`
924
+ \u2026 [${r.length-e} bytes elided]`}function qC(t){let e=new Map,r=null;for(let n of t.split(`
925
+ `)){if(n.startsWith("+++ ")){let o=n.slice(4).trim();r=o==="/dev/null"?null:o.replace(/^b\//,""),r&&!e.has(r)&&e.set(r,[]);continue}if(r&&n.startsWith("@@")){let o=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(n);if(!o)continue;let i=Number(o[1]),s=o[2]!==void 0?Number(o[2]):1,a=s===0?Math.max(1,i):i,c=s===0?Math.max(1,i):i+s-1;e.get(r).push([a,c])}}return e}function YC(t,e,r){for(let n of t.findings??[]){if(!n.file)continue;let o=n.repo??r;if(!o)continue;let i=e.get(o);if(!i)continue;let s=i.get(n.file);if(!s){n.scope="outside";continue}if(n.line===void 0||s.length===0){n.scope="diff";continue}let a=n.line;n.scope=s.some(([c,l])=>a>=c&&a<=l)?"diff":"file"}}var GC,KC,Gt,ln,la,HC,Hu=E(()=>{"use strict";GC=16*1024,KC=4*1024,Gt=class extends Error{},ln="meta/review-result.json";la=8*1024,HC=50});import{readFileSync as VC,statSync as zC}from"node:fs";import{join as hb}from"node:path";function rP(t){return t.startsWith("meta/")||tP.has(t)}function nP(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 oP(t){return`[codepipe] artifact unreadable at upload time: ${t} could not be read from the workspace \u2014 content omitted.`}function gb(t,e,r){let n=r?.maxBytes??XC,o=r?.totalBytes??JC,i=r?.maxCount??ZC,s=e.map((m,y)=>{let b=null;try{b=zC(hb(t,m)).size}catch{}return{path:m,index:y,size:b}}),a=[...s].sort((m,y)=>{let b=w=>rP(w.path)?0:1;return b(m)!==b(y)?b(m)-b(y):(m.size??0)-(y.size??0)}),c=a.slice(0,i),l=a.slice(i).sort((m,y)=>m.index-y.index).map(m=>m.path),u=new Array(s.length),p=[],d=0;for(let m of c){let y=null;if(m.size!==null&&m.size<=n&&d+m.size<=o)try{y=VC(hb(t,m.path))}catch{}if(y!==null){d+=y.length,u[m.index]={path:m.path,contentBase64:y.toString("base64")};continue}let b=m.size===null?oP(m.path):nP(m.path,m.size,n,o),w=Buffer.from(b,"utf-8");d+=w.length,u[m.index]={path:m.path,contentBase64:w.toString("base64")},p.push({path:m.path,bytes:m.size??0})}let f=u.filter(m=>m!==void 0);if(l.length>0){let m=l.slice(0,eP),y=`# Artifacts omitted from upload
912
926
 
913
927
  ${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.
914
928
 
915
929
  `+m.map(b=>`- ${b}
916
930
  `).join("")+(l.length>m.length?`
917
931
  \u2026and ${l.length-m.length} more.
918
- `:"");f.push({path:TC,contentBase64:Buffer.from(y,"utf-8").toString("base64")})}return{artifacts:f,omitted:p,dropped:l}}var SC,EC,RC,TC,IC,CC,Jw=E(()=>{"use strict";SC=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),EC=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),RC=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),TC="artifacts-omitted.md",IC=500,CC=new Set(["QUESTIONS.md","PLAN.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","SOLUTION.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as jC,mkdtempSync as NC,readFileSync as OC,readdirSync as Qw,rmSync as Zw}from"node:fs";import{tmpdir as LC}from"node:os";import{join as ea,relative as MC}from"node:path";function eb(t){let e=NC(ea(LC(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Zw(e,{recursive:!0,force:!0}),listFiles:()=>tb(e,e),readFile:r=>OC(ea(e,r),"utf-8"),clean:()=>{for(let r of Qw(e))UC.has(r)||Zw(ea(e,r),{recursive:!0,force:!0})}}}function tb(t,e){let r=[];for(let n of Qw(e)){let o=ea(e,n),i=jC(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&DC.has(n))continue;r.push(...tb(t,o))}else r.push(MC(t,o))}return r}var DC,UC,rb=E(()=>{"use strict";DC=new Set(["code","context","scratch",".claude"]),UC=new Set(["code","context"])});import{readFileSync as BC}from"node:fs";import{join as FC}from"node:path";function qC(t,e){let r=_o(t);return r?ob(YC(r),e):""}function nb(t,e,r={}){let n=r.perAncestorBudget??GC,o=r.totalBudget??KC,i=[...t.matchAll(Li)];if(i.length===0)return t;let s=i.map(l=>{let u=l[1],p=VC(e,u),d=p!=null?qC(p,n):"";return{key:u,text:d||`(\u0442\u0435\u043B\u043E \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u2014 \u0441\u043C. tasks/${u}/task.md)`}}),a=o,c=new Map;for(let l of s){let u=Math.max(0,Math.min(l.text.length,a));c.set(l.key,ob(l.text,u)),a-=u}return t.replace(Li,(l,u)=>c.get(u)??"")}function YC(t){let e=t.split(`
919
- `),r=e.findIndex(a=>WC.test(a));if(r<0)return t;let n=e.slice(0,r).join(`
932
+ `:"");f.push({path:QC,contentBase64:Buffer.from(y,"utf-8").toString("base64")})}return{artifacts:f,omitted:p,dropped:l}}var XC,JC,ZC,QC,eP,tP,yb=E(()=>{"use strict";XC=Number(process.env.SANDBOX_MAX_ARTIFACT_BYTES??4*1024*1024),JC=Number(process.env.SANDBOX_MAX_ARTIFACT_TOTAL_BYTES??16*1024*1024),ZC=Number(process.env.SANDBOX_MAX_ARTIFACT_COUNT??200),QC="artifacts-omitted.md",eP=500,tP=new Set(["QUESTIONS.md","PLAN.md","SOLUTION.md","DRAFT.md","ESTIMATE.md","SOLUTION.md","diff-summary.md","review-result.md","commit-message.txt","pr-description.md"])});import{lstatSync as iP,mkdtempSync as sP,readFileSync as aP,readdirSync as bb,rmSync as wb}from"node:fs";import{tmpdir as cP}from"node:os";import{join as ua,relative as lP}from"node:path";function kb(t){let e=sP(ua(cP(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>wb(e,{recursive:!0,force:!0}),listFiles:()=>vb(e,e),readFile:r=>aP(ua(e,r),"utf-8"),clean:()=>{for(let r of bb(e))dP.has(r)||wb(ua(e,r),{recursive:!0,force:!0})}}}function vb(t,e){let r=[];for(let n of bb(e)){let o=ua(e,n),i=iP(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&uP.has(n))continue;r.push(...vb(t,o))}else r.push(lP(t,o))}return r}var uP,dP,$b=E(()=>{"use strict";uP=new Set(["code","context","scratch",".claude"]),dP=new Set(["code","context"])});import{readFileSync as pP}from"node:fs";import{join as fP}from"node:path";function wP(t,e){let r=Do(t);return r?Sb(bP(r),e):""}function xb(t,e,r={}){let n=r.perAncestorBudget??mP,o=r.totalBudget??hP,i=[...t.matchAll(Wi)];if(i.length===0)return t;let s=i.map(l=>{let u=l[1],p=kP(e,u),d=p!=null?wP(p,n):"";return{key:u,text:d||`(\u0442\u0435\u043B\u043E \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u2014 \u0441\u043C. tasks/${u}/task.md)`}}),a=o,c=new Map;for(let l of s){let u=Math.max(0,Math.min(l.text.length,a));c.set(l.key,Sb(l.text,u)),a-=u}return t.replace(Wi,(l,u)=>c.get(u)??"")}function bP(t){let e=t.split(`
933
+ `),r=e.findIndex(a=>yP.test(a));if(r<0)return t;let n=e.slice(0,r).join(`
920
934
  `).trim(),o=(e[r]??"").match(/^#+/)?.[0].length??1,i=e.length;for(let a=r+1;a<e.length;a++){let c=(e[a]??"").match(/^(#{1,6})\s/);if(c&&(c[1]?.length??0)<=o){i=a;break}}let s=e.slice(r,i).join(`
921
935
  `).trim();return[n,s].filter(Boolean).join(`
922
936
 
923
- `)}function ob(t,e){return t.length<=e?t:t.slice(0,e).trimEnd()+HC}function VC(t,e){if(!t)return null;try{return BC(FC(t,"tasks",e,"task.md"),"utf-8")}catch{return null}}var GC,KC,HC,WC,ib=E(()=>{"use strict";M();GC=1200,KC=3e3,HC=`
937
+ `)}function Sb(t,e){return t.length<=e?t:t.slice(0,e).trimEnd()+gP}function kP(t,e){if(!t)return null;try{return pP(fP(t,"tasks",e,"task.md"),"utf-8")}catch{return null}}var mP,hP,gP,yP,Eb=E(()=>{"use strict";M();mP=1200,hP=3e3,gP=`
924
938
 
925
- \u2026(\u043E\u0431\u0440\u0435\u0437\u0430\u043D\u043E)`,WC=/^#{1,6}\s.*(приёмк|acceptance|критери)/i});import{existsSync as ra,readFileSync as sb,readdirSync as Nu}from"node:fs";import{join as Qt}from"node:path";import{parse as zC}from"yaml";function na(t){if(!ra(t))return[];let e=[];for(let r of Nu(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=Qt(t,r.name);r.isDirectory()?e.push(...na(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function ta(t){try{return zC(sb(t,"utf-8"))}catch{return null}}function ab(t){let e={nodes:new Map,adjacency:new Map,events:new Map,annotations:new Map,keyByEntity:new Map,orphanedEntities:new Set,empty:!0},r=(i,s,a,c)=>{e.adjacency.has(i)||e.adjacency.set(i,[]),e.adjacency.has(s)||e.adjacency.set(s,[]),e.adjacency.get(i).push({to:s,kind:a,weight:c}),e.adjacency.get(s).push({to:i,kind:a,weight:c})};for(let i of na(Qt(t,"model/derived/structure"))){let s=Gt(ta(i));if(s.ok){for(let a of s.value.nodes)e.nodes.set(a.key,a);for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}}for(let i of[...na(Qt(t,"model/derived/correlates")),Qt(t,"model/derived/relates.yaml")]){if(!ra(i))continue;let s=xo(ta(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=Qt(t,"model/facts/events");if(ra(n))for(let i of Nu(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Kt(ta(Qt(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=Re(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,Re(l),"references",1)}for(let i of na(Qt(t,"model/facts/identity"))){let s=So(ta(i));if(s.ok)for(let a of s.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=Qt(t,"model/facts/annotations");if(ra(o)){for(let i of Nu(o).sort())if(i.endsWith(".md"))try{let s=sb(Qt(o,i),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(s);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var cb=E(()=>{"use strict";M()});function ub(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function rP(t,e){if(t.size===0||e.size===0)return 0;let r=0;for(let n of t)e.has(n)&&r++;return r/(t.size+e.size-r)}function db(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(f,m)=>{(i.get(f)??0)<m&&i.set(f,m)};(o.events.has(e)||o.adjacency.has(Re(e)))&&s(Re(e),lb);for(let f of`${r}
926
- ${n}`.match(tP)??[]){if(f===e)continue;let m=Re(f);(o.events.has(f)||o.adjacency.has(m))&&s(m,lb)}let a=new Map;for(let f of o.nodes.keys()){let m=re(f);if(m?.level!=="code")continue;let y=m.path.slice(m.path.lastIndexOf("/")+1);for(let b of[m.path,y])a.has(b)||a.set(b,[]),a.get(b).push(f)}let c=`${r}
927
- ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let f of c){let m=f.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!m||!m.includes("/")&&!m.includes("."))continue;let y=a.get(m)??[];y.length===1&&s(y[0],XC)}let l=new Map,u=(f,m)=>{let y=f.toLowerCase();!y||y.length<4||l.set(y,l.has(y)&&l.get(y)!==m?null:m)};for(let f of o.nodes.keys()){let m=re(f);if(!m)continue;let y=m.path.slice(m.path.lastIndexOf("/")+1);m.level==="code"&&u(y.replace(/\.[a-z0-9]+$/i,""),f),m.level==="component"&&u(y,f)}for(let f of`${r}
928
- ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let m=l.get(f.toLowerCase());m&&s(m,JC)}let p=ub(`${r}
929
- ${n}`),d=[];for(let[f,m]of o.events){if(f===e||!m.title)continue;let y=rP(p,ub(m.title));y>=QC&&d.push({key:Re(f),score:y})}return d.sort((f,m)=>m.score-f.score||(f.key<m.key?-1:1)).slice(0,eP).forEach(f=>s(f.key,ZC)),i}var lb,XC,JC,ZC,QC,eP,tP,pb=E(()=>{"use strict";M();lb=1,XC=.9,JC=.7,ZC=.5,QC=.15,eP=3,tP=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function fb(t,e,r={}){let n=r.cutoff??Nr.activationCutoff,o=r.topK??Nr.topKPerNode,i=r.nodeCap??Nr.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=Ga[p.kind]??.3,f=l.activation*d*Math.min(p.weight,1);if(f<n)continue;let m=s.get(p.to);(!m||m.activation<f)&&(s.set(p.to,{activation:f,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:f}))}}return s}var mb=E(()=>{"use strict";M()});import{existsSync as Lu,readFileSync as hb,readdirSync as nP}from"node:fs";import{join as oa}from"node:path";function Ou(t){return Math.ceil(t.length/4)}function ro(t,e,r){let n=o=>o.via?.kind==="correlates"?r?.get(o.key)??1:1;return[...t.entries()].filter(([o])=>e(o)).map(([o,i])=>({key:o,activation:i.activation,via:i.via})).sort((o,i)=>i.activation*n(i)-o.activation*n(o)||(o.key<i.key?-1:1))}function At(t){let e=re(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function ui(t){if(!t.via)return"matched from the task text";let e=At(t.via.from);switch(t.via.kind){case"touched_by":return t.via.from.startsWith("task::")?`touched by ${e}`:`touches ${e}`;case"correlates":return`co-changes with ${e}`;case"relates":return`related to ${e} (shared files)`;case"references":return`referenced by ${e}`;case"contains":return`contained in ${e}`;default:return`linked to ${e}`}}function gb(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=oa(t,"adr");if(!Lu(n))return null;let o=r.padStart(4,"0");for(let i of nP(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:hb(oa(n,i),"utf-8").trim()}}catch{return null}return null}function yb(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??Nr.budgetTokens,a=[],c=0,l=R=>{let v=Ou(R);return c+v>s?!1:(a.push(R),c+=v,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
930
- `));let u=ro(i,R=>R.startsWith("adr::")),p=!1;for(let R of u){let v=gb(n,At(R.key));if(!v)continue;let _=`${p?"":`
939
+ \u2026(\u043E\u0431\u0440\u0435\u0437\u0430\u043D\u043E)`,yP=/^#{1,6}\s.*(приёмк|acceptance|критери)/i});import{existsSync as pa,readFileSync as Rb,readdirSync as Wu}from"node:fs";import{join as rr}from"node:path";import{parse as vP}from"yaml";function fa(t){if(!pa(t))return[];let e=[];for(let r of Wu(t,{withFileTypes:!0}).sort((n,o)=>n.name<o.name?-1:1)){let n=rr(t,r.name);r.isDirectory()?e.push(...fa(n)):r.name.endsWith(".yaml")&&e.push(n)}return e}function da(t){try{return vP(Rb(t,"utf-8"))}catch{return null}}function Tb(t){let e={nodes:new Map,adjacency:new Map,events:new Map,annotations:new Map,keyByEntity:new Map,orphanedEntities:new Set,empty:!0},r=(i,s,a,c)=>{e.adjacency.has(i)||e.adjacency.set(i,[]),e.adjacency.has(s)||e.adjacency.set(s,[]),e.adjacency.get(i).push({to:s,kind:a,weight:c}),e.adjacency.get(s).push({to:i,kind:a,weight:c})};for(let i of fa(rr(t,"model/derived/structure"))){let s=qt(da(i));if(s.ok){for(let a of s.value.nodes)e.nodes.set(a.key,a);for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}}for(let i of[...fa(rr(t,"model/derived/correlates")),rr(t,"model/derived/relates.yaml")]){if(!pa(i))continue;let s=Co(da(i));if(s.ok)for(let a of s.value.edges)r(a.from,a.to,a.kind,a.weight??1)}let n=rr(t,"model/facts/events");if(pa(n))for(let i of Wu(n).sort()){if(!i.endsWith(".yaml"))continue;let s=Yt(da(rr(n,i)));if(!s.ok)continue;let a=s.value;e.events.set(a.taskKey,a);let c=Re(a.taskKey);for(let l of a.files)r(c,l.key,"touched_by",1);for(let l of a.links?.adr??[])r(c,`adr::${l}`,"references",1);for(let l of a.links?.tasks??[])r(c,Re(l),"references",1)}for(let i of fa(rr(t,"model/facts/identity"))){let s=Po(da(i));if(s.ok)for(let a of s.value.entities)a.status==="orphaned"?e.orphanedEntities.add(a.entityId):e.keyByEntity.set(a.entityId,a.currentKey)}let o=rr(t,"model/facts/annotations");if(pa(o)){for(let i of Wu(o).sort())if(i.endsWith(".md"))try{let s=Rb(rr(o,i),"utf-8"),a=/^---\n[\s\S]*?entityId:\s*(e_[0-9a-f]{8})[\s\S]*?\n---\n?([\s\S]*)$/.exec(s);a&&e.annotations.set(a[1],a[2].trim())}catch{}}return e.empty=e.nodes.size===0&&e.events.size===0,e}var Ib=E(()=>{"use strict";M()});function Pb(t){return new Set((t.toLowerCase().match(/[a-zа-я0-9_]{4,}/g)??[]).filter(e=>!/^\d+$/.test(e)))}function IP(t,e){if(t.size===0||e.size===0)return 0;let r=0;for(let n of t)e.has(n)&&r++;return r/(t.size+e.size-r)}function Ab(t){let{taskKey:e,title:r,text:n,model:o}=t,i=new Map,s=(f,m)=>{(i.get(f)??0)<m&&i.set(f,m)};(o.events.has(e)||o.adjacency.has(Re(e)))&&s(Re(e),Cb);for(let f of`${r}
940
+ ${n}`.match(TP)??[]){if(f===e)continue;let m=Re(f);(o.events.has(f)||o.adjacency.has(m))&&s(m,Cb)}let a=new Map;for(let f of o.nodes.keys()){let m=re(f);if(m?.level!=="code")continue;let y=m.path.slice(m.path.lastIndexOf("/")+1);for(let b of[m.path,y])a.has(b)||a.set(b,[]),a.get(b).push(f)}let c=`${r}
941
+ ${n}`.split(/[\s,;()[\]{}<>"'!?]+/);for(let f of c){let m=f.replace(/^[`*_]+|[`*_.:]+$/g,"");if(!m||!m.includes("/")&&!m.includes("."))continue;let y=a.get(m)??[];y.length===1&&s(y[0],$P)}let l=new Map,u=(f,m)=>{let y=f.toLowerCase();!y||y.length<4||l.set(y,l.has(y)&&l.get(y)!==m?null:m)};for(let f of o.nodes.keys()){let m=re(f);if(!m)continue;let y=m.path.slice(m.path.lastIndexOf("/")+1);m.level==="code"&&u(y.replace(/\.[a-z0-9]+$/i,""),f),m.level==="component"&&u(y,f)}for(let f of`${r}
942
+ ${n}`.match(/[A-Za-z][A-Za-z0-9_-]{3,}/g)??[]){let m=l.get(f.toLowerCase());m&&s(m,xP)}let p=Pb(`${r}
943
+ ${n}`),d=[];for(let[f,m]of o.events){if(f===e||!m.title)continue;let y=IP(p,Pb(m.title));y>=EP&&d.push({key:Re(f),score:y})}return d.sort((f,m)=>m.score-f.score||(f.key<m.key?-1:1)).slice(0,RP).forEach(f=>s(f.key,SP)),i}var Cb,$P,xP,SP,EP,RP,TP,_b=E(()=>{"use strict";M();Cb=1,$P=.9,xP=.7,SP=.5,EP=.15,RP=3,TP=/\b[A-Z][A-Z0-9]{1,9}-\d+\b/g});function jb(t,e,r={}){let n=r.cutoff??Br.activationCutoff,o=r.topK??Br.topKPerNode,i=r.nodeCap??Br.nodeCap,s=new Map;for(let[l,u]of e)s.set(l,{activation:u});let a=[...e].map(([l,u])=>({key:l,activation:u})).sort((l,u)=>u.activation-l.activation||(l.key<u.key?-1:1)),c=new Set;for(;a.length>0;){a.sort((p,d)=>d.activation-p.activation||(p.key<d.key?-1:1));let l=a.shift();if(c.has(l.key)||(s.get(l.key)?.activation??0)>l.activation)continue;if(c.add(l.key),c.size>i)break;let u=[...t.adjacency.get(l.key)??[]].sort((p,d)=>d.weight-p.weight||(p.to<d.to?-1:1)).slice(0,o);for(let p of u){let d=Xa[p.kind]??.3,f=l.activation*d*Math.min(p.weight,1);if(f<n)continue;let m=s.get(p.to);(!m||m.activation<f)&&(s.set(p.to,{activation:f,via:{from:l.key,kind:p.kind}}),a.push({key:p.to,activation:f}))}}return s}var Nb=E(()=>{"use strict";M()});import{existsSync as Yu,readFileSync as Ob,readdirSync as CP}from"node:fs";import{join as ma}from"node:path";function qu(t){return Math.ceil(t.length/4)}function ao(t,e,r){let n=o=>o.via?.kind==="correlates"?r?.get(o.key)??1:1;return[...t.entries()].filter(([o])=>e(o)).map(([o,i])=>({key:o,activation:i.activation,via:i.via})).sort((o,i)=>i.activation*n(i)-o.activation*n(o)||(o.key<i.key?-1:1))}function Lt(t){let e=re(t);return e?(e.level==="task"||e.level==="adr",e.path):t}function yi(t){if(!t.via)return"matched from the task text";let e=Lt(t.via.from);switch(t.via.kind){case"touched_by":return t.via.from.startsWith("task::")?`touched by ${e}`:`touches ${e}`;case"correlates":return`co-changes with ${e}`;case"relates":return`related to ${e} (shared files)`;case"references":return`referenced by ${e}`;case"contains":return`contained in ${e}`;default:return`linked to ${e}`}}function Lb(t,e){let r=/^ADR-(\d{3,4})$/.exec(e)?.[1];if(!r)return null;let n=ma(t,"adr");if(!Yu(n))return null;let o=r.padStart(4,"0");for(let i of CP(n).sort())if(!(!i.startsWith(`${o}-`)||!i.endsWith(".md")))try{return{file:`adr/${i}`,content:Ob(ma(n,i),"utf-8").trim()}}catch{return null}return null}function Mb(t){let{taskKey:e,title:r,contextDir:n,model:o,activated:i}=t,s=t.budgetTokens??Br.budgetTokens,a=[],c=0,l=R=>{let v=qu(R);return c+v>s?!1:(a.push(R),c+=v,!0)};l([`# Context pack \u2014 ${e}: ${r}`,"","Assembled deterministically from the project map (git history, past","tasks, decisions). No file bodies here \u2014 the paths are ENTRY POINTS","into the repositories; each line says why it made the list."].join(`
944
+ `));let u=ao(i,R=>R.startsWith("adr::")),p=!1;for(let R of u){let v=Lb(n,Lt(R.key));if(!v)continue;let P=`${p?"":`
931
945
  ## Governing decisions
932
946
  `}
933
- ### ${At(R.key)} (\`${v.file}\`, ${ui(R)})
947
+ ### ${Lt(R.key)} (\`${v.file}\`, ${yi(R)})
934
948
 
935
949
  ${v.content}
936
- `;if(!l(_))break;p=!0}let d=ro(i,R=>o.nodes.get(R)?.entityId!==void 0).filter(R=>o.annotations.has(o.nodes.get(R.key).entityId)),f=t.staleKeys??new Set,m=!1;for(let R of d){let v=o.nodes.get(R.key).entityId,_=o.annotations.get(v),N=f.has(R.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(v)?" \u2014 \u26A0 the file no longer exists":"",G=`${m?"":`
950
+ `;if(!l(P))break;p=!0}let d=ao(i,R=>o.nodes.get(R)?.entityId!==void 0).filter(R=>o.annotations.has(o.nodes.get(R.key).entityId)),f=t.staleKeys??new Set,m=!1;for(let R of d){let v=o.nodes.get(R.key).entityId,P=o.annotations.get(v),N=f.has(R.key)?" \u2014 \u26A0 the file changed since the map was built":o.orphanedEntities.has(v)?" \u2014 \u26A0 the file no longer exists":"",G=`${m?"":`
937
951
  ## Why the code is shaped this way (intent notes)
938
952
  `}
939
- ### \`${At(R.key)}\`${N}
953
+ ### \`${Lt(R.key)}\`${N}
940
954
 
941
- ${_}
942
- `;if(!l(G))break;m=!0}let y=Re(e),b=ro(i,R=>R.startsWith("task::")&&R!==y).slice(0,oP),w=!1;for(let R of b){let v=o.events.get(At(R.key));if(!v)continue;let _=[...v.files].filter(g=>!f.has(g.key)&&(!g.entityId||!o.orphanedEntities.has(g.entityId))).sort((g,B)=>(B.churn??0)-(g.churn??0)||(g.key<B.key?-1:1)).slice(0,3).map(g=>`\`${At(g.key)}\``).join(", "),N="",G=v.links?.solution??[`tasks/${v.taskKey}/PLAN.md`,`tasks/${v.taskKey}/SOLUTION.md`].find(g=>Lu(oa(n,g)))??`tasks/${v.taskKey}/PLAN.md`,W=oa(n,G);if(Lu(W))try{N=`
943
- > ${hb(W,"utf-8").trim().slice(0,sP).replace(/\n+/g," ").trim()}\u2026
955
+ ${P}
956
+ `;if(!l(G))break;m=!0}let y=Re(e),b=ao(i,R=>R.startsWith("task::")&&R!==y).slice(0,PP),w=!1;for(let R of b){let v=o.events.get(Lt(R.key));if(!v)continue;let P=[...v.files].filter(g=>!f.has(g.key)&&(!g.entityId||!o.orphanedEntities.has(g.entityId))).sort((g,B)=>(B.churn??0)-(g.churn??0)||(g.key<B.key?-1:1)).slice(0,3).map(g=>`\`${Lt(g.key)}\``).join(", "),N="",G=v.links?.solution??[`tasks/${v.taskKey}/PLAN.md`,`tasks/${v.taskKey}/SOLUTION.md`].find(g=>Yu(ma(n,g)))??`tasks/${v.taskKey}/PLAN.md`,W=ma(n,G);if(Yu(W))try{N=`
957
+ > ${Ob(W,"utf-8").trim().slice(0,_P).replace(/\n+/g," ").trim()}\u2026
944
958
  > _(full text: \`${G}\`)_`}catch{}let C=`${w?"":`
945
959
  ## Related past tasks
946
960
  `}
947
- - **${v.taskKey}**${v.title?` \u2014 ${v.title}`:""}${v.date?` (${v.date})`:""}, ${ui(R)}. Files: ${_||"\u2014"}.${N}`;if(!l(C))break;w=!0}let k=R=>{if(f.has(R.key))return!1;let v=o.nodes.get(R.key)?.entityId;return!v||!o.orphanedEntities.has(v)},x=ro(i,R=>R.startsWith("code:"),t.fileWeights),h=x.filter(k).slice(0,iP);if(h.length>0){let R=["","## Files likely involved",""];for(let v of h){let _=`- \`${At(v.key)}\` \u2014 ${ui(v)}`;if(c+Ou(R.join(`
948
- `))+Ou(_)>s)break;R.push(_)}R.length>3&&l(R.join(`
949
- `))}let T=x.filter(R=>!k(R)).slice(0,10);if(T.length>0){let R=["","## Possibly stale (verify before trusting)","","These entries reference files that changed after the map was built or","no longer exist at their recorded location. Useful as history, wrong","as current fact.","",...T.map(v=>`- \`${At(v.key)}\` \u2014 ${ui(v)}${f.has(v.key)?" (changed since the map was built)":" (file gone)"}`)];l(R.join(`
961
+ - **${v.taskKey}**${v.title?` \u2014 ${v.title}`:""}${v.date?` (${v.date})`:""}, ${yi(R)}. Files: ${P||"\u2014"}.${N}`;if(!l(C))break;w=!0}let k=R=>{if(f.has(R.key))return!1;let v=o.nodes.get(R.key)?.entityId;return!v||!o.orphanedEntities.has(v)},x=ao(i,R=>R.startsWith("code:"),t.fileWeights),h=x.filter(k).slice(0,AP);if(h.length>0){let R=["","## Files likely involved",""];for(let v of h){let P=`- \`${Lt(v.key)}\` \u2014 ${yi(v)}`;if(c+qu(R.join(`
962
+ `))+qu(P)>s)break;R.push(P)}R.length>3&&l(R.join(`
963
+ `))}let T=x.filter(R=>!k(R)).slice(0,10);if(T.length>0){let R=["","## Possibly stale (verify before trusting)","","These entries reference files that changed after the map was built or","no longer exist at their recorded location. Useful as history, wrong","as current fact.","",...T.map(v=>`- \`${Lt(v.key)}\` \u2014 ${yi(v)}${f.has(v.key)?" (changed since the map was built)":" (file gone)"}`)];l(R.join(`
950
964
  `))}return a.length<=1?null:a.join(`
951
965
  `)+`
952
- `}function wb(t){let{model:e,activated:r}=t,n=t.staleKeys??new Set,o=t.maxPaths??18,i=1600,s=ro(r,u=>u.startsWith("adr::")).filter(u=>gb(t.contextDir,At(u.key))!==null).slice(0,6).map(u=>At(u.key)),a=u=>{if(n.has(u.key))return!1;let p=e.nodes.get(u.key)?.entityId;return!p||!e.orphanedEntities.has(p)},c=ro(r,u=>u.startsWith("code:"),t.fileWeights).filter(a).slice(0,o);if(s.length===0&&c.length===0)return null;let l=["Top of the pack (the full brief with reasons and decision bodies is in","`meta/context-pack.md` \u2014 still read it):"];if(s.length>0&&l.push("",`Governing decisions: ${s.join(", ")} (bodies under \`adr/\`).`),c.length>0){l.push("","Files most likely involved:");let u=0;for(let p of c){let d=`- \`${At(p.key)}\` \u2014 ${ui(p)}`;if(u+d.length>i)break;l.push(d),u+=d.length+1}}return l.join(`
953
- `)}var oP,iP,sP,bb=E(()=>{"use strict";M();oP=5,iP=300,sP=400});var Sb={};Ne(Sb,{assembleContextPack:()=>dP,computeIdfWeights:()=>xb});import{createHash as aP}from"node:crypto";import{existsSync as kb,readFileSync as vb}from"node:fs";import{join as $b}from"node:path";function xb(t){let e=new Map,r=t.events.size;if(r<cP)return e;let n=new Map;for(let i of t.events.values()){let s=new Set;for(let a of i.files){let c=a.entityId?`e:${a.entityId}`:`k:${a.key}`;s.has(c)||(s.add(c),n.set(c,(n.get(c)??0)+1))}}let o=Math.log(r+1);for(let[i,s]of n){let a=i.startsWith("e:")?t.keyByEntity.get(i.slice(2))??null:i.slice(2);a&&e.set(a,Math.max(.15,Math.log((r+1)/(s+1))/o))}return e}function lP(t){return aP("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function uP(t,e,r){let n=new Set;for(let o of e.keys()){let i=re(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=$b(a,i.path);try{if(!kb(c)){n.add(o);continue}lP(vb(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function dP(t){let e=ab(t.contextDir);if(e.empty)return null;let r="",n=$b(t.contextDir,`tasks/${t.taskKey}/task.md`);if(kb(n))try{r=vb(n,"utf-8")}catch{r=""}let o=db({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=fb(e,o),s=t.repoDirs?uP(e,i,t.repoDirs):new Set,a=t.idfPenalty===!1?new Map:xb(e),c=yb({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,fileWeights:a,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}});return c?{markdown:c,top:wb({model:e,activated:i,contextDir:t.contextDir,staleKeys:s,fileWeights:a})}:null}var cP,Eb=E(()=>{"use strict";M();cb();pb();mb();bb();cP=30});var Cb={};Ne(Cb,{SKILLS_DIR:()=>Mu,loadSkills:()=>vP,materializeSkills:()=>$P,renderSkillsBlock:()=>xP,resolveBundledSkillsDir:()=>Ib});import{cpSync as pP,existsSync as Rb,mkdirSync as fP,readFileSync as mP,readdirSync as Tb}from"node:fs";import{dirname as hP,join as Sr}from"node:path";import{fileURLToPath as gP}from"node:url";import{parse as yP}from"yaml";function Ib(t){for(let e of[t,Sr(t,"skills")])try{if(Tb(e,{withFileTypes:!0}).some(n=>n.isDirectory()&&Rb(Sr(e,n.name,"SKILL.md"))))return e}catch{}return t}function bP(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
966
+ `}function Db(t){let{model:e,activated:r}=t,n=t.staleKeys??new Set,o=t.maxPaths??18,i=1600,s=ao(r,u=>u.startsWith("adr::")).filter(u=>Lb(t.contextDir,Lt(u.key))!==null).slice(0,6).map(u=>Lt(u.key)),a=u=>{if(n.has(u.key))return!1;let p=e.nodes.get(u.key)?.entityId;return!p||!e.orphanedEntities.has(p)},c=ao(r,u=>u.startsWith("code:"),t.fileWeights).filter(a).slice(0,o);if(s.length===0&&c.length===0)return null;let l=["Top of the pack (the full brief with reasons and decision bodies is in","`meta/context-pack.md` \u2014 still read it):"];if(s.length>0&&l.push("",`Governing decisions: ${s.join(", ")} (bodies under \`adr/\`).`),c.length>0){l.push("","Files most likely involved:");let u=0;for(let p of c){let d=`- \`${Lt(p.key)}\` \u2014 ${yi(p)}`;if(u+d.length>i)break;l.push(d),u+=d.length+1}}return l.join(`
967
+ `)}var PP,AP,_P,Ub=E(()=>{"use strict";M();PP=5,AP=300,_P=400});var Hb={};Me(Hb,{assembleContextPack:()=>MP,computeIdfWeights:()=>Kb});import{createHash as jP}from"node:crypto";import{existsSync as Bb,readFileSync as Fb}from"node:fs";import{join as Gb}from"node:path";function Kb(t){let e=new Map,r=t.events.size;if(r<NP)return e;let n=new Map;for(let i of t.events.values()){let s=new Set;for(let a of i.files){let c=a.entityId?`e:${a.entityId}`:`k:${a.key}`;s.has(c)||(s.add(c),n.set(c,(n.get(c)??0)+1))}}let o=Math.log(r+1);for(let[i,s]of n){let a=i.startsWith("e:")?t.keyByEntity.get(i.slice(2))??null:i.slice(2);a&&e.set(a,Math.max(.15,Math.log((r+1)/(s+1))/o))}return e}function OP(t){return jP("sha1").update(`blob ${t.length}\0`).update(t).digest("hex")}function LP(t,e,r){let n=new Set;for(let o of e.keys()){let i=re(o);if(i?.level!=="code")continue;let s=t.nodes.get(o);if(!s?.contentHash)continue;let a=r.get(i.repo);if(!a)continue;let c=Gb(a,i.path);try{if(!Bb(c)){n.add(o);continue}OP(Fb(c)).startsWith(s.contentHash)||n.add(o)}catch{}}return n}function MP(t){let e=Tb(t.contextDir);if(e.empty)return null;let r="",n=Gb(t.contextDir,`tasks/${t.taskKey}/task.md`);if(Bb(n))try{r=Fb(n,"utf-8")}catch{r=""}let o=Ab({taskKey:t.taskKey,title:t.title,text:r,model:e});if(o.size===0)return null;let i=jb(e,o),s=t.repoDirs?LP(e,i,t.repoDirs):new Set,a=t.idfPenalty===!1?new Map:Kb(e),c=Mb({taskKey:t.taskKey,title:t.title,contextDir:t.contextDir,model:e,activated:i,staleKeys:s,fileWeights:a,...t.budgetTokens!==void 0?{budgetTokens:t.budgetTokens}:{}});return c?{markdown:c,top:Db({model:e,activated:i,contextDir:t.contextDir,staleKeys:s,fileWeights:a})}:null}var NP,Wb=E(()=>{"use strict";M();Ib();_b();Nb();Ub();NP=30});var zb={};Me(zb,{SKILLS_DIR:()=>Vu,loadSkills:()=>YP,materializeSkills:()=>VP,renderSkillsBlock:()=>zP,resolveBundledSkillsDir:()=>Vb});import{cpSync as DP,existsSync as qb,mkdirSync as UP,readFileSync as BP,readdirSync as Yb}from"node:fs";import{dirname as FP,join as Cr}from"node:path";import{fileURLToPath as GP}from"node:url";import{parse as KP}from"yaml";function Vb(t){for(let e of[t,Cr(t,"skills")])try{if(Yb(e,{withFileTypes:!0}).some(n=>n.isDirectory()&&qb(Cr(e,n.name,"SKILL.md"))))return e}catch{}return t}function WP(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
954
968
  ---`,3);return r===-1?null:{yaml:e.slice(e.indexOf(`
955
969
  `,3)+1,r),body:e.slice(e.indexOf(`
956
- `,r+1)+1)}}function kP(t,e,r){let n=[],o=[];if(!Rb(t))return{skills:n,errors:o};let i;try{i=Tb(t,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name).sort()}catch(s){return{skills:n,errors:[{source:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){let a=Sr(t,s),c=`${r}/${s}`,l;try{l=mP(Sr(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=bP(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=yP(u.yaml)}catch(f){o.push({source:c,error:`frontmatter is not valid YAML: ${String(f)}`});continue}let d=bc({name:s,frontmatter:p,body:u.body});d.ok?n.push({...d.skill,dir:a,origin:e}):o.push({source:c,error:d.error})}return{skills:n,errors:o}}function vP(t){let e=[],r=(s,a,c)=>{let l=kP(s,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(wP,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(Sr(t.contextDir,"skills"),"context","skills"):[],i=t.sources.repo?t.repoDirs.flatMap(s=>r(Sr(s,".claude","skills"),"repo","repo")):[];return{skills:kc(n,o,i),errors:e}}function $P(t,e){if(e.length===0)return[];let r=Sr(t,Mu);fP(r,{recursive:!0});let n=[];for(let o of e)pP(o.dir,Sr(r,o.name),{recursive:!0}),n.push(`${Mu}/${o.name}`);return n}function xP(t,e=[]){let r=new Set(t.map(s=>s.name)),n=e.filter(s=>!r.has(s));if(t.length===0&&n.length===0)return"";let o=[];t.length>0&&o.push("## Skills available to you","",...t.map(s=>`- **${s.name}** \u2014 ${s.description}`),"","Only these lines are in context; a skill's steps load when you invoke it.","When one covers what you are about to do, use it: it was written down","because the obvious approach was wrong or costly.","");let i=e.filter(s=>r.has(s));return i.length>0&&o.push("**The approved plan requires this task to follow: "+i.map(s=>`\`${s}\``).join(", ")+".**","This is not a suggestion \u2014 a reviewer approved it as a requirement.",""),n.length>0&&o.push("**The plan prescribes "+n.map(s=>`\`${s}\``).join(", ")+", which is not available here.**","Proceed without it and say so in your result \u2014 do not invent the procedure.",""),o.join(`
957
- `)}var Mu,wP,Pb=E(()=>{"use strict";M();Mu=".claude/skills";wP=Ib(hP(gP(import.meta.url)))});var Nb={};Ne(Nb,{seedMarketplaces:()=>jP});import{spawn as SP}from"node:child_process";import{cpSync as EP,existsSync as Ab,mkdirSync as _b,rmSync as Du,symlinkSync as RP,writeFileSync as TP}from"node:fs";import{homedir as IP}from"node:os";import{join as Er}from"node:path";function jb(){return Er(IP(),".codepipe-sandbox","plugins")}function AP(t){return Er(jb(),"src",`${t.name}@${t.sha||"head"}`)}function di(t,e){return new Promise((r,n)=>{let o=SP("git",t,{cwd:e,stdio:["ignore","ignore","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"}}),i=[];o.stderr.setEncoding("utf-8"),o.stderr.on("data",s=>i.push(s)),o.on("error",n),o.on("close",s=>{if(s===0)return r();n(new Error(`git ${t[0]} failed (exit ${s}): ${i.join("").trim().slice(0,400)}`))})})}async function _P(t){let e=AP(t);if(Ab(Er(e,".claude-plugin","marketplace.json")))return e;Du(e,{recursive:!0,force:!0}),_b(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await di(["init","--quiet"],e),await di(["remote","add","origin",r],e),await di(["fetch","--quiet","--depth","1","origin",t.sha],e),await di(["checkout","--quiet","FETCH_HEAD"],e)):await di(["clone","--quiet","--depth","1",r,e]),!Ab(Er(e,".claude-plugin","marketplace.json")))throw Du(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function jP(t){if(t.length===0)return{dir:null,ready:[],errors:[]};let e=[],r=[],n=new Map;for(let a of t)try{n.set(a.name,await _P(a)),r.push(a)}catch(c){e.push({repo:a.repo,error:c instanceof Error?c.message:String(c)})}if(r.length===0)return{dir:null,ready:r,errors:e};let o=Er(jb(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),i=Er(o,CP);_b(i,{recursive:!0});let s={};for(let a of r){let c=Er(i,a.name);Du(c,{recursive:!0,force:!0}),NP(n.get(a.name),c),s[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return TP(Er(o,PP),`${JSON.stringify(s,null,2)}
958
- `),{dir:o,ready:r,errors:e}}function NP(t,e){try{RP(t,e,"dir")}catch{EP(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var CP,PP,Ob=E(()=>{"use strict";CP="marketplaces",PP="known_marketplaces.json"});var Bu={};Ne(Bu,{loadRoles:()=>GP,resolveBundledRolesDir:()=>Db});import{existsSync as OP,readFileSync as LP,readdirSync as Mb}from"node:fs";import{dirname as MP,join as Uu}from"node:path";import{fileURLToPath as DP}from"node:url";import{parse as UP}from"yaml";function Db(t){for(let e of[t,Uu(t,"roles")])try{if(Mb(e).some(r=>r.endsWith(".md")))return e}catch{}return t}function FP(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
970
+ `,r+1)+1)}}function qP(t,e,r){let n=[],o=[];if(!qb(t))return{skills:n,errors:o};let i;try{i=Yb(t,{withFileTypes:!0}).filter(s=>s.isDirectory()).map(s=>s.name).sort()}catch(s){return{skills:n,errors:[{source:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){let a=Cr(t,s),c=`${r}/${s}`,l;try{l=BP(Cr(a,"SKILL.md"),"utf-8")}catch{o.push({source:c,error:"no SKILL.md in the directory"});continue}let u=WP(l);if(!u){o.push({source:c,error:"SKILL.md has no frontmatter block"});continue}let p;try{p=KP(u.yaml)}catch(f){o.push({source:c,error:`frontmatter is not valid YAML: ${String(f)}`});continue}let d=Nc({name:s,frontmatter:p,body:u.body});d.ok?n.push({...d.skill,dir:a,origin:e}):o.push({source:c,error:d.error})}return{skills:n,errors:o}}function YP(t){let e=[],r=(s,a,c)=>{let l=qP(s,a,c);return e.push(...l.errors),l.skills},n=t.sources.bundled?r(HP,"bundled","bundled"):[],o=t.sources.context&&t.contextDir?r(Cr(t.contextDir,"skills"),"context","skills"):[],i=t.sources.repo?t.repoDirs.flatMap(s=>r(Cr(s,".claude","skills"),"repo","repo")):[];return{skills:Oc(n,o,i),errors:e}}function VP(t,e){if(e.length===0)return[];let r=Cr(t,Vu);UP(r,{recursive:!0});let n=[];for(let o of e)DP(o.dir,Cr(r,o.name),{recursive:!0}),n.push(`${Vu}/${o.name}`);return n}function zP(t,e=[]){let r=new Set(t.map(s=>s.name)),n=e.filter(s=>!r.has(s));if(t.length===0&&n.length===0)return"";let o=[];t.length>0&&o.push("## Skills available to you","",...t.map(s=>`- **${s.name}** \u2014 ${s.description}`),"","Only these lines are in context; a skill's steps load when you invoke it.","When one covers what you are about to do, use it: it was written down","because the obvious approach was wrong or costly.","");let i=e.filter(s=>r.has(s));return i.length>0&&o.push("**The approved plan requires this task to follow: "+i.map(s=>`\`${s}\``).join(", ")+".**","This is not a suggestion \u2014 a reviewer approved it as a requirement.",""),n.length>0&&o.push("**The plan prescribes "+n.map(s=>`\`${s}\``).join(", ")+", which is not available here.**","Proceed without it and say so in your result \u2014 do not invent the procedure.",""),o.join(`
971
+ `)}var Vu,HP,Xb=E(()=>{"use strict";M();Vu=".claude/skills";HP=Vb(FP(GP(import.meta.url)))});var ek={};Me(ek,{seedMarketplaces:()=>iA});import{spawn as XP}from"node:child_process";import{cpSync as JP,existsSync as Jb,mkdirSync as Zb,rmSync as zu,symlinkSync as ZP,writeFileSync as QP}from"node:fs";import{homedir as eA}from"node:os";import{join as Pr}from"node:path";function Qb(){return Pr(eA(),".codepipe-sandbox","plugins")}function nA(t){return Pr(Qb(),"src",`${t.name}@${t.sha||"head"}`)}function wi(t,e){return new Promise((r,n)=>{let o=XP("git",t,{cwd:e,stdio:["ignore","ignore","pipe"],env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"}}),i=[];o.stderr.setEncoding("utf-8"),o.stderr.on("data",s=>i.push(s)),o.on("error",n),o.on("close",s=>{if(s===0)return r();n(new Error(`git ${t[0]} failed (exit ${s}): ${i.join("").trim().slice(0,400)}`))})})}async function oA(t){let e=nA(t);if(Jb(Pr(e,".claude-plugin","marketplace.json")))return e;zu(e,{recursive:!0,force:!0}),Zb(e,{recursive:!0});let r=`https://github.com/${t.repo}.git`;if(t.sha?(await wi(["init","--quiet"],e),await wi(["remote","add","origin",r],e),await wi(["fetch","--quiet","--depth","1","origin",t.sha],e),await wi(["checkout","--quiet","FETCH_HEAD"],e)):await wi(["clone","--quiet","--depth","1",r,e]),!Jb(Pr(e,".claude-plugin","marketplace.json")))throw zu(e,{recursive:!0,force:!0}),new Error("no .claude-plugin/marketplace.json \u2014 this repository is not a marketplace");return e}async function iA(t){if(t.length===0)return{dir:null,ready:[],errors:[]};let e=[],r=[],n=new Map;for(let a of t)try{n.set(a.name,await oA(a)),r.push(a)}catch(c){e.push({repo:a.repo,error:c instanceof Error?c.message:String(c)})}if(r.length===0)return{dir:null,ready:r,errors:e};let o=Pr(Qb(),"seed",r.map(a=>`${a.name}@${a.sha||"head"}`).sort().join("_")),i=Pr(o,tA);Zb(i,{recursive:!0});let s={};for(let a of r){let c=Pr(i,a.name);zu(c,{recursive:!0,force:!0}),sA(n.get(a.name),c),s[a.name]={source:{source:"github",repo:a.repo},installLocation:c,...a.sha?{commit:a.sha}:{}}}return QP(Pr(o,rA),`${JSON.stringify(s,null,2)}
972
+ `),{dir:o,ready:r,errors:e}}function sA(t,e){try{ZP(t,e,"dir")}catch{JP(t,e,{recursive:!0,filter:r=>!/(^|\/)\.git(\/|$)/.test(r)})}}var tA,rA,tk=E(()=>{"use strict";tA="marketplaces",rA="known_marketplaces.json"});var Ju={};Me(Ju,{loadRoles:()=>mA,resolveBundledRolesDir:()=>ok});import{existsSync as aA,readFileSync as cA,readdirSync as nk}from"node:fs";import{dirname as lA,join as Xu}from"node:path";import{fileURLToPath as uA}from"node:url";import{parse as dA}from"yaml";function ok(t){for(let e of[t,Xu(t,"roles")])try{if(nk(e).some(r=>r.endsWith(".md")))return e}catch{}return t}function fA(t){let e=t.replace(/^/,"");if(!e.startsWith("---"))return null;let r=e.indexOf(`
959
973
  ---`,3);if(r===-1)return null;let n=e.slice(e.indexOf(`
960
974
  `,3)+1,r),o=e.indexOf(`
961
- `,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function Lb(t,e,r){let n=[],o=[];if(!OP(t))return{roles:n,errors:o};let i;try{i=Mb(t).sort()}catch(s){return{roles:n,errors:[{file:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){if(!s.endsWith(".md"))continue;let a=`${r}/${s}`,c;try{c=LP(Uu(t,s),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=FP(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=UP(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=fc({name:s.slice(0,-3),frontmatter:u,body:l.body,origin:e});p.ok?n.push(p.role):o.push({file:a,error:p.error})}return{roles:n,errors:o}}function GP(t){let e=Lb(BP,"bundled","bundled"),r=t?Lb(Uu(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:mc(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var BP,Fu=E(()=>{"use strict";M();BP=Db(MP(DP(import.meta.url)))});var Gu={};Ne(Gu,{COUNCIL_DEFAULT_MAX_PARALLEL:()=>YP,COUNCIL_DIR:()=>qP,COUNCIL_MAX_PARALLEL_CEILING:()=>Ub,renderCouncilRolePrompt:()=>VP,renderOpinionsBlock:()=>XP,renderReviewOpinionsBlock:()=>JP,renderReviewRolePrompt:()=>zP,runCouncil:()=>ZP});import{existsSync as KP,mkdirSync as HP,writeFileSync as WP}from"node:fs";import{join as ia}from"node:path";function Bb(t,e){return["## Where to read (read-only)","",...e?["The workspace contains the project repos and the Context Repo clone",`(\`${e}\`; start with \`knowledge/INDEX.md\` and \`adr/\`).`]:["The workspace contains the project repos."],...t.refs.length>0&&e?["Read these first:",...t.refs.map(r=>`- \`${ia(e,r)}\``)]:[]]}function VP(t,e,r,n){return[`# Council role: ${t.name}`,"",t.body,"","## The questions the pipeline is blocked on","",e,"",...Bb(t,r),"","## Your deliverable","",`Write your opinion to \`${n}\`: for EACH question \u2014 your answer,`,"the strongest argument for it, and what would change your mind. You are","ONE role of a council: argue your perspective sharply, do not average.","You never modify code \u2014 this file is your only output."].join(`
962
- `)}function zP(t,e,r,n){return[`# Council role: ${t.name}`,"",t.body,"","## The review subject","","Review the change under `code/`: in each repo, the subject is","`git diff refs/worktree/codepipe/review-base..HEAD` \u2014 the base ref is","pinned, do not diff against a branch tip. A repo with an empty diff is","context, not subject. If the ref is MISSING in a repo (the pin can fail),","say so in your opinion and skip that repo \u2014 never substitute another base:","findings against a wrong diff are worse than no findings.","","## The finding contract","","Every finding names file + line, the concrete failing scenario, and stays","within the diff \u2014 or states explicitly how the change broke an untouched","place. A finding without a scenario is an opinion, not a finding.",...e?["",e.trim()]:[],"",...Bb(t,r),"","## Your deliverable","",`Write your findings to \`${n}\` \u2014 your role's independent view,`,"one section per finding. Returning NOTHING is a normal outcome \u2014 do not","manufacture findings to justify your seat. You are ONE role of a council:","stay inside your perspective, do not average.","You never modify code \u2014 this file is your only output."].join(`
963
- `)}function Fb(t){let e=t.filter(n=>n.ok),r=t.filter(n=>!n.ok);return[...e.map(n=>`- \`${n.artifact}\` \u2014 the ${n.role} role`),...r.length>0?["",`Failed roles (no opinion \u2014 weigh accordingly): ${r.map(n=>n.role).join(", ")}.`]:[]]}function XP(t){return["## The council's opinions (already gathered)","","The council's roles have already examined the questions \u2014 each in its own","context, blind to the others. Read every opinion before answering:","",...Fb(t),"","Weigh, do not vote: agreement between roles is evidence, not a verdict,","and you may overrule any of them \u2014 say so in the rationale when you do."].join(`
964
- `)}function JP(t){return["## The council's findings (already gathered)","","The project's critic roles have already reviewed this change \u2014 each in its","own context, blind to the others. Read every file before your own pass:","",...Fb(t),"","Then do your own job on what they wrote:","","1. **Deduplicate.** Two roles reporting the same defect is one finding, not two.","2. **Filter.** A finding earns a round-trip only if it is a real defect, a"," regression or a convention the project actually enforces. Taste-level"," notes go in the summary, never in the remarks.","3. **Decide.** The verdict is yours, not a vote: a role can be wrong, and"," you are the one who read the code. When you overrule a role, say why in"," the summary.","","A role that found nothing is a normal outcome \u2014 do not manufacture findings","to justify the council."].join(`
965
- `)}async function ZP(t){let e=t.baseInput.workspaceDir;HP(ia(e,t.artifactDir),{recursive:!0});let r=Math.max(1,Math.min(t.maxParallel,Ub)),n=[...t.roles],o=[],i=ut(),s=null,a=new AbortController,c=t.baseInput.signal,l=()=>a.abort();c?.aborted?a.abort():c?.addEventListener("abort",l,{once:!0});let u=async d=>{let f=`${t.artifactDir}/${d.name}.md`,m=t.runnerFor(d.provider),y=t.promptFor(d,f),b=d.model??t.defaultModel;try{let w=await m.run({...t.baseInput,signal:a.signal,role:"council",prompt:y,...b?{model:b}:{},...t.effort?{effort:t.effort}:{}});Qr(i,w.usage),KP(ia(e,f))?(o.push({role:d.name,ok:!0,artifact:f,usage:w.usage}),t.log(`role ${d.name}: done ($${w.usage.totalCostUsd.toFixed(2)})`)):(o.push({role:d.name,ok:!1,error:`exited ok but wrote no ${f}`,usage:w.usage}),t.log(`role ${d.name}: exited ok but wrote no ${f}`))}catch(w){let k=w instanceof Me?w.details.usage:w instanceof Pt?w.usage:void 0;k&&Qr(i,k),w instanceof Me&&w.details.rateLimited&&!s&&(s=w,a.abort());let x=w instanceof Error?w.message:String(w);o.push({role:d.name,ok:!1,error:x,usage:k??ut()}),t.log(`role ${d.name}: failed \u2014 ${x}`)}},p=Array.from({length:Math.min(r,n.length)},async()=>{for(;n.length>0&&!a.signal.aborted;){let d=n.shift();if(!d)break;await u(d)}});try{await Promise.all(p)}finally{c?.removeEventListener("abort",l)}if(s){let d=s,f=d.details.usage?.model;throw d.details.usage={...i,...f!==void 0?{model:f}:{}},d}return WP(ia(e,t.artifactDir,"usage.json"),JSON.stringify(o.map(d=>({role:d.role,ok:d.ok,costUsd:d.usage.totalCostUsd,model:d.usage.model})),null,2)),{opinions:o,usage:i}}var qP,Ub,YP,Ku=E(()=>{"use strict";M();br();ai();qP="council",Ub=5,YP=3});var Gb={};Ne(Gb,{ROLE_AGENTS_DIR:()=>Wu,materializeRoleAgents:()=>rA,renderRolesBlock:()=>nA});import{mkdirSync as QP,writeFileSync as eA}from"node:fs";import{join as Hu}from"node:path";function tA(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
966
- `),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${Hu(e,o)}\``),"","They are this role's curated context. If one is missing, say so in a line and continue \u2014","its absence is not an error.",""].join(`
975
+ `,r+1);return{yaml:n,body:o===-1?"":e.slice(o+1)}}function rk(t,e,r){let n=[],o=[];if(!aA(t))return{roles:n,errors:o};let i;try{i=nk(t).sort()}catch(s){return{roles:n,errors:[{file:r,error:`cannot read: ${String(s)}`}]}}for(let s of i){if(!s.endsWith(".md"))continue;let a=`${r}/${s}`,c;try{c=cA(Xu(t,s),"utf-8")}catch(d){o.push({file:a,error:`cannot read: ${String(d)}`});continue}let l=fA(c);if(!l){o.push({file:a,error:"missing frontmatter block (--- \u2026 ---) at the top of the file"});continue}let u;try{u=dA(l.yaml)}catch(d){o.push({file:a,error:`frontmatter is not valid YAML: ${String(d)}`});continue}let p=Ic({name:s.slice(0,-3),frontmatter:u,body:l.body,origin:e});p.ok?n.push(p.role):o.push({file:a,error:p.error})}return{roles:n,errors:o}}function mA(t){let e=rk(pA,"bundled","bundled"),r=t?rk(Xu(t,"roles"),"project","roles"):{roles:[],errors:[]};return{roles:Cc(e.roles,r.roles),errors:[...e.errors,...r.errors]}}var pA,Zu=E(()=>{"use strict";M();pA=ok(lA(uA(import.meta.url)))});var Qu={};Me(Qu,{COUNCIL_DEFAULT_MAX_PARALLEL:()=>bA,COUNCIL_DIR:()=>wA,COUNCIL_MAX_PARALLEL_CEILING:()=>ik,renderCouncilRolePrompt:()=>kA,renderOpinionsBlock:()=>$A,renderReviewOpinionsBlock:()=>xA,renderReviewRolePrompt:()=>vA,runCouncil:()=>SA});import{existsSync as hA,mkdirSync as gA,writeFileSync as yA}from"node:fs";import{join as ha}from"node:path";function sk(t,e){return["## Where to read (read-only)","",...e?["The workspace contains the project repos and the Context Repo clone",`(\`${e}\`; start with \`knowledge/INDEX.md\` and \`adr/\`).`]:["The workspace contains the project repos."],...t.refs.length>0&&e?["Read these first:",...t.refs.map(r=>`- \`${ha(e,r)}\``)]:[]]}function kA(t,e,r,n){return[`# Council role: ${t.name}`,"",t.body,"","## The questions the pipeline is blocked on","",e,"",...sk(t,r),"","## Your deliverable","",`Write your opinion to \`${n}\`: for EACH question \u2014 your answer,`,"the strongest argument for it, and what would change your mind. You are","ONE role of a council: argue your perspective sharply, do not average.","You never modify code \u2014 this file is your only output."].join(`
976
+ `)}function vA(t,e,r,n){return[`# Council role: ${t.name}`,"",t.body,"","## The review subject","","Review the change under `code/`: in each repo, the subject is","`git diff refs/worktree/codepipe/review-base..HEAD` \u2014 the base ref is","pinned, do not diff against a branch tip. A repo with an empty diff is","context, not subject. If the ref is MISSING in a repo (the pin can fail),","say so in your opinion and skip that repo \u2014 never substitute another base:","findings against a wrong diff are worse than no findings.","","## The finding contract","","Every finding names file + line, the concrete failing scenario, and stays","within the diff \u2014 or states explicitly how the change broke an untouched","place. A finding without a scenario is an opinion, not a finding.",...e?["",e.trim()]:[],"",...sk(t,r),"","## Your deliverable","",`Write your findings to \`${n}\` \u2014 your role's independent view,`,"one section per finding. Returning NOTHING is a normal outcome \u2014 do not","manufacture findings to justify your seat. You are ONE role of a council:","stay inside your perspective, do not average.","You never modify code \u2014 this file is your only output."].join(`
977
+ `)}function ak(t){let e=t.filter(n=>n.ok),r=t.filter(n=>!n.ok);return[...e.map(n=>`- \`${n.artifact}\` \u2014 the ${n.role} role`),...r.length>0?["",`Failed roles (no opinion \u2014 weigh accordingly): ${r.map(n=>n.role).join(", ")}.`]:[]]}function $A(t){return["## The council's opinions (already gathered)","","The council's roles have already examined the questions \u2014 each in its own","context, blind to the others. Read every opinion before answering:","",...ak(t),"","Weigh, do not vote: agreement between roles is evidence, not a verdict,","and you may overrule any of them \u2014 say so in the rationale when you do."].join(`
978
+ `)}function xA(t){return["## The council's findings (already gathered)","","The project's critic roles have already reviewed this change \u2014 each in its","own context, blind to the others. Read every file before your own pass:","",...ak(t),"","Then do your own job on what they wrote:","","1. **Deduplicate.** Two roles reporting the same defect is one finding, not two.","2. **Filter.** A finding earns a round-trip only if it is a real defect, a"," regression or a convention the project actually enforces. Taste-level"," notes go in the summary, never in the remarks.","3. **Decide.** The verdict is yours, not a vote: a role can be wrong, and"," you are the one who read the code. When you overrule a role, say why in"," the summary.","","A role that found nothing is a normal outcome \u2014 do not manufacture findings","to justify the council."].join(`
979
+ `)}async function SA(t){let e=t.baseInput.workspaceDir;gA(ha(e,t.artifactDir),{recursive:!0});let r=Math.max(1,Math.min(t.maxParallel,ik)),n=[...t.roles],o=[],i=ht(),s=null,a=new AbortController,c=t.baseInput.signal,l=()=>a.abort();c?.aborted?a.abort():c?.addEventListener("abort",l,{once:!0});let u=async d=>{let f=`${t.artifactDir}/${d.name}.md`,m=t.runnerFor(d.provider),y=t.promptFor(d,f),b=d.model??t.defaultModel;try{let w=await m.run({...t.baseInput,signal:a.signal,role:"council",prompt:y,...b?{model:b}:{},...t.effort?{effort:t.effort}:{}});cn(i,w.usage),hA(ha(e,f))?(o.push({role:d.name,ok:!0,artifact:f,usage:w.usage}),t.log(`role ${d.name}: done ($${w.usage.totalCostUsd.toFixed(2)})`)):(o.push({role:d.name,ok:!1,error:`exited ok but wrote no ${f}`,usage:w.usage}),t.log(`role ${d.name}: exited ok but wrote no ${f}`))}catch(w){let k=w instanceof Fe?w.details.usage:w instanceof Ot?w.usage:void 0;k&&cn(i,k),w instanceof Fe&&w.details.rateLimited&&!s&&(s=w,a.abort());let x=w instanceof Error?w.message:String(w);o.push({role:d.name,ok:!1,error:x,usage:k??ht()}),t.log(`role ${d.name}: failed \u2014 ${x}`)}},p=Array.from({length:Math.min(r,n.length)},async()=>{for(;n.length>0&&!a.signal.aborted;){let d=n.shift();if(!d)break;await u(d)}});try{await Promise.all(p)}finally{c?.removeEventListener("abort",l)}if(s){let d=s,f=d.details.usage?.model;throw d.details.usage={...i,...f!==void 0?{model:f}:{}},d}return yA(ha(e,t.artifactDir,"usage.json"),JSON.stringify(o.map(d=>({role:d.role,ok:d.ok,costUsd:d.usage.totalCostUsd,model:d.usage.model})),null,2)),{opinions:o,usage:i}}var wA,ik,bA,ed=E(()=>{"use strict";M();Sr();mi();wA="council",ik=5,bA=3});var ck={};Me(ck,{ROLE_AGENTS_DIR:()=>rd,materializeRoleAgents:()=>IA,renderRolesBlock:()=>CA});import{mkdirSync as EA,writeFileSync as RA}from"node:fs";import{join as td}from"node:path";function TA(t,e){let r=["---",`name: ${t.name}`,`description: ${t.description}`,...t.model?[`model: ${t.model}`]:[],"---",""].join(`
980
+ `),n=t.refs.length>0&&e?["","## Read these first","",...t.refs.map(o=>`- \`${td(e,o)}\``),"","They are this role's curated context. If one is missing, say so in a line and continue \u2014","its absence is not an error.",""].join(`
967
981
  `):"";return`${r}${t.body}
968
- ${n}`}function rA(t,e,r,n){let o=hc(e,r);if(o.length===0)return{roles:[],files:[]};let i=Hu(t,Wu);QP(i,{recursive:!0});let s=[];for(let a of o)eA(Hu(i,`${a.name}.md`),tA(a,n)),s.push(`${Wu}/${a.name}.md`);return{roles:o,files:s}}function nA(t,e){return t.roles.length===0?"":["## The panel \u2014 run these critics first","","This project reviews through a panel of roles. Each is available to you as a","subagent with its own narrow view and its own reading list:","",t.roles.map(n=>`- **${n.name}** \u2014 ${n.description}`).join(`
982
+ ${n}`}function IA(t,e,r,n){let o=Pc(e,r);if(o.length===0)return{roles:[],files:[]};let i=td(t,rd);EA(i,{recursive:!0});let s=[];for(let a of o)RA(td(i,`${a.name}.md`),TA(a,n)),s.push(`${rd}/${a.name}.md`);return{roles:o,files:s}}function CA(t,e){return t.roles.length===0?"":["## The panel \u2014 run these critics first","","This project reviews through a panel of roles. Each is available to you as a","subagent with its own narrow view and its own reading list:","",t.roles.map(n=>`- **${n.name}** \u2014 ${n.description}`).join(`
969
983
  `),"","Delegate to **every** role above \u2014 **in parallel**, all Task calls in one","turn. Give each role the SAME briefing (DEV-651 \u2014 the panel's quality is","the briefing's quality, not the coordinator's mood):","","- the review subject: `git diff refs/worktree/codepipe/review-base..HEAD`"," in each repo under `code/` \u2014 the base ref is pinned, do not diff against"," a branch tip;","- the finding contract: every finding names file + line, the concrete"," failing scenario, and stays within the diff \u2014 or states explicitly how"," the change broke an untouched place;","- established facts the role must not re-derive (the BUILD verdict when"," your prompt carries one).","","The roles are independent read-only views that never wait on each other,","so the panel costs the time of its slowest member, not the sum. Then do","your own job on what comes back:","",`1. Save each role's findings verbatim as \`${e}/<role>.md\`.`,"2. **Deduplicate.** Two roles reporting the same defect is one finding, not two.","3. **Filter.** A finding earns a round-trip only if it is a real defect, a"," regression or a convention the project actually enforces. Taste-level notes"," go in the summary, never in the remarks.","4. **Decide.** The verdict is yours, not a vote: a role can be wrong, and you"," are the one who read the code. When you overrule a role, say why in the"," summary.","","A role that returns nothing is a normal outcome \u2014 do not manufacture findings","to justify the panel.",""].join(`
970
- `)}var Wu,Kb=E(()=>{"use strict";M();Wu=".claude/agents"});var Wb={};Ne(Wb,{COUNCIL_ANSWER_PATH:()=>Hb,readCouncilVerdict:()=>sA});import{readFileSync as oA}from"node:fs";import{join as iA}from"node:path";function sA(t){let e;try{e=oA(iA(t,Hb),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Hb,qb=E(()=>{"use strict";Hb="meta/council-answer.json"});var Vb={};Ne(Vb,{QUEUE_PLAN_PATH:()=>Yb,readQueuePlan:()=>lA});import{readFileSync as aA}from"node:fs";import{join as cA}from"node:path";function lA(t){let e;try{e=aA(cA(t,Yb),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var Yb,zb=E(()=>{"use strict";Yb="meta/queue-plan.json"});import{mkdirSync as qu,readFileSync as sa,readdirSync as uA,rmSync as dA,writeFileSync as Yu}from"node:fs";import{homedir as pA}from"node:os";import{dirname as Xb,join as gt}from"node:path";function mA(t){let e=Buffer.from(t,"utf-8");if(e.length<=aa)return t;let r=Math.floor(aa/4),n=aa-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}
984
+ `)}var rd,lk=E(()=>{"use strict";M();rd=".claude/agents"});var dk={};Me(dk,{COUNCIL_ANSWER_PATH:()=>uk,readCouncilVerdict:()=>_A});import{readFileSync as PA}from"node:fs";import{join as AA}from"node:path";function _A(t){let e;try{e=PA(AA(t,uk),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var uk,pk=E(()=>{"use strict";uk="meta/council-answer.json"});var mk={};Me(mk,{QUEUE_PLAN_PATH:()=>fk,readQueuePlan:()=>OA});import{readFileSync as jA}from"node:fs";import{join as NA}from"node:path";function OA(t){let e;try{e=jA(NA(t,fk),"utf-8")}catch{return null}try{return JSON.parse(e)}catch{return null}}var fk,hk=E(()=>{"use strict";fk="meta/queue-plan.json"});import{mkdirSync as nd,readFileSync as ga,readdirSync as LA,rmSync as MA,writeFileSync as od}from"node:fs";import{homedir as DA}from"node:os";import{dirname as gk,join as vt}from"node:path";function BA(t){let e=Buffer.from(t,"utf-8");if(e.length<=ya)return t;let r=Math.floor(ya/4),n=ya-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}
971
985
 
972
- \u2026 [${s} bytes elided \u2014 log capped at ${aa} bytes for upload] \u2026
986
+ \u2026 [${s} bytes elided \u2014 log capped at ${ya} bytes for upload] \u2026
973
987
 
974
- ${i}`}function hA(){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 pi(t={}){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=Ky(t.profile,e.sandboxId,!!ee("SANDBOX_CONFIG")),s=gt(pA(),".codepipe","logs"),a=Bi("SANDBOX_LOG",i,s);if(a.enabled){let C=new An(a);Fi(C),console.log(`[log] file logging \u2192 ${C.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${et} (protocol ${$t})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=nw(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=bu();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new Xn(e.hubUrl,e.token);e.llm==="claude-headless"&&(async()=>{let{identity:C,login:g}=iw(),B=await u.reportAgentAuth({identity:C,login:g!==null,...g?.email?{email:g.email}:{}});if(!g){console.warn("[agent-auth] this host is not logged into Claude Code \u2014 run `claude` and sign in, or set a project token with `codepipe login`");return}if(!B)return;let L=await sw();console.log(`[agent-auth] probe: ${L.state}${L.detail?` (${L.detail})`:""}`),await u.reportAgentAuthResult({identity:C,state:L.state,...L.detail?{detail:L.detail}:{},...g.email?{email:g.email}:{}})})().catch(C=>{console.warn(`[agent-auth] probe skipped: ${C instanceof Error?C.message:String(C)}`)});let p=!1,d=new AbortController,f=new Map,m=null,y=null,b=!1,w=()=>{let C=u.openControlSocket();return m=C,C.on("open",()=>{console.log("[ws] connected");let g={type:"sandbox_hello",platformVersion:et,protocolVersion:$t};C.send(JSON.stringify(g))}),C.on("message",g=>{let B=g.toString("utf-8"),L=null;try{let q=JSON.parse(B);q&&typeof q=="object"&&(L=q)}catch{}if(L&&L.type==="hello"){let q=L;y=bo(q.protocolVersion);let te=y?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${q.platformVersion} (protocol ${q.protocolVersion}) \u2014 ${te}`),y&&(b=!1);return}if(L&&L.type==="pause_job"){let q=typeof L.jobId=="string"?L.jobId:"",te=q?f.get(q):void 0;te?(console.warn(`[ws] pause_job ${q} \u2014 aborting agent`),te.paused=!0,te.abort.abort()):console.log(`[ws] pause_job ${q} \u2014 not a running job, ignoring`),q&&C.send(JSON.stringify({type:"job_paused",jobId:q}));return}if(L&&(L.type==="chat_user_message"||L.type==="chat_finalize")){let q=typeof L.jobId=="string"?L.jobId:"",te=q?f.get(q):void 0;if(te?.chatInbox)if(L.type==="chat_user_message"){let de=typeof L.text=="string"?L.text:"";de.trim()&&te.chatInbox.push({kind:"user",text:de})}else te.chatInbox.finalize();else console.log(`[ws] ${String(L.type)} ${q} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${B}`)}),C.on("close",(g,B)=>{console.log(`[ws] closed code=${g} reason=${B?.toString()||""}`),m===C&&(m=null),!p&&setTimeout(w,2e3)}),C.on("error",g=>console.warn(`[ws] error: ${g.message}`)),C},k=w(),x=async C=>{for(;!p;){if(y===!1){b||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${et}, protocol ${$t}) \u2014 not claiming jobs until versions align.`),b=!0),await new Promise(g=>setTimeout(g,5e3));continue}try{let g=await u.claim(d.signal,C);if(g.status===204)continue;if(g.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(!g.ok){console.warn(`[claim:${C}] ${g.status} \u2014 backoff 5s`),await new Promise(L=>setTimeout(L,5e3));continue}let B=await g.json();await h(u,B)}catch(g){if(d.signal.aborted)break;let B=g instanceof Error?g.message:String(g);console.warn(`[claim:${C}] error: ${B} \u2014 backoff 5s`),await new Promise(L=>setTimeout(L,5e3))}}};async function h(C,g){let B={abort:new AbortController,paused:!1};za(g.role)&&(B.chatInbox=hA()),f.set(g.jobId,B);let L=!1,q=null,te=null,de=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),wt=async()=>{try{await C.heartbeat(g.jobId)==="claim_lost"&&(L=!0,console.warn(`[job] ${g.jobId} claim lost \u2014 HUB sweeper took it`))}catch($){let P=$ instanceof Error?$.message:String($);console.warn(`[job] ${g.jobId} heartbeat error: ${P}`)}};wt();let Ft=setInterval(()=>{wt()},de),we=new Date().toISOString();console.log(`[job] ${g.jobId} claimed \u2014 role=${g.role} task=${g.taskId} phase=${g.phase}`),console.log(`[job] ${g.jobId} prompt (${g.prompt.length} chars):`),console.log(R(g.prompt," \u2502 "));let We=[],Be=null,bt=400,Ie=25,st=500,kt=()=>{if(Be&&(clearTimeout(Be),Be=null),We.length===0)return;let $=We.splice(0,We.length),P=m;if(!P||P.readyState!==P.OPEN)return;let S={type:"agent_activity",jobId:g.jobId,taskId:g.taskId,projectId:g.projectId,role:g.role,phase:g.phase,events:$};try{P.send(JSON.stringify(S))}catch{}},er=$=>{We.push($),We.length>st&&We.shift(),We.length>=Ie?kt():Be||(Be=setTimeout(kt,bt))},U=g.role==="analysis"&&g.taskId.startsWith("draft::")?g.taskId.slice(7):null,K=new Set,D=null;try{if(!c){L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:we,finishedAt:new Date().toISOString()});return}if(!wu(o,g.provider??null)){L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${g.provider??"claude"}"`},startedAt:we,finishedAt:new Date().toISOString()});return}let $=eb(g.jobId);console.log(`[job] ${g.jobId} workspace=${$.dir}`);let P=T(g,r);q=P.gitCreds,te=P.contextGitCreds;let S=q?.env,I=P.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:P.claudeOauthToken}:void 0,F=[],V=null,he=null;try{let j=g.role==="build"?"clone":"worktree";F=await Bw($.dir,g.projectId,g.projectRepos,j,S,n);let O=await Fw($.dir,g.projectId,g.contextRepo,"worktree",S,n);he=O,V=O?.workspacePath??null}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} materialize failed: ${O}`),L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${O}`},startedAt:we,finishedAt:new Date().toISOString()}),$.dispose();return}let on=g.model,go=g.effort;g.role==="build"&&g.modelDiscovery&&!Hw(V)&&(on=g.modelDiscovery,go=g.effortDiscovery,console.log(`[job] ${g.jobId} BUILD discovery (no steps in ${Pu}) \u2014 model=${on}`));let $d=async()=>{if(!g.deliveries||g.deliveries.length===0)return[];let j=g.contextRepo?.cloneUrl;if(!j||!S)throw new Error(j?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let O=[];for(let H of g.deliveries){let Y=F.find(Z=>Z.name===H.name);if(Y){if(g.role==="implement"&&H.baseSha&&H.baseSha!==Y.baseSha){let Z=await Nw(Y,H.deliveryRef,H.deliverySha,H.baseSha,j,S);console.log(`[job] ${g.jobId} ${Y.name}: base moved ${H.baseSha.slice(0,10)} \u2192 ${Y.baseSha.slice(0,10)} \u2014 re-applied delivery ${H.deliverySha.slice(0,10)} (${Z.length} conflicted file(s))`),Z.length>0&&O.push(`- **${Y.name}**:`,...Z.map(pe=>` - \`${pe}\``));continue}await jw(Y,H.deliveryRef,H.deliverySha,j,S),console.log(`[job] ${g.jobId} ${Y.name}: checked out delivery ${H.deliverySha.slice(0,10)} for ${g.role}`)}}return O},xa=[];if(g.role==="build"||g.role==="implement"||g.role==="code-review")try{xa=await $d()}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} delivery checkout failed: ${O}`),L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${O}`},startedAt:we,finishedAt:new Date().toISOString()}),$.dispose();return}if(g.role==="code-review"){let j=g.metadata?.externalReview===!0;for(let O of F)try{if(j){let H=g.projectRepos.find(Z=>Z.name===O.name)?.defaultBranch??O.ref,Y=await Mw(O,H,S);Y?console.log(`[job] ${g.jobId} ${O.name}: review base ${Y.slice(0,10)} (merge-base with ${H})`):console.warn(`[job] ${g.jobId} ${O.name}: no merge-base with ${H} \u2014 review base not pinned (agent falls back to manual deepen)`)}else await Cu(O,O.baseSha,S),console.log(`[job] ${g.jobId} ${O.name}: review base ${O.baseSha.slice(0,10)} (pre-delivery)`)}catch(H){let Y=H instanceof Error?H.message:String(H);console.warn(`[job] ${g.jobId} ${O.name}: review-base pin failed: ${Y}`)}}let Sa=g.role==="resolve-conflict"?g.metadata?.mergeBranchByRepo??g.metadata?.taskBranchByRepo??{}:{},xd="";if(g.role==="resolve-conflict"){if(!F.some(j=>Sa[j.name])){let j="resolve-conflict job carries no branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${g.jobId} ${j}`),L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:j},startedAt:we,finishedAt:new Date().toISOString()}),$.dispose();return}try{let j=[];for(let O of F){let H=Sa[O.name];if(!H)continue;let Y=await Iu(O,H,S);console.log(`[job] ${g.jobId} ${O.name}: merged ${H} into ${O.ref} \u2014 ${Y.length} conflicted file(s)`),Y.length>0?j.push(`- **${O.name}**:`,...Y.map(Z=>` - \`${Z}\``)):j.push(`- **${O.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}xd=`
988
+ ${i}`}function FA(){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 bi(t={}){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=lw(t.profile,e.sandboxId,!!ee("SANDBOX_CONFIG")),s=vt(DA(),".codepipe","logs"),a=zi("SANDBOX_LOG",i,s);if(a.enabled){let C=new Dn(a);Xi(C),console.log(`[log] file logging \u2192 ${C.path} (rotate at ${a.maxBytes}B, keep ${a.maxFiles})`)}console.log(`codepipe-sandbox v${ot} (protocol ${Rt})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let c=xw(e.llm);console.log(`llm backend: ${c?c.name():"(none \u2014 will not claim agent jobs)"}`);let l=Pu();console.log(`llm retry: maxAttempts=${l.maxAttempts} backoff=${l.baseDelayMs}\u2013${l.maxDelayMs}ms budget=${l.totalBudgetMs}ms`);let u=new to(e.hubUrl,e.token);e.llm==="claude-headless"&&(async()=>{let{identity:C,login:g}=Ew(),B=await u.reportAgentAuth({identity:C,login:g!==null,...g?.email?{email:g.email}:{}});if(!g){console.warn("[agent-auth] this host is not logged into Claude Code \u2014 run `claude` and sign in, or set a project token with `codepipe login`");return}if(!B)return;let L=await Rw();console.log(`[agent-auth] probe: ${L.state}${L.detail?` (${L.detail})`:""}`),await u.reportAgentAuthResult({identity:C,state:L.state,...L.detail?{detail:L.detail}:{},...g.email?{email:g.email}:{}})})().catch(C=>{console.warn(`[agent-auth] probe skipped: ${C instanceof Error?C.message:String(C)}`)});let p=!1,d=new AbortController,f=new Map,m=null,y=null,b=!1,w=()=>{let C=u.openControlSocket();return m=C,C.on("open",()=>{console.log("[ws] connected");let g={type:"sandbox_hello",platformVersion:ot,protocolVersion:Rt};C.send(JSON.stringify(g))}),C.on("message",g=>{let B=g.toString("utf-8"),L=null;try{let q=JSON.parse(B);q&&typeof q=="object"&&(L=q)}catch{}if(L&&L.type==="hello"){let q=L;y=Eo(q.protocolVersion);let te=y?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${q.platformVersion} (protocol ${q.protocolVersion}) \u2014 ${te}`),y&&(b=!1);return}if(L&&L.type==="pause_job"){let q=typeof L.jobId=="string"?L.jobId:"",te=q?f.get(q):void 0;te?(console.warn(`[ws] pause_job ${q} \u2014 aborting agent`),te.paused=!0,te.abort.abort()):console.log(`[ws] pause_job ${q} \u2014 not a running job, ignoring`),q&&C.send(JSON.stringify({type:"job_paused",jobId:q}));return}if(L&&(L.type==="chat_user_message"||L.type==="chat_finalize")){let q=typeof L.jobId=="string"?L.jobId:"",te=q?f.get(q):void 0;if(te?.chatInbox)if(L.type==="chat_user_message"){let le=typeof L.text=="string"?L.text:"";le.trim()&&te.chatInbox.push({kind:"user",text:le})}else te.chatInbox.finalize();else console.log(`[ws] ${String(L.type)} ${q} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${B}`)}),C.on("close",(g,B)=>{console.log(`[ws] closed code=${g} reason=${B?.toString()||""}`),m===C&&(m=null),!p&&setTimeout(w,2e3)}),C.on("error",g=>console.warn(`[ws] error: ${g.message}`)),C},k=w(),x=async C=>{for(;!p;){if(y===!1){b||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ot}, protocol ${Rt}) \u2014 not claiming jobs until versions align.`),b=!0),await new Promise(g=>setTimeout(g,5e3));continue}try{let g=await u.claim(d.signal,C);if(g.status===204)continue;if(g.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(!g.ok){console.warn(`[claim:${C}] ${g.status} \u2014 backoff 5s`),await new Promise(L=>setTimeout(L,5e3));continue}let B=await g.json();await h(u,B)}catch(g){if(d.signal.aborted)break;let B=g instanceof Error?g.message:String(g);console.warn(`[claim:${C}] error: ${B} \u2014 backoff 5s`),await new Promise(L=>setTimeout(L,5e3))}}};async function h(C,g){let B={abort:new AbortController,paused:!1};nc(g.role)&&(B.chatInbox=FA()),f.set(g.jobId,B);let L=!1,q=null,te=null,le=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),ut=async()=>{try{await C.heartbeat(g.jobId)==="claim_lost"&&(L=!0,console.warn(`[job] ${g.jobId} claim lost \u2014 HUB sweeper took it`))}catch($){let _=$ instanceof Error?$.message:String($);console.warn(`[job] ${g.jobId} heartbeat error: ${_}`)}};ut();let Wt=setInterval(()=>{ut()},le),we=new Date().toISOString();console.log(`[job] ${g.jobId} claimed \u2014 role=${g.role} task=${g.taskId} phase=${g.phase}`),console.log(`[job] ${g.jobId} prompt (${g.prompt.length} chars):`),console.log(R(g.prompt," \u2502 "));let Ke=[],_e=null,xt=400,Ie=25,dt=500,St=()=>{if(_e&&(clearTimeout(_e),_e=null),Ke.length===0)return;let $=Ke.splice(0,Ke.length),_=m;if(!_||_.readyState!==_.OPEN)return;let S={type:"agent_activity",jobId:g.jobId,taskId:g.taskId,projectId:g.projectId,role:g.role,phase:g.phase,events:$};try{_.send(JSON.stringify(S))}catch{}},Nr=$=>{Ke.push($),Ke.length>dt&&Ke.shift(),Ke.length>=Ie?St():_e||(_e=setTimeout(St,xt))},U=g.role==="analysis"&&g.taskId.startsWith("draft::")?g.taskId.slice(7):null,K=new Set,D=null;try{if(!c){L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:we,finishedAt:new Date().toISOString()});return}if(!Cu(o,g.provider??null)){L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`llm provider mismatch: worker backend "${o}" does not serve provider "${g.provider??"claude"}"`},startedAt:we,finishedAt:new Date().toISOString()});return}let $=kb(g.jobId);console.log(`[job] ${g.jobId} workspace=${$.dir}`);let _=T(g,r);q=_.gitCreds,te=_.contextGitCreds;let S=q?.env,I=_.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:_.claudeOauthToken}:void 0,F=[],V=null,he=null;try{let j=g.role==="build"?"clone":"worktree";F=await sb($.dir,g.projectId,g.projectRepos,j,S,n);let O=await ab($.dir,g.projectId,g.contextRepo,"worktree",S,n);he=O,V=O?.workspacePath??null}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} materialize failed: ${O}`),L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${O}`},startedAt:we,finishedAt:new Date().toISOString()}),$.dispose();return}let fn=g.model,$o=g.effort;g.role==="build"&&g.modelDiscovery&&!ub(V)&&(fn=g.modelDiscovery,$o=g.effortDiscovery,console.log(`[job] ${g.jobId} BUILD discovery (no steps in ${Fu}) \u2014 model=${fn}`));let Nd=async()=>{if(!g.deliveries||g.deliveries.length===0)return[];let j=g.contextRepo?.cloneUrl;if(!j||!S)throw new Error(j?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let O=[];for(let H of g.deliveries){let Y=F.find(Z=>Z.name===H.name);if(Y){if(g.role==="implement"&&H.baseSha&&H.baseSha!==Y.baseSha){let Z=await eb(Y,H.deliveryRef,H.deliverySha,H.baseSha,j,S);console.log(`[job] ${g.jobId} ${Y.name}: base moved ${H.baseSha.slice(0,10)} \u2192 ${Y.baseSha.slice(0,10)} \u2014 re-applied delivery ${H.deliverySha.slice(0,10)} (${Z.length} conflicted file(s))`),Z.length>0&&O.push(`- **${Y.name}**:`,...Z.map(pe=>` - \`${pe}\``));continue}await Qw(Y,H.deliveryRef,H.deliverySha,j,S),console.log(`[job] ${g.jobId} ${Y.name}: checked out delivery ${H.deliverySha.slice(0,10)} for ${g.role}`)}}return O},Aa=[];if(g.role==="build"||g.role==="implement"||g.role==="code-review")try{Aa=await Nd()}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} delivery checkout failed: ${O}`),L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${O}`},startedAt:we,finishedAt:new Date().toISOString()}),$.dispose();return}if(g.role==="code-review"){let j=g.metadata?.externalReview===!0;for(let O of F)try{if(j){let H=g.projectRepos.find(Z=>Z.name===O.name)?.defaultBranch??O.ref,Y=await nb(O,H,S);Y?console.log(`[job] ${g.jobId} ${O.name}: review base ${Y.slice(0,10)} (merge-base with ${H})`):console.warn(`[job] ${g.jobId} ${O.name}: no merge-base with ${H} \u2014 review base not pinned (agent falls back to manual deepen)`)}else await Bu(O,O.baseSha,S),console.log(`[job] ${g.jobId} ${O.name}: review base ${O.baseSha.slice(0,10)} (pre-delivery)`)}catch(H){let Y=H instanceof Error?H.message:String(H);console.warn(`[job] ${g.jobId} ${O.name}: review-base pin failed: ${Y}`)}}let _a=g.role==="resolve-conflict"?g.metadata?.mergeBranchByRepo??g.metadata?.taskBranchByRepo??{}:{},Od="";if(g.role==="resolve-conflict"){if(!F.some(j=>_a[j.name])){let j="resolve-conflict job carries no branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${g.jobId} ${j}`),L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:j},startedAt:we,finishedAt:new Date().toISOString()}),$.dispose();return}try{let j=[];for(let O of F){let H=_a[O.name];if(!H)continue;let Y=await Uu(O,H,S);console.log(`[job] ${g.jobId} ${O.name}: merged ${H} into ${O.ref} \u2014 ${Y.length} conflicted file(s)`),Y.length>0?j.push(`- **${O.name}**:`,...Y.map(Z=>` - \`${Z}\``)):j.push(`- **${O.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}Od=`
975
989
 
976
990
  ## Conflicts to resolve
977
991
 
978
992
  `+(j.length>0?j.join(`
979
993
  `):"(no task branches to merge)")+`
980
- `}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} conflict merge failed: ${O}`),L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${O}`},startedAt:we,finishedAt:new Date().toISOString()}),$.dispose();return}}let Ea=null,Sd="";if(g.contextPack&&V)try{let{assembleContextPack:j}=await Promise.resolve().then(()=>(Eb(),Sb)),O=j({contextDir:V,taskKey:String(g.metadata?.trackerIssueKey??g.taskId.split(":")[1]??""),title:String(g.metadata?.taskTitle??""),repoDirs:new Map(F.map(H=>[H.name,H.workspacePath])),idfPenalty:g.contextPackIdf!==!1});O?(qu(gt($.dir,"meta"),{recursive:!0}),Yu(gt($.dir,"meta","context-pack.md"),O.markdown),Ea=O.markdown,Sd=O.top??"",console.log(`[job] ${g.jobId} context pack: ${O.markdown.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${g.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} context pack failed (non-fatal): ${O}`)}let Ed="",Cr=null,yo=null;try{let{loadSkills:j,materializeSkills:O,renderSkillsBlock:H}=await Promise.resolve().then(()=>(Pb(),Cb)),Y=g.skills??{bundled:!0,context:!0,repo:!0},Z=j({contextDir:V,repoDirs:F.map(at=>at.workspacePath),sources:Y});for(let at of Z.errors)console.warn(`[job] ${g.jobId} skill ${at.source}: ${at.error}`);let pe=O($.dir,Z.skills),ne=["implement","rework","testing"].includes(g.role)?$c(vc(_(V,g.taskId))):[];Ed=H(Z.skills,ne),pe.length>0&&console.log(`[job] ${g.jobId} skills: ${Z.skills.map(at=>at.name).join(", ")}`);let{parseMarketplaces:ge,enabledPluginsSetting:an}=await Promise.resolve().then(()=>(M(),Oc)),{sources:cn,errors:wo}=ge(Y.marketplaces??[]);for(let at of wo)console.warn(`[job] ${g.jobId} marketplace ${at}`);if(cn.length>0&&(Y.plugins??[]).length>0){let{seedMarketplaces:at}=await Promise.resolve().then(()=>(Ob(),Nb)),ln=await at(cn);for(let z of ln.errors)console.warn(`[job] ${g.jobId} marketplace ${z.repo}: ${z.error}`);let{enabled:un,unknown:dn}=an(Y.plugins??[],ln.ready);for(let z of dn)console.warn(`[job] ${g.jobId} plugin ${z}: no such marketplace in this project`);ln.dir&&Object.keys(un).length>0&&(Cr=ln.dir,yo={enabledPlugins:un},console.log(`[job] ${g.jobId} plugins: ${Object.keys(un).join(", ")}`))}}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} skills unavailable (non-fatal): ${O}`)}let Rd="",qe=null,Td=g.role==="council"&&Array.isArray(g.metadata?.questions)?g.metadata.questions.filter(j=>typeof j=="string"&&j.trim().length>0):[],Yv=g.metadata?.reviewVerify===!0||g.metadata?.externalReviewVerify===!0;if((g.role==="council"||g.role==="code-review")&&g.council&&!Yv)try{let{loadRoles:j}=await Promise.resolve().then(()=>(Fu(),Bu)),{rolesForScenario:O}=await Promise.resolve().then(()=>(M(),Oc)),H=await Promise.resolve().then(()=>(Ku(),Gu)),Y=j(V);for(let Z of Y.errors)console.warn(`[job] ${g.jobId} role ${Z.file}: ${Z.error}`);if(g.role==="council"&&Td.length>0){let Z=O(Y.roles,"council");if(Z.length>=2){let pe=Td.map((ne,ge)=>`${ge+1}. ${ne}`).join(`
981
- `);qe={roles:Z,artifactDir:"council",promptFor:(ne,ge)=>H.renderCouncilRolePrompt(ne,pe,V,ge),opinionsBlock:H.renderOpinionsBlock,onAllFailed:"fail",verdictFile:"meta/council-answer.json"}}}else if(g.role==="code-review"){let Z=O(Y.roles,"code_review");if(Z.length>=2){let pe=typeof g.metadata?.buildReportBlock=="string"?g.metadata.buildReportBlock:"";qe={roles:Z,artifactDir:"code-review",promptFor:(ne,ge)=>H.renderReviewRolePrompt(ne,pe,V,ge),opinionsBlock:H.renderReviewOpinionsBlock,onAllFailed:"solo",verdictFile:"meta/review-result.json"}}}qe&&console.log(`[job] ${g.jobId} council convened (${qe.artifactDir}): ${qe.roles.map(Z=>Z.name).join(", ")}`)}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} council roles unavailable (non-fatal, solo): ${O}`)}if((g.role==="council"||g.role==="code-review")&&!qe)console.log(`[job] ${g.jobId} ${g.role}: solo session (no council convened)`);else if(["analyze","testing"].includes(g.role))try{let{loadRoles:j}=await Promise.resolve().then(()=>(Fu(),Bu)),{materializeRoleAgents:O,renderRolesBlock:H}=await Promise.resolve().then(()=>(Kb(),Gb)),Y=j(V);for(let ge of Y.errors)console.warn(`[job] ${g.jobId} role ${ge.file}: ${ge.error}`);let Z=g.role==="analyze"?"plan_review":"code_review",pe=g.role==="analyze"?"plan-review":"testing",ne=O($.dir,Y.roles,Z,V);Rd=H(ne,pe),console.log(`[job] ${g.jobId} review roles: ${ne.roles.length>0?ne.roles.map(ge=>ge.name).join(", "):"(no roles)"}`)}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} review roles unavailable (non-fatal): ${O}`)}let Vv=xa.length>0?`
994
+ `}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} conflict merge failed: ${O}`),L||await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${O}`},startedAt:we,finishedAt:new Date().toISOString()}),$.dispose();return}}let ja=null,Ld="";if(g.contextPack&&V)try{let{assembleContextPack:j}=await Promise.resolve().then(()=>(Wb(),Hb)),O=j({contextDir:V,taskKey:String(g.metadata?.trackerIssueKey??g.taskId.split(":")[1]??""),title:String(g.metadata?.taskTitle??""),repoDirs:new Map(F.map(H=>[H.name,H.workspacePath])),idfPenalty:g.contextPackIdf!==!1});O?(nd(vt($.dir,"meta"),{recursive:!0}),od(vt($.dir,"meta","context-pack.md"),O.markdown),ja=O.markdown,Ld=O.top??"",console.log(`[job] ${g.jobId} context pack: ${O.markdown.length} chars \u2192 meta/context-pack.md`)):console.log(`[job] ${g.jobId} context pack: model empty or no signal \u2014 skipped`)}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} context pack failed (non-fatal): ${O}`)}let Md="",Or=null,xo=null;try{let{loadSkills:j,materializeSkills:O,renderSkillsBlock:H}=await Promise.resolve().then(()=>(Xb(),zb)),Y=g.skills??{bundled:!0,context:!0,repo:!0},Z=j({contextDir:V,repoDirs:F.map(pt=>pt.workspacePath),sources:Y});for(let pt of Z.errors)console.warn(`[job] ${g.jobId} skill ${pt.source}: ${pt.error}`);let pe=O($.dir,Z.skills),ne=["implement","rework","testing"].includes(g.role)?Mc(Lc(P(V,g.taskId))):[];Md=H(Z.skills,ne),pe.length>0&&console.log(`[job] ${g.jobId} skills: ${Z.skills.map(pt=>pt.name).join(", ")}`);let{parseMarketplaces:ge,enabledPluginsSetting:hn}=await Promise.resolve().then(()=>(M(),Kc)),{sources:gn,errors:So}=ge(Y.marketplaces??[]);for(let pt of So)console.warn(`[job] ${g.jobId} marketplace ${pt}`);if(gn.length>0&&(Y.plugins??[]).length>0){let{seedMarketplaces:pt}=await Promise.resolve().then(()=>(tk(),ek)),yn=await pt(gn);for(let z of yn.errors)console.warn(`[job] ${g.jobId} marketplace ${z.repo}: ${z.error}`);let{enabled:wn,unknown:bn}=hn(Y.plugins??[],yn.ready);for(let z of bn)console.warn(`[job] ${g.jobId} plugin ${z}: no such marketplace in this project`);yn.dir&&Object.keys(wn).length>0&&(Or=yn.dir,xo={enabledPlugins:wn},console.log(`[job] ${g.jobId} plugins: ${Object.keys(wn).join(", ")}`))}}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} skills unavailable (non-fatal): ${O}`)}let Dd="",Xe=null,Ud=g.role==="council"&&Array.isArray(g.metadata?.questions)?g.metadata.questions.filter(j=>typeof j=="string"&&j.trim().length>0):[],p$=g.metadata?.reviewVerify===!0||g.metadata?.externalReviewVerify===!0;if((g.role==="council"||g.role==="code-review")&&g.council&&!p$)try{let{loadRoles:j}=await Promise.resolve().then(()=>(Zu(),Ju)),{rolesForScenario:O}=await Promise.resolve().then(()=>(M(),Kc)),H=await Promise.resolve().then(()=>(ed(),Qu)),Y=j(V);for(let Z of Y.errors)console.warn(`[job] ${g.jobId} role ${Z.file}: ${Z.error}`);if(g.role==="council"&&Ud.length>0){let Z=O(Y.roles,"council");if(Z.length>=2){let pe=Ud.map((ne,ge)=>`${ge+1}. ${ne}`).join(`
995
+ `);Xe={roles:Z,artifactDir:"council",promptFor:(ne,ge)=>H.renderCouncilRolePrompt(ne,pe,V,ge),opinionsBlock:H.renderOpinionsBlock,onAllFailed:"fail",verdictFile:"meta/council-answer.json"}}}else if(g.role==="code-review"){let Z=O(Y.roles,"code_review");if(Z.length>=2){let pe=typeof g.metadata?.buildReportBlock=="string"?g.metadata.buildReportBlock:"";Xe={roles:Z,artifactDir:"code-review",promptFor:(ne,ge)=>H.renderReviewRolePrompt(ne,pe,V,ge),opinionsBlock:H.renderReviewOpinionsBlock,onAllFailed:"solo",verdictFile:"meta/review-result.json"}}}Xe&&console.log(`[job] ${g.jobId} council convened (${Xe.artifactDir}): ${Xe.roles.map(Z=>Z.name).join(", ")}`)}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} council roles unavailable (non-fatal, solo): ${O}`)}if((g.role==="council"||g.role==="code-review")&&!Xe)console.log(`[job] ${g.jobId} ${g.role}: solo session (no council convened)`);else if(["analyze","testing"].includes(g.role))try{let{loadRoles:j}=await Promise.resolve().then(()=>(Zu(),Ju)),{materializeRoleAgents:O,renderRolesBlock:H}=await Promise.resolve().then(()=>(lk(),ck)),Y=j(V);for(let ge of Y.errors)console.warn(`[job] ${g.jobId} role ${ge.file}: ${ge.error}`);let Z=g.role==="analyze"?"plan_review":"code_review",pe=g.role==="analyze"?"plan-review":"testing",ne=O($.dir,Y.roles,Z,V);Dd=H(ne,pe),console.log(`[job] ${g.jobId} review roles: ${ne.roles.length>0?ne.roles.map(ge=>ge.name).join(", "):"(no roles)"}`)}catch(j){let O=j instanceof Error?j.message:String(j);console.warn(`[job] ${g.jobId} review roles unavailable (non-fatal): ${O}`)}let f$=Aa.length>0?`
982
996
 
983
997
  ## Base branch moved \u2014 conflicts to resolve
984
998
 
985
999
  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:
986
1000
 
987
- `+xa.join(`
1001
+ `+Aa.join(`
988
1002
  `)+`
989
- `:"",Id=N(v(g.prompt,F,V).replace(/\{\{contextPackTop\}\}/g,()=>Sd),V,g.taskId).replace(/\{\{skillsBlock\}\}/g,Ed)+xd+Vv,Si=Id.replace(/\{\{rolesBlock\}\}/g,()=>Rd),sn=[...F.map(j=>j.workspacePath),...V?[V]:[]];if(sn.length>0&&console.log(`[job] ${g.jobId} --add-dir: ${sn.join(", ")}`),xu("agent-request")){let j=Vs(Jn(g.metadata??{})),O=Su(g.projectId,g.jobId,"agent-request",[`# Agent request \u2014 job ${g.jobId}`,"",`- project: ${g.projectId}`,`- task: ${g.taskId}`,`- role: ${g.role}`,`- model: ${on??"(backend default)"}`,`- effort: ${go??"(backend default)"}`,`- add-dirs:${sn.length>0?"":" (none)"}`,...sn.map(H=>` - ${H}`),"","## Append-system-prompt (language directive)","","```",j,"```","","## Prompt","",Si,"",...Ea?["## Context pack (meta/context-pack.md)","",Ea]:["## Context pack","","(not generated for this job)"],""].join(`
990
- `));O&&console.log(`[debug] ${g.jobId} agent request \u2192 ${O}`)}U&&(D=setInterval(()=>{let O=m;if(!O||O.readyState!==O.OPEN)return;let H;try{H=uA(gt($.dir,"drafts")).filter(Y=>Y.endsWith(".json")).sort()}catch{return}for(let Y of H){if(K.has(Y))continue;if(K.size>=Nc)break;let Z;try{let ne=JSON.parse(sa(gt($.dir,"drafts",Y),"utf-8")),ge=typeof ne.localRef=="string"?ne.localRef:"",an=typeof ne.title=="string"?ne.title:"",cn=typeof ne.body=="string"?ne.body:"";if(!ge||!an)continue;Z={localRef:ge,title:an,body:cn,...ne.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ne.links)?{links:ne.links}:{}}}catch{continue}K.add(Y);let pe={type:"child_draft",jobId:g.jobId,projectId:g.projectId,draftId:U,child:Z};try{O.send(JSON.stringify(pe))}catch{}}},1500));let Pr=null,Cd=new Map;try{if(qe){let{runCouncil:z,COUNCIL_DEFAULT_MAX_PARALLEL:le}=await Promise.resolve().then(()=>(Ku(),Gu)),_e=await z({roles:qe.roles,artifactDir:qe.artifactDir,promptFor:qe.promptFor,maxParallel:g.council?.maxParallel??le,defaultModel:on,effort:go,baseInput:{workspaceDir:$.dir,addDirs:sn,metadata:g.metadata??{},...I||Cr?{env:{...I??{},...Cr?{CLAUDE_CODE_PLUGIN_SEED_DIR:Cr}:{}}}:{},...yo?{settings:yo}:{},signal:B.abort.signal,onActivity:er},runnerFor:fe=>(fe&&!wu(o,fe)&&console.warn(`[job] ${g.jobId} council role provider "${fe}" not served by backend "${o}" \u2014 using the default backend`),c),log:fe=>console.log(`[job] ${g.jobId} council ${fe}`)});Pr=_e.usage;let tr=_e.opinions.some(fe=>fe.ok);if(!tr&&qe.onAllFailed==="fail")throw new Error(`council: every role failed \u2014 ${_e.opinions.map(fe=>`${fe.role}: ${fe.error??"?"}`).join("; ")}`);if(tr){Si=Id.replace(/\{\{rolesBlock\}\}/g,()=>qe.opinionsBlock(_e.opinions));for(let fe of $.listFiles().filter(ct=>ct.startsWith(`${qe.artifactDir}/`)))Cd.set(fe,$.readFile(fe))}else console.warn(`[job] ${g.jobId} council produced no opinions \u2014 proceeding solo (${_e.opinions.map(fe=>`${fe.role}: ${fe.error??"?"}`).join("; ")})`);if(dA(gt($.dir,qe.verdictFile),{force:!0}),xu("agent-request")){let fe=Su(g.projectId,g.jobId,"agent-request-synthesis",Si);fe&&console.log(`[debug] ${g.jobId} council synthesis request \u2192 ${fe}`)}}let j={workspaceDir:$.dir,role:g.role,prompt:Si,addDirs:sn,metadata:g.metadata??{},...on?{model:on}:{},...go?{effort:go}:{},...I||Cr?{env:{...I??{},...Cr?{CLAUDE_CODE_PLUGIN_SEED_DIR:Cr}:{}}}:{},...yo?{settings:yo}:{},signal:B.abort.signal,onActivity:er},O=B.chatInbox?await c.run({...j,interactive:{inbox:B.chatInbox.iterable}}):await vu(c,j,{jobId:g.jobId,policy:l,onBeforeRetry:async()=>{$.clean();for(let[z,le]of Cd){let _e=gt($.dir,z);qu(Xb(_e),{recursive:!0}),Yu(_e,le)}for(let z of F)try{await Iw(z);let le=Sa[z.name];g.role==="resolve-conflict"&&le&&await Iu(z,le,S)}catch(le){let _e=le instanceof Error?le.message:String(le);console.warn(`[job] ${g.jobId} worktree reset failed (${z.name}): ${_e}`)}try{await $d()}catch(z){let le=z instanceof Error?z.message:String(z);console.warn(`[job] ${g.jobId} delivery re-checkout failed: ${le}`)}},aborted:()=>L||B.paused});if(Pr){let{addUsageInto:z}=await Promise.resolve().then(()=>(ai(),$u));z(O.usage,Pr)}let H=[];if(fA.has(g.role)&&F.length>0){let z=g.metadata??{},le=typeof z.commitMessage=="string"?z.commitMessage:`${g.taskId}: changes`,_e=g.contextRepo?.cloneUrl,tr=te?.env;if(!_e||!tr)throw new Error("delivery requested but "+(_e?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let fe=g.taskId.includes(":")?g.taskId.slice(g.taskId.indexOf(":")+1):g.taskId;for(let ct of F){let pn=await Cw(ct,le);if(!pn){console.log(`[job] ${g.jobId} ${ct.name}: no changes \u2014 no delivery`);continue}let Ra=`codepipe/deliveries/${fe}/${g.jobId}/${ct.name}`;await Pw(ct,pn,Ra,_e,tr);let zv=await _w(ct,pn);H.push({name:ct.name,deliveryRef:Ra,deliverySha:pn,baseSha:ct.baseSha,changedFiles:zv}),console.log(`[job] ${g.jobId} ${ct.name}: delivered ${pn.slice(0,10)} \u2192 ${Ra}`);let Pd=await Aw(ct,pn);if(Pd.trim().length>0){let Xv=gt("display",`${ct.name}.diff`),Ad=gt($.dir,Xv);qu(Xb(Ad),{recursive:!0}),Yu(Ad,Pd)}}}if(g.role==="resolve-conflict"&&H.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's SOLUTION.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let Y;g.role==="build"&&(Y=qw($.dir),console.log(`[job] ${g.jobId} build verdict: ok=${Y.ok}`+(Y.failedStep?` failedStep=${Y.failedStep}`:"")));let Z;if(g.role==="code-review"){Z=_u($.dir),console.log(`[job] ${g.jobId} review verdict: approved=${Z.approved}`);try{let{parseChangedRanges:z,markFindingScope:le}=await Promise.resolve().then(()=>(ju(),Vw)),_e=new Map;for(let tr of F)try{let fe=await Lw(tr,S);_e.set(tr.name,z(fe))}catch{}le(Z,_e,F.length===1?F[0].name:void 0)}catch(z){console.warn(`[job] ${g.jobId} finding scope marking failed (non-fatal): ${String(z)}`)}}let pe;if(g.role==="council"){let{readCouncilVerdict:z}=await Promise.resolve().then(()=>(qb(),Wb));pe=z($.dir)??void 0,console.log(`[job] ${g.jobId} council: ${pe?"answered":"no verdict \u2014 task stops for a human"}`)}let ne;if(g.role==="testing"){try{let z=sa(gt($.dir,"meta","test-result.json"),"utf-8");ne=JSON.parse(z)}catch{ne=void 0}console.log(`[job] ${g.jobId} test verdict: ${ne?"written":"none \u2014 proceeding to the PR"}`)}let ge;if(g.role==="observer"){let{readQueuePlan:z}=await Promise.resolve().then(()=>(zb(),Vb));ge=z($.dir)??void 0,console.log(`[job] ${g.jobId} queue plan: ${ge?"produced":"none \u2014 batch keeps the staged order"}`)}let an=O.artifactPaths.length>0?O.artifactPaths:$.listFiles(),cn=Array.from(new Set(an)),wo;if(he)try{let z=g.role==="index"?["adr/SOURCES.md"]:g.role==="backfill"?["adr"]:[],le=await Gw(he,z);le.length>0&&(wo=le,console.log(`[job] ${g.jobId} captured ${le.length} knowledge file(s) for Context Repo`))}catch(z){let le=z instanceof Error?z.message:String(z);console.warn(`[job] ${g.jobId} knowledge capture failed (non-fatal): ${le}`)}let{artifacts:at,omitted:ln,dropped:un}=Xw($.dir,cn);for(let z of ln)console.warn(`[job] ${g.jobId} artifact ${z.path} (${z.bytes} bytes) exceeded upload budget \u2014 content omitted`);un.length>0&&console.warn(`[job] ${g.jobId} artifact listing truncated: ${un.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let dn={jobId:g.jobId,status:"succeeded",artifacts:at,...wo?{contextWrites:wo}:{},...H.length>0?{deliveries:H}:{},log:mA(O.log),startedAt:we,finishedAt:new Date().toISOString(),usage:O.usage,...O.rateLimit?{rateLimit:O.rateLimit}:{},...Y?{build:Y}:{},...Z?{review:Z}:{},...ge!==void 0?{queuePlan:ge}:{},...pe!==void 0?{council:pe}:{},...ne!==void 0?{test:ne}:{}};if(L||B.paused)console.warn(`[job] ${g.jobId} skipping result upload \u2014 ${B.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await C.submitResult(dn),console.log(`[job] ${g.jobId} done \u2014 uploaded ${dn.artifacts.length} artifact(s):`);for(let z of dn.artifacts){let le=Buffer.from(z.contentBase64,"base64").length;console.log(` \xB7 ${z.path} (${le} bytes)`)}dn.artifacts.length===0&&console.warn(`[job] ${g.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(j){let O=j instanceof Error?j.message:String(j);if(B.paused)console.log(`[job] ${g.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(L)console.warn(`[job] ${g.jobId} failed after claim lost (${O}) \u2014 skipping result upload`);else{let H=ku(j),Y=j instanceof $r,Z=j instanceof Dt,pe=j instanceof Me?j.details.rateLimited:void 0;if(Pr&&j instanceof Me)if(j.details.usage){let{addUsageInto:ge}=await Promise.resolve().then(()=>(ai(),$u));ge(j.details.usage,Pr)}else j.details.usage=Pr;let ne=(j instanceof Me?j.details.usage:void 0)??Pr??void 0;console.warn(pe?`[job] ${g.jobId} rate-limited (${pe.kind??"unknown window"}`+(pe.resetAtMs?`, resets ${new Date(pe.resetAtMs).toISOString()}`:"")+") \u2014 HUB will hold and auto-resume":H?`[job] ${g.jobId} failed: ${O} (Claude auth \u2014 token invalid/expired)`:Y?`[job] ${g.jobId} failed: ${O} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:Z?`[job] ${g.jobId} failed: ${O} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${g.jobId} failed: ${O}`),await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:we,finishedAt:new Date().toISOString(),...H?{authError:!0}:{},...Y?{buildInconclusive:!0}:{},...Z?{reviewInconclusive:!0}:{},...pe?{rateLimited:pe}:{},...ne?{usage:ne}:{}})}}finally{$.dispose()}}finally{clearInterval(Ft),D&&clearInterval(D),kt(),B.chatInbox?.close(),f.delete(g.jobId),q?.cleanup(),te?.cleanup()}}function T(C,g){if(!C.credBundle)return{gitCreds:null,contextGitCreds:null};if(!g)return console.warn(`[job] ${C.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let B;try{B=JSON.parse(Kn(g,C.credBundle).toString("utf-8"))}catch(de){return console.warn(`[job] ${C.jobId} failed to open credBundle: ${de instanceof Error?de.message:String(de)}`),{gitCreds:null,contextGitCreds:null}}let L=Ru(B);L&&console.log(`[job] ${C.jobId} cred bundle opened \u2014 git creds configured`);let q=vw(B,C.contextRepo.cloneUrl),te={gitCreds:L,contextGitCreds:q};return B.claudeOauthToken&&(te.claudeOauthToken=B.claudeOauthToken),te}function R(C,g){return C.split(`
1003
+ `:"",Bd=N(v(g.prompt,F,V).replace(/\{\{contextPackTop\}\}/g,()=>Ld),V,g.taskId).replace(/\{\{skillsBlock\}\}/g,Md)+Od+f$,Ai=Bd.replace(/\{\{rolesBlock\}\}/g,()=>Dd),mn=[...F.map(j=>j.workspacePath),...V?[V]:[]];if(mn.length>0&&console.log(`[job] ${g.jobId} --add-dir: ${mn.join(", ")}`),Nu("agent-request")){let j=oa(ro(g.metadata??{})),O=Ou(g.projectId,g.jobId,"agent-request",[`# Agent request \u2014 job ${g.jobId}`,"",`- project: ${g.projectId}`,`- task: ${g.taskId}`,`- role: ${g.role}`,`- model: ${fn??"(backend default)"}`,`- effort: ${$o??"(backend default)"}`,`- add-dirs:${mn.length>0?"":" (none)"}`,...mn.map(H=>` - ${H}`),"","## Append-system-prompt (language directive)","","```",j,"```","","## Prompt","",Ai,"",...ja?["## Context pack (meta/context-pack.md)","",ja]:["## Context pack","","(not generated for this job)"],""].join(`
1004
+ `));O&&console.log(`[debug] ${g.jobId} agent request \u2192 ${O}`)}U&&(D=setInterval(()=>{let O=m;if(!O||O.readyState!==O.OPEN)return;let H;try{H=LA(vt($.dir,"drafts")).filter(Y=>Y.endsWith(".json")).sort()}catch{return}for(let Y of H){if(K.has(Y))continue;if(K.size>=Gc)break;let Z;try{let ne=JSON.parse(ga(vt($.dir,"drafts",Y),"utf-8")),ge=typeof ne.localRef=="string"?ne.localRef:"",hn=typeof ne.title=="string"?ne.title:"",gn=typeof ne.body=="string"?ne.body:"";if(!ge||!hn)continue;Z={localRef:ge,title:hn,body:gn,...ne.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ne.links)?{links:ne.links}:{}}}catch{continue}K.add(Y);let pe={type:"child_draft",jobId:g.jobId,projectId:g.projectId,draftId:U,child:Z};try{O.send(JSON.stringify(pe))}catch{}}},1500));let Lr=null,Fd=new Map;try{if(Xe){let{runCouncil:z,COUNCIL_DEFAULT_MAX_PARALLEL:ue}=await Promise.resolve().then(()=>(ed(),Qu)),je=await z({roles:Xe.roles,artifactDir:Xe.artifactDir,promptFor:Xe.promptFor,maxParallel:g.council?.maxParallel??ue,defaultModel:fn,effort:$o,baseInput:{workspaceDir:$.dir,addDirs:mn,metadata:g.metadata??{},...I||Or?{env:{...I??{},...Or?{CLAUDE_CODE_PLUGIN_SEED_DIR:Or}:{}}}:{},...xo?{settings:xo}:{},signal:B.abort.signal,onActivity:Nr},runnerFor:fe=>(fe&&!Cu(o,fe)&&console.warn(`[job] ${g.jobId} council role provider "${fe}" not served by backend "${o}" \u2014 using the default backend`),c),log:fe=>console.log(`[job] ${g.jobId} council ${fe}`)});Lr=je.usage;let nr=je.opinions.some(fe=>fe.ok);if(!nr&&Xe.onAllFailed==="fail")throw new Error(`council: every role failed \u2014 ${je.opinions.map(fe=>`${fe.role}: ${fe.error??"?"}`).join("; ")}`);if(nr){Ai=Bd.replace(/\{\{rolesBlock\}\}/g,()=>Xe.opinionsBlock(je.opinions));for(let fe of $.listFiles().filter(ft=>ft.startsWith(`${Xe.artifactDir}/`)))Fd.set(fe,$.readFile(fe))}else console.warn(`[job] ${g.jobId} council produced no opinions \u2014 proceeding solo (${je.opinions.map(fe=>`${fe.role}: ${fe.error??"?"}`).join("; ")})`);if(MA(vt($.dir,Xe.verdictFile),{force:!0}),Nu("agent-request")){let fe=Ou(g.projectId,g.jobId,"agent-request-synthesis",Ai);fe&&console.log(`[debug] ${g.jobId} council synthesis request \u2192 ${fe}`)}}let j={workspaceDir:$.dir,role:g.role,prompt:Ai,addDirs:mn,metadata:g.metadata??{},...fn?{model:fn}:{},...$o?{effort:$o}:{},...I||Or?{env:{...I??{},...Or?{CLAUDE_CODE_PLUGIN_SEED_DIR:Or}:{}}}:{},...xo?{settings:xo}:{},signal:B.abort.signal,onActivity:Nr},O=B.chatInbox?await c.run({...j,interactive:{inbox:B.chatInbox.iterable}}):await _u(c,j,{jobId:g.jobId,policy:l,onBeforeRetry:async()=>{$.clean();for(let[z,ue]of Fd){let je=vt($.dir,z);nd(gk(je),{recursive:!0}),od(je,ue)}for(let z of F)try{await Vw(z);let ue=_a[z.name];g.role==="resolve-conflict"&&ue&&await Uu(z,ue,S)}catch(ue){let je=ue instanceof Error?ue.message:String(ue);console.warn(`[job] ${g.jobId} worktree reset failed (${z.name}): ${je}`)}try{await Nd()}catch(z){let ue=z instanceof Error?z.message:String(z);console.warn(`[job] ${g.jobId} delivery re-checkout failed: ${ue}`)}},aborted:()=>L||B.paused});if(Lr){let{addUsageInto:z}=await Promise.resolve().then(()=>(mi(),ju));z(O.usage,Lr)}let H=[];if(UA.has(g.role)&&F.length>0){let z=g.metadata??{},ue=typeof z.commitMessage=="string"?z.commitMessage:`${g.taskId}: changes`,je=g.contextRepo?.cloneUrl,nr=te?.env;if(!je||!nr)throw new Error("delivery requested but "+(je?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let fe=g.taskId.includes(":")?g.taskId.slice(g.taskId.indexOf(":")+1):g.taskId;for(let ft of F){let kn=await zw(ft,ue);if(!kn){console.log(`[job] ${g.jobId} ${ft.name}: no changes \u2014 no delivery`);continue}let Na=`codepipe/deliveries/${fe}/${g.jobId}/${ft.name}`;await Xw(ft,kn,Na,je,nr);let m$=await Zw(ft,kn);H.push({name:ft.name,deliveryRef:Na,deliverySha:kn,baseSha:ft.baseSha,changedFiles:m$}),console.log(`[job] ${g.jobId} ${ft.name}: delivered ${kn.slice(0,10)} \u2192 ${Na}`);let Gd=await Jw(ft,kn);if(Gd.trim().length>0){let h$=vt("display",`${ft.name}.diff`),Kd=vt($.dir,h$);nd(gk(Kd),{recursive:!0}),od(Kd,Gd)}}}if(g.role==="resolve-conflict"&&H.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's SOLUTION.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let Y;g.role==="build"&&(Y=pb($.dir),console.log(`[job] ${g.jobId} build verdict: ok=${Y.ok}`+(Y.failedStep?` failedStep=${Y.failedStep}`:"")));let Z;if(g.role==="code-review"){Z=Ku($.dir),console.log(`[job] ${g.jobId} review verdict: approved=${Z.approved}`);try{let{parseChangedRanges:z,markFindingScope:ue}=await Promise.resolve().then(()=>(Hu(),mb)),je=new Map;for(let nr of F)try{let fe=await rb(nr,S);je.set(nr.name,z(fe))}catch{}ue(Z,je,F.length===1?F[0].name:void 0)}catch(z){console.warn(`[job] ${g.jobId} finding scope marking failed (non-fatal): ${String(z)}`)}}let pe;if(g.role==="council"){let{readCouncilVerdict:z}=await Promise.resolve().then(()=>(pk(),dk));pe=z($.dir)??void 0,console.log(`[job] ${g.jobId} council: ${pe?"answered":"no verdict \u2014 task stops for a human"}`)}let ne;if(g.role==="testing"){try{let z=ga(vt($.dir,"meta","test-result.json"),"utf-8");ne=JSON.parse(z)}catch{ne=void 0}console.log(`[job] ${g.jobId} test verdict: ${ne?"written":"none \u2014 proceeding to the PR"}`)}let ge;if(g.role==="observer"){let{readQueuePlan:z}=await Promise.resolve().then(()=>(hk(),mk));ge=z($.dir)??void 0,console.log(`[job] ${g.jobId} queue plan: ${ge?"produced":"none \u2014 batch keeps the staged order"}`)}let hn=O.artifactPaths.length>0?O.artifactPaths:$.listFiles(),gn=Array.from(new Set(hn)),So;if(he)try{let z=g.role==="index"?["adr/SOURCES.md"]:g.role==="backfill"?["adr"]:[],ue=await cb(he,z);ue.length>0&&(So=ue,console.log(`[job] ${g.jobId} captured ${ue.length} knowledge file(s) for Context Repo`))}catch(z){let ue=z instanceof Error?z.message:String(z);console.warn(`[job] ${g.jobId} knowledge capture failed (non-fatal): ${ue}`)}let{artifacts:pt,omitted:yn,dropped:wn}=gb($.dir,gn);for(let z of yn)console.warn(`[job] ${g.jobId} artifact ${z.path} (${z.bytes} bytes) exceeded upload budget \u2014 content omitted`);wn.length>0&&console.warn(`[job] ${g.jobId} artifact listing truncated: ${wn.length} file(s) over the count budget dropped \u2014 paths listed in artifacts-omitted.md`);let bn={jobId:g.jobId,status:"succeeded",artifacts:pt,...So?{contextWrites:So}:{},...H.length>0?{deliveries:H}:{},log:BA(O.log),startedAt:we,finishedAt:new Date().toISOString(),usage:O.usage,...O.rateLimit?{rateLimit:O.rateLimit}:{},...Y?{build:Y}:{},...Z?{review:Z}:{},...ge!==void 0?{queuePlan:ge}:{},...pe!==void 0?{council:pe}:{},...ne!==void 0?{test:ne}:{}};if(L||B.paused)console.warn(`[job] ${g.jobId} skipping result upload \u2014 ${B.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await C.submitResult(bn),console.log(`[job] ${g.jobId} done \u2014 uploaded ${bn.artifacts.length} artifact(s):`);for(let z of bn.artifacts){let ue=Buffer.from(z.contentBase64,"base64").length;console.log(` \xB7 ${z.path} (${ue} bytes)`)}bn.artifacts.length===0&&console.warn(`[job] ${g.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(j){let O=j instanceof Error?j.message:String(j);if(B.paused)console.log(`[job] ${g.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(L)console.warn(`[job] ${g.jobId} failed after claim lost (${O}) \u2014 skipping result upload`);else{let H=Au(j),Y=j instanceof Tr,Z=j instanceof Gt,pe=j instanceof Fe?j.details.rateLimited:void 0;if(Lr&&j instanceof Fe)if(j.details.usage){let{addUsageInto:ge}=await Promise.resolve().then(()=>(mi(),ju));ge(j.details.usage,Lr)}else j.details.usage=Lr;let ne=(j instanceof Fe?j.details.usage:void 0)??Lr??void 0;console.warn(pe?`[job] ${g.jobId} rate-limited (${pe.kind??"unknown window"}`+(pe.resetAtMs?`, resets ${new Date(pe.resetAtMs).toISOString()}`:"")+") \u2014 HUB will hold and auto-resume":H?`[job] ${g.jobId} failed: ${O} (Claude auth \u2014 token invalid/expired)`:Y?`[job] ${g.jobId} failed: ${O} (BUILD left no verdict \u2014 inconclusive; HUB may retry)`:Z?`[job] ${g.jobId} failed: ${O} (review left no verdict \u2014 inconclusive; HUB may retry)`:`[job] ${g.jobId} failed: ${O}`),await C.submitResult({jobId:g.jobId,status:"failed",artifacts:[],error:{message:O},startedAt:we,finishedAt:new Date().toISOString(),...H?{authError:!0}:{},...Y?{buildInconclusive:!0}:{},...Z?{reviewInconclusive:!0}:{},...pe?{rateLimited:pe}:{},...ne?{usage:ne}:{}})}}finally{$.dispose()}}finally{clearInterval(Wt),D&&clearInterval(D),St(),B.chatInbox?.close(),f.delete(g.jobId),q?.cleanup(),te?.cleanup()}}function T(C,g){if(!C.credBundle)return{gitCreds:null,contextGitCreds:null};if(!g)return console.warn(`[job] ${C.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let B;try{B=JSON.parse(Vn(g,C.credBundle).toString("utf-8"))}catch(le){return console.warn(`[job] ${C.jobId} failed to open credBundle: ${le instanceof Error?le.message:String(le)}`),{gitCreds:null,contextGitCreds:null}}let L=Mu(B);L&&console.log(`[job] ${C.jobId} cred bundle opened \u2014 git creds configured`);let q=Fw(B,C.contextRepo.cloneUrl),te={gitCreds:L,contextGitCreds:q};return B.claudeOauthToken&&(te.claudeOauthToken=B.claudeOauthToken),te}function R(C,g){return C.split(`
991
1005
  `).map(B=>g+B).join(`
992
- `)}function v(C,g,B){let L=g[0]?.workspacePath??"";return C.replace(/\{\{codeDir\}\}/g,L).replace(/\{\{codeRoot\}\}/g,L?L.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,B??"")}function _(C,g){let B=g.includes("::")?"":g.split(":",2)[1]??"";if(!C||!B)return"";for(let L of["PLAN.md","SOLUTION.md"])try{return sa(gt(C,"tasks",B,L),"utf-8")}catch{}return""}function N(C,g,B){let L=C,q=B.includes("::")?"":B.split(":",2)[1]??"",te=de=>{if(!g||!q)return"";try{return sa(gt(g,"tasks",q,de),"utf-8").trim()}catch{return""}};if(L.includes("{{planMd}}")||L.includes("{{solutionMd}}")){let de=te("PLAN.md")||te("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";L=L.replace(/\{\{planMd\}\}/g,()=>de),L=L.replace(/\{\{solutionMd\}\}/g,()=>de)}if(L.includes("{{taskDescription}}")){let de=te("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";L=L.replace(/\{\{taskDescription\}\}/g,()=>de)}return L=nb(L,g),L}let G=C=>{if(p)return;p=!0,console.log(`
993
- [${C}] shutting down`),d.abort();let g=[...f.keys()];for(let q of f.values())q.abort.abort();let B=new AbortController,L=setTimeout(()=>B.abort(),3e3);(async()=>(await Promise.all(g.map(async q=>{try{await u.releaseJob(q,`sandbox ${C}`,B.signal),console.log(`[${C}] released job ${q}`)}catch(te){let de=te instanceof Error?te.message:String(te);console.warn(`[${C}] release failed: ${de} (sweeper will reclaim)`)}})),clearTimeout(L),k.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>G("SIGINT")),process.on("SIGTERM",()=>G("SIGTERM"));let W=[x("implementation")];e.planningLane!==!1?W.push(x("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(W)}var aa,fA,Jb=E(()=>{"use strict";M();ht();Uc();ow();cw();zs();ai();br();hw();Ye();Ys();$w();du();Kw();Ww();Yw();ju();Jw();rb();ib();aa=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),fA=new Set(["implement","resolve-conflict"])});var no=E(()=>{"use strict";Wy();Jb();Ys()});import{cancel as gA,isCancel as Qb,log as ot,password as yA,text as wA}from"@clack/prompts";function bA(t){return Qb(t)&&(gA("aborted"),process.exit(1)),typeof t=="string"?t:""}function ek(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function kA(t){let e=Jc({redirectUri:Xc,challenge:t.challenge,state:t.state});ot.message(`Open this URL, approve the access, and paste the code shown:
994
- ${e}`);let r=await wA({message:"Authorization code \u2014 blank to skip"});if(Qb(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=um(r,t.state);return await Zc({code:n,verifier:t.verifier,state:t.state,redirectUri:Xc})}catch(n){return ot.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function vA(t){if(In()?.claude?.oauthToken&&!t.farm)return ot.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN!=="1"||!process.stdout.isTTY)return null;ot.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=Yi(),n;try{n=await dm({...r,openUrl:ur,log:i=>ot.message(i)})}catch(i){ot.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await kA(r);if(s===null)return null;n=s}let o=await Xt(n.oauthToken);return o==="invalid"?(ot.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(ot.success(`Claude: logged in \u2014 ${ek(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function tk(t){ot.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
1006
+ `)}function v(C,g,B){let L=g[0]?.workspacePath??"";return C.replace(/\{\{codeDir\}\}/g,L).replace(/\{\{codeRoot\}\}/g,L?L.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,B??"")}function P(C,g){let B=g.includes("::")?"":g.split(":",2)[1]??"";if(!C||!B)return"";for(let L of["PLAN.md","SOLUTION.md"])try{return ga(vt(C,"tasks",B,L),"utf-8")}catch{}return""}function N(C,g,B){let L=C,q=B.includes("::")?"":B.split(":",2)[1]??"",te=le=>{if(!g||!q)return"";try{return ga(vt(g,"tasks",q,le),"utf-8").trim()}catch{return""}};if(L.includes("{{planMd}}")||L.includes("{{solutionMd}}")){let le=te("PLAN.md")||te("SOLUTION.md")||"(PLAN.md missing \u2014 proceed from the task description)";L=L.replace(/\{\{planMd\}\}/g,()=>le),L=L.replace(/\{\{solutionMd\}\}/g,()=>le)}if(L.includes("{{taskDescription}}")){let le=te("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";L=L.replace(/\{\{taskDescription\}\}/g,()=>le)}return L=xb(L,g),L}let G=C=>{if(p)return;p=!0,console.log(`
1007
+ [${C}] shutting down`),d.abort();let g=[...f.keys()];for(let q of f.values())q.abort.abort();let B=new AbortController,L=setTimeout(()=>B.abort(),3e3);(async()=>(await Promise.all(g.map(async q=>{try{await u.releaseJob(q,`sandbox ${C}`,B.signal),console.log(`[${C}] released job ${q}`)}catch(te){let le=te instanceof Error?te.message:String(te);console.warn(`[${C}] release failed: ${le} (sweeper will reclaim)`)}})),clearTimeout(L),k.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>G("SIGINT")),process.on("SIGTERM",()=>G("SIGTERM"));let W=[x("implementation")];e.planningLane!==!1?W.push(x("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(W)}var ya,UA,yk=E(()=>{"use strict";M();kt();Yc();Sw();Iw();ia();mi();Sr();Ow();Je();na();Gw();$u();lb();db();fb();Hu();yb();$b();Eb();ya=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),UA=new Set(["implement","resolve-conflict"])});var co=E(()=>{"use strict";dw();yk();na()});import{cancel as GA,isCancel as bk,log as at,password as KA,text as HA}from"@clack/prompts";function WA(t){return bk(t)&&(GA("aborted"),process.exit(1)),typeof t=="string"?t:""}function kk(t){return`${t.slice(0,14)}\u2026 (${t.length} chars)`}async function qA(t){let e=il({redirectUri:ol,challenge:t.challenge,state:t.state});at.message(`Open this URL, approve the access, and paste the code shown:
1008
+ ${e}`);let r=await HA({message:"Authorization code \u2014 blank to skip"});if(bk(r)||typeof r!="string"||r.trim().length===0)return null;try{let n=$m(r,t.state);return await sl({code:n,verifier:t.verifier,state:t.state,redirectUri:ol})}catch(n){return at.warn(`Code paste didn't work (${n instanceof Error?n.message:String(n)}).`),null}}async function YA(t){if(On()?.claude?.oauthToken&&!t.farm)return at.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";if(process.env.CODEPIPE_CLAUDE_AUTOLOGIN!=="1"||!process.stdout.isTTY)return null;at.message("Claude login \u2014 pipeline agents run on your Claude subscription.");let r=rs(),n;try{n=await xm({...r,openUrl:fr,log:i=>at.message(i)})}catch(i){at.warn(`Browser sign-in didn't complete (${i instanceof Error?i.message:String(i)}) \u2014 trying the code-paste fallback.`);let s=await qA(r);if(s===null)return null;n=s}let o=await er(n.oauthToken);return o==="invalid"?(at.warn("Claude rejected the obtained token (401) \u2014 falling back to manual entry."),null):(at.success(`Claude: logged in \u2014 ${kk(n.oauthToken)}, /v1/models: ${o}.`),n.oauthToken)}async function vk(t){at.message(`Claude \u2014 the pipeline's agents run on your Claude subscription.
995
1009
  In another terminal:
996
1010
  1. install Claude Code \u2014 https://claude.com/claude-code
997
1011
  2. run \`claude setup-token\`
998
1012
  3. paste the token it prints (starts with sk-ant-) below`+(t.farm?`
999
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=bA(await yA({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return ot.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||ot.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await Xt(e);return r==="invalid"?(ot.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),tk(t)):(ot.success(`Claude: ${ek(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var rk,nk=E(()=>{"use strict";Vi();jn();ue();el();rk={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:vA,promptManual:tk,validate:Xt}});function ok(t){return rk}async function ik(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var sk=E(()=>{"use strict";nk()});async function oo(t,e,r){return e.host==="github"?xA(t,e,r):e.host==="gitlab"?CA(t,e,r):AA(t,e,r)}async function ak(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 it(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await ck(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 Je(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await lk(e.gitlabToken,t):o}}return e.bitbucket?(await Ut(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await uk(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 ck(t,e){let r=!1;try{r=(await it(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 lk(t,e){let r=!1;try{r=(await Je(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 uk(t,e){let r=!1;try{r=(await Ut(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 it(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($A+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 xA(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 SA(n,e,r),i=await EA(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Un(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await RA(n,o.owner,o.name,a.path,i)||await TA(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 SA(t,e,r){let n=await it(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 ck(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Vu(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 it(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 Vu(t,e){let{status:r,data:n}=await it(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function EA(t,e,r){let{data:n}=await it(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function RA(t,e,r,n,o){let{status:i,data:s}=await it(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function TA(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 it(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function Je(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(IA+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 CA(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 Je(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 lk(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await Je(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let m=await Je(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(m.status===404||!m.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=m.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let f=await Je(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Un(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await Je(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let m of f)l.add(m.path);if(f.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await Je(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 Ut(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(PA+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 AA(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 Ut(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 uk(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 Ut(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=Un(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await Ut(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let f of l)p.set(f.path,f.content);if((await Ut(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 $A,IA,PA,fi=E(()=>{"use strict";Hr();$A="https://api.github.com";IA="https://gitlab.com/api/v4";PA="https://api.bitbucket.org/2.0"});function Ze(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=_A[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 _A,ca=E(()=>{"use strict";_A={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as jA}from"node:crypto";import{existsSync as dk,mkdirSync as NA,readFileSync as pk,readdirSync as OA,rmSync as la,writeFileSync as LA}from"node:fs";import{homedir as MA}from"node:os";import{dirname as DA,join as zu}from"node:path";function fk(){return zu(MA(),".codepipe","init-drafts")}function Xu(t){let e=jA("sha256").update(t).digest("hex").slice(0,16);return zu(fk(),`${e}.json`)}function mk(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=UA)}function hk(t){let e=Xu(t);if(!dk(e))return null;try{let r=JSON.parse(pk(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:mk(r.savedAt)?(la(e,{force:!0}),null):r}catch{return null}}function Ju(t){la(Xu(t),{force:!0})}function gk(){let t=fk();if(dk(t))for(let e of OA(t)){let r=zu(t,e);try{let n=JSON.parse(pk(r,"utf-8"));mk(n.savedAt)&&la(r,{force:!0})}catch{la(r,{force:!0})}}}var UA,io,yk=E(()=>{"use strict";UA=24*60*60*1e3;io=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(){Ju(this.cwd)}persist(){let e=Xu(this.cwd);NA(DA(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};LA(e,JSON.stringify(r,null,2)+`
1000
- `,{mode:384})}}});function wk(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 bk(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 kk=E(()=>{"use strict"});import{existsSync as BA}from"node:fs";import{join as FA}from"node:path";import{simpleGit as GA}from"simple-git";function qA(t){let e=t.split("/");return e[e.length-1]??t}function vk(t){if(t.filter(r=>!HA.test(qA(r))).length>KA)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(WA.has(n))return!0}return!1}async function YA(t){try{let r=(await GA(t).raw(["ls-files"])).split(`
1001
- `).map(n=>n.trim()).filter(Boolean);return vk(r)}catch{return!1}}async function VA(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)?vk(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function $k(t,e){for(let r of t)try{let n=e.localRoot!=null?FA(e.localRoot,r.mountAs??r.name):null;if(n&&BA(n)?await YA(n):await VA(r,e.tokens))return!0}catch{}return!1}var KA,HA,WA,xk=E(()=>{"use strict";KA=3,HA=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,WA=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Sk}from"node:fs";import{join as Ek}from"node:path";import{simpleGit as Rk}from"simple-git";async function hi(t,e,r={}){let n=r.log??zA,o=[];for(let i of e){let s=Ek(t,i.mountAs),a=of(i);if(!Sk(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 Rk().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=mi(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(!Sk(Ek(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=Rk(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!XA(l,a)){n.warn(`${i.mountAs}/ origin (${mi(l)||"none"}) != expected (${mi(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:mi(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=mi(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 XA(t,e){return Tk(t)===Tk(e)}function Tk(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function mi(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Ik(t={}){let e=je();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 hi(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 zA,ua=E(()=>{"use strict";Et();zA={info:t=>console.log(t),warn:t=>console.warn(t)}});import{existsSync as Zu,readFileSync as Qu,writeFileSync as Ck}from"node:fs";import{join as ed}from"node:path";import{parseDocument as td}from"yaml";function Pk(t){let e={};return t.branches.integration&&(e.integration=t.branches.integration),t.branches.stable!==void 0&&(e.stable=t.branches.stable),t.branches.release_pattern!==void 0&&(e.release_pattern=t.branches.release_pattern),{flow:t.flow,branches:e}}function Ak(t){let{errors:e}=kn(t);if(e.length>0)throw new Error(`invalid git config: ${e.join("; ")}`)}async function _k(t,e){let r=Pk(e);Ak(r);let n=ed(t,"project.yaml");if(!Zu(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=td(Qu(n,"utf-8"));o.set("git",r),Ck(n,o.toString())}async function jk(t,e,r){let n=Pk(r);Ak(n);let o=ed(t,"project.yaml");if(!Zu(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=td(Qu(o,"utf-8"));ls(i,e).set("git",n),Ck(o,i.toString())}function Nk(t){let e=ed(t,"project.yaml");if(!Zu(e))return null;try{let r=td(Qu(e,"utf-8")).toJS();return JA(r?.git)}catch{return null}}function JA(t){if(!t||typeof t!="object")return null;let e=t,r=e.flow;if(r!=="simple"&&r!=="gitflow"&&r!=="release")return null;let n=e.branches;if(!n||typeof n!="object")return null;let o=n,i=o.integration;if(typeof i!="string"||!i)return null;let s={flow:r,branches:{integration:i}};return typeof o.stable=="string"&&(s.branches.stable=o.stable),typeof o.release_pattern=="string"&&(s.branches.release_pattern=o.release_pattern),s}var Ok=E(()=>{"use strict";M();us()});import{confirm as ZA,isCancel as QA}from"@clack/prompts";async function da(t){let e=Co(t.facts),r=t.confirm??e_,n=t.log??(()=>{}),o=t.readProject??Nk,i=t.writeProject??_k,s=t.writeOverride??jk;if(!t.contextDir)return e.flow!=="simple"&&n(`git-flow: detected ${so(e)} (no context repo to persist)`),{outcome:"no-context",detected:e};let a=t.contextDir,c=o(a);return c===null?e.flow==="simple"?(n("git-flow: simple (single branch)"),{outcome:"silent-simple",detected:e}):await r(`Detected git-flow: ${so(e)}. Use it?`)?(await i(a,e),n(`git-flow: ${so(e)} (project default)`),{outcome:"wrote-project",detected:e}):(n("git-flow: keeping simple (detection declined)"),{outcome:"declined",detected:e}):Pc(e,c)?await r(`This repo's git-flow (${so(e)}) differs from the project (${so(c)}). Record a per-repo override?`)?(await s(a,t.repoName,e),n(`git-flow: ${so(e)} (per-repo override for "${t.repoName}")`),{outcome:"wrote-override",detected:e}):(n(`git-flow: using the project flow for "${t.repoName}" (override declined)`),{outcome:"declined",detected:e}):{outcome:"match",detected:e}}function so(t){if(t.flow==="simple")return"simple (single branch)";let e=[`integration=${t.branches.integration}`];return t.branches.stable&&e.push(`stable=${t.branches.stable}`),t.branches.release_pattern&&e.push(`release=${t.branches.release_pattern}`),`${t.flow} (${e.join(", ")})`}async function e_(t){let e=await ZA({message:t,initialValue:!0});return QA(e)?!1:e===!0}var rd=E(()=>{"use strict";M();Ok()});import{simpleGit as Lk}from"simple-git";async function gi(t,e){let r=Lk(t),n=null;try{n=(await r.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"")||null}catch{}!n&&e&&(n=await t_(e));let o=[];try{o=(await r.raw(["for-each-ref","--format=%(refname:short)","refs/remotes/origin"])).split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).map(s=>s.replace(/^origin\//,"")).filter(s=>s!=="HEAD"&&s!=="origin")}catch{o=[]}return{defaultBranch:n,branches:o}}async function t_(t){try{let e=await Lk().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}var nd=E(()=>{"use strict"});import{simpleGit as r_}from"simple-git";async function Mk(t,e,r){return t.host==="github"?n_(t,e,r):t.host==="gitlab"?o_(t,e,r):i_(t,e,r)}function od(t){return new Error(`${t.owner}/${t.repoName} exists but is PUBLIC \u2014 a mirror holds the repository's full history and must be private. Make it private (or pick another name) and re-run`)}async function n_(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await it(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw od(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:o.data.ssh_url,created:!1}}let i=(await it(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await Vu(n,t.owner);if(!s&&!a)throw new Error(`"${t.owner}" is neither the token's account ("${i}") nor an organization it can see \u2014 nothing was created. Use a GitHub username or organization (not an email)`);r.info(`creating mirror ${t.owner}/${t.repoName} (github, ${a?"org":"user"})`);let c=await it(n,"POST",a?`/orgs/${t.owner}/repos`:"/user/repos",{name:t.repoName,private:!0,auto_init:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"});if(!c.data)throw new Error(`GitHub: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url,created:!0}}async function Dk(t,e,r){try{return t==="github"?(await it(e,"GET","/user")).data?.login??null:t==="gitlab"?(await Je(e,"GET","/user")).data?.username??null:r?(await Ut({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function o_(t,e,r){let n=e.gitlabToken;if(!n)throw new Error("GitLab PAT required to create a gitlab-hosted mirror");let o=encodeURIComponent(`${t.owner}/${t.repoName}`),i=await Je(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw od(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i.data.ssh_url_to_repo,created:!1}}let s={name:t.repoName,path:t.repoName,visibility:"private",initialize_with_readme:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"};if((await Je(n,"GET","/user")).data?.username!==t.owner){let l=await Je(n,"GET",`/namespaces/${encodeURIComponent(t.owner)}`);if(l.status===404||!l.data)throw new Error(`GitLab namespace "${t.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);s.namespace_id=l.data.id}r.info(`creating mirror ${t.owner}/${t.repoName} (gitlab)`);let c=await Je(n,"POST","/projects",s);if(!c.data)throw new Error(`GitLab: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url_to_repo,created:!0}}async function i_(t,e,r){let n=e.bitbucket;if(!n)throw new Error("Bitbucket email + API token required to create a bitbucket-hosted mirror");let o=`/repositories/${t.owner}/${encodeURIComponent(t.repoName)}`,i=`git@bitbucket.org:${t.owner}/${t.repoName}.git`,s=await Ut(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw od(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i,created:!1}}r.info(`creating mirror ${t.owner}/${t.repoName} (bitbucket)`);let a=await Ut(n,"POST",o,{json:{scm:"git",is_private:!0,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"}});if(a.status===404||!a.data?.slug)throw new Error(`Bitbucket cannot create ${t.owner}/${t.repoName} \u2014 check the workspace and that the credential may create repositories in it`);return{spec:t,sshUrl:i,created:!0}}async function Uk(t,e,r){let n=r_(t);if((await n.raw(["rev-parse","--is-shallow-repository"])).trim()==="true")throw new Error("this clone is shallow \u2014 the mirror would be seeded with partial history. Run `git fetch --unshallow` first");if((await n.listRemote(["--heads",e])).trim().length>0)return r.info("mirror already has branches \u2014 leaving its content alone"),{seeded:!1};r.info("seeding mirror with the repository's branches and tags\u2026");let i=(await n.raw(["for-each-ref","refs/remotes/origin","--format=%(refname)"])).split(`
1002
- `).map(a=>a.trim()).filter(a=>a.length>0&&a!=="refs/remotes/origin/HEAD");if(i.length===0)throw new Error("the local clone has no origin branches to seed from");let s=i.map(a=>`${a}:refs/heads/${a.slice(20)}`);return await n.push([e,...s]),await n.push([e,"--tags"]),{seeded:!0}}function s_(t,e){let r=e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-");return`${t}-${r}-mirror`.replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function a_(t,e,r){return e.mirror?{host:e.mirror.host,owner:e.mirror.owner,repoName:e.mirror.repoName}:{host:r.host,owner:r.owner,repoName:s_(t,e.repoName)}}function Bk(t,e,r){let n=new Map,o=[];for(let i of e){let s=a_(t,i,r),a=`${s.host}:${s.owner.toLowerCase()}/${s.repoName.toLowerCase()}`,c=n.get(a);if(c)throw new Error(`repositories "${c}" and "${i.name}" both map to the mirror ${s.owner}/${s.repoName} \u2014 mirroring them into one repository would merge their histories. Give one an explicit mirror name (mirror.repo in project.yaml) and re-run`);n.set(a,i.name),o.push({repo:i,spec:s})}return o}var Fk=E(()=>{"use strict";fi()});var qk={};Ne(qk,{ensureEmbeddedWorker:()=>fa,spawnWorkerProcess:()=>ma,upCommand:()=>ha,workerChildEnv:()=>Wk,workerStartArgs:()=>Hk});import{spawn as Kk}from"node:child_process";import{existsSync as Gk}from"node:fs";import{homedir as c_,hostname as l_}from"node:os";import{join as pa}from"node:path";async function u_(t,e,r){let n=Ke(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Ct(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 Mg(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 ${Ct(e)} still holds its token.
1003
- 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`),kf(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function d_(t,e,r){let n=Ke(e)!==null;if(!await u_(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 _s(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof J&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof J&&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 J?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 zr({hub:t.hubUrl,token:o,name:r.name??`${l_()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function p_(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=ze(r.sealPublicKey);if(!X(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Di(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 fa(t,e,r){await d_(t,e,r),p_(t.projectId,e)}function Hk(t){return[...t?["--profile",t]:[],"worker","start"]}function Wk(t){let e={...t};for(let r of Dc)delete e[r];return e}function ma(t){let e=Kk(process.execPath,[t.entry,...Hk(t.profile)],{stdio:["ignore","pipe","pipe"],env:Wk(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
1004
- `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function f_(t,e){let r=process.cwd(),n=pa(r,nt);if(En(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Gk(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 se(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 id(r);if(!nf(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=X(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await qs({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=pa(c_(),".codepipe",e?pa("profiles",e,"context-config"):"context-config");if(Ji(c.contextDir,l,a),!Gk(pa(c.contextDir,"project.yaml"))){Ln(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Do(c.contextDir,Lt(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 ha(t){let{cfg:e,profile:r}=Tn(t.profile);if(t.debug){let f=typeof t.debug=="string"&&t.debug.trim()?t.debug.trim():"agent-request";process.env.CODEPIPE_DEBUG=f,console.log(`[up] debug logging on (${f}) \u2192 ~/.codepipe/debug/${e.projectId}/`)}await f_(e,r),await fa(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(f,m)=>{let y=b=>w=>{for(let k of w.toString("utf-8").split(`
1013
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let e=WA(await KA({message:"Claude OAuth token \u2014 blank to skip"})).trim();if(!e)return at.warn(t.farm?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"";e.startsWith("sk-ant-")||at.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`.");let r=await er(e);return r==="invalid"?(at.warn("Claude refused this token. Run `claude setup-token` again and paste the new one."),vk(t)):(at.success(`Claude: ${kk(e)} \u2014 ${r==="valid"?"verified":"check inconclusive, saved"}.`),e)}var $k,xk=E(()=>{"use strict";ns();Bn();de();cl();$k={id:"claude",label:"Claude",runnerEnvVar:"CLAUDE_CODE_OAUTH_TOKEN",interactiveLogin:YA,promptManual:vk,validate:er}});function Sk(t){return $k}async function Ek(t,e){let r=null;try{r=await t.interactiveLogin(e)}catch{r=null}return r!==null?r:t.promptManual(e)}var Rk=E(()=>{"use strict";xk()});async function lo(t,e,r){return e.host==="github"?zA(t,e,r):e.host==="gitlab"?t_(t,e,r):n_(t,e,r)}async function Tk(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 ct(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ik(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 tt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ck(e.gitlabToken,t):o}}return e.bitbucket?(await Kt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Pk(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 Ik(t,e){let r=!1;try{r=(await ct(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 Ck(t,e){let r=!1;try{r=(await tt(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 Pk(t,e){let r=!1;try{r=(await Kt(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 ct(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(VA+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 zA(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 XA(n,e,r),i=await JA(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Hn(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await ZA(n,o.owner,o.name,a.path,i)||await QA(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 XA(t,e,r){let n=await ct(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 Ik(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await id(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 ct(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 id(t,e){let{status:r,data:n}=await ct(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function JA(t,e,r){let{data:n}=await ct(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function ZA(t,e,r,n,o){let{status:i,data:s}=await ct(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function QA(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 ct(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}async function tt(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(e_+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 t_(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 tt(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 Ck(n,e)} (attach joins an existing Context Repo and never creates one)`);let p=await tt(n,"GET","/user"),d={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(p.data?.username!==e.owner){let m=await tt(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(m.status===404||!m.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);d.namespace_id=m.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let f=await tt(n,"POST","/projects",d);if(!f.data)throw new Error("GitLab create project: empty response");i=f.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Hn(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let p=1;;p++){let f=(await tt(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${p}&ref=${encodeURIComponent(a)}`)).data??[];for(let m of f)l.add(m.path);if(f.length<100)break}let u=c.filter(p=>!l.has(p.path)).map(p=>({action:"create",file_path:p.path,content:p.content}));return u.length>0?await tt(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 Kt(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(r_+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 n_(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 Kt(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 Pk(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 Kt(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=Hn(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let p of c)(await Kt(n,"GET",`${o}/src/${encodeURIComponent(a)}/${p.path}?format=meta`)).status===404&&l.push(p);if(l.length>0){let p=new URLSearchParams;p.set("message","chore(codepipe): scaffold context repo files"),p.set("branch",a);for(let f of l)p.set(f.path,f.content);if((await Kt(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 VA,e_,r_,ki=E(()=>{"use strict";Zr();VA="https://api.github.com";e_="https://gitlab.com/api/v4";r_="https://api.bitbucket.org/2.0"});function rt(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=o_[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 o_,wa=E(()=>{"use strict";o_={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"}});import{createHash as i_}from"node:crypto";import{existsSync as Ak,mkdirSync as s_,readFileSync as _k,readdirSync as a_,rmSync as ba,writeFileSync as c_}from"node:fs";import{homedir as l_}from"node:os";import{dirname as u_,join as sd}from"node:path";function jk(){return sd(l_(),".codepipe","init-drafts")}function ad(t){let e=i_("sha256").update(t).digest("hex").slice(0,16);return sd(jk(),`${e}.json`)}function Nk(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=d_)}function Ok(t){let e=ad(t);if(!Ak(e))return null;try{let r=JSON.parse(_k(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Nk(r.savedAt)?(ba(e,{force:!0}),null):r}catch{return null}}function cd(t){ba(ad(t),{force:!0})}function Lk(){let t=jk();if(Ak(t))for(let e of a_(t)){let r=sd(t,e);try{let n=JSON.parse(_k(r,"utf-8"));Nk(n.savedAt)&&ba(r,{force:!0})}catch{ba(r,{force:!0})}}}var d_,uo,Mk=E(()=>{"use strict";d_=24*60*60*1e3;uo=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(){cd(this.cwd)}persist(){let e=ad(this.cwd);s_(u_(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};c_(e,JSON.stringify(r,null,2)+`
1014
+ `,{mode:384})}}});function Dk(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 Uk(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 Bk=E(()=>{"use strict"});import{existsSync as p_}from"node:fs";import{join as f_}from"node:path";import{simpleGit as m_}from"simple-git";function w_(t){let e=t.split("/");return e[e.length-1]??t}function Fk(t){if(t.filter(r=>!g_.test(w_(r))).length>h_)return!0;for(let r of t){let n=(r.split("/")[0]??"").toLowerCase();if(y_.has(n))return!0}return!1}async function b_(t){try{let r=(await m_(t).raw(["ls-files"])).split(`
1015
+ `).map(n=>n.trim()).filter(Boolean);return Fk(r)}catch{return!1}}async function k_(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)?Fk(i.map(s=>s.name??"").filter(Boolean)):!1}catch{return!1}}async function Gk(t,e){for(let r of t)try{let n=e.localRoot!=null?f_(e.localRoot,r.mountAs??r.name):null;if(n&&p_(n)?await b_(n):await k_(r,e.tokens))return!0}catch{}return!1}var h_,g_,y_,Kk=E(()=>{"use strict";h_=3,g_=/^(\.gitignore|license(\.[a-z]+)?|readme(\.[a-z]+)?)$/i,y_=new Set(["src","lib","app","docs","package.json","pyproject.toml","go.mod","cargo.toml","pom.xml"])});import{existsSync as Hk}from"node:fs";import{join as Wk}from"node:path";import{simpleGit as qk}from"simple-git";async function $i(t,e,r={}){let n=r.log??v_,o=[];for(let i of e){let s=Wk(t,i.mountAs),a=yf(i);if(!Hk(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 qk().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let p=vi(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(!Hk(Wk(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=qk(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!$_(l,a)){n.warn(`${i.mountAs}/ origin (${vi(l)||"none"}) != expected (${vi(a)}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:vi(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=vi(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 $_(t,e){return Yk(t)===Yk(e)}function Yk(t){return t.trim().replace(/\.git$/,"").replace(/^\w+:\/\//,"").replace(/^[^/@]*@/,"").replace(/:/g,"/").toLowerCase()}function vi(t){return t.replace(/(\w+:\/\/)[^/@]*@/g,"$1***@")}async function Vk(t={}){let e=Ne();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 $i(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 v_,ka=E(()=>{"use strict";Ct();v_={info:t=>console.log(t),warn:t=>console.warn(t)}});import{existsSync as ld,readFileSync as ud}from"node:fs";import{join as dd}from"node:path";import{parseDocument as pd}from"yaml";function zk(t){let e={};return t.branches.integration&&(e.integration=t.branches.integration),t.branches.stable!==void 0&&(e.stable=t.branches.stable),t.branches.release_pattern!==void 0&&(e.release_pattern=t.branches.release_pattern),{flow:t.flow,branches:e}}function Xk(t){let{errors:e}=sr(t);if(e.length>0)throw new Error(`invalid git config: ${e.join("; ")}`)}async function Jk(t,e){let r=zk(e);Xk(r),await Oe(t,async()=>{let n=dd(t,"project.yaml");if(!ld(n))throw new Error(`project.yaml not found in context repo (${t})`);let o=pd(ud(n,"utf-8"));o.set("git",r),await qe(t,[{path:"project.yaml",content:o.toString()}],`chore(config): set git flow ${e.flow}`)})}async function Zk(t,e,r){let n=zk(r);Xk(n),await Oe(t,async()=>{let o=dd(t,"project.yaml");if(!ld(o))throw new Error(`project.yaml not found in context repo (${t})`);let i=pd(ud(o,"utf-8"));Al(i,e).set("git",n),await qe(t,[{path:"project.yaml",content:i.toString()}],`chore(config): set ${e} git flow ${r.flow}`)})}function Qk(t){let e=dd(t,"project.yaml");if(!ld(e))return null;try{let r=pd(ud(e,"utf-8")).toJS();return x_(r?.git)}catch{return null}}function x_(t){if(!t||typeof t!="object")return null;let e=t,r=e.flow;if(r!=="simple"&&r!=="gitflow"&&r!=="release")return null;let n=e.branches;if(!n||typeof n!="object")return null;let o=n,i=o.integration;if(typeof i!="string"||!i)return null;let s={flow:r,branches:{integration:i}};return typeof o.stable=="string"&&(s.branches.stable=o.stable),typeof o.release_pattern=="string"&&(s.branches.release_pattern=o.release_pattern),s}var ev=E(()=>{"use strict";M();Le();vs()});import{confirm as S_,isCancel as E_}from"@clack/prompts";async function va(t){let e=jo(t.facts),r=t.confirm??R_,n=t.log??(()=>{}),o=t.readProject??Qk,i=t.writeProject??Jk,s=t.writeOverride??Zk;if(!t.contextDir)return e.flow!=="simple"&&n(`git-flow: detected ${po(e)} (no context repo to persist)`),{outcome:"no-context",detected:e};let a=t.contextDir,c=o(a);return c===null?e.flow==="simple"?(n("git-flow: simple (single branch)"),{outcome:"silent-simple",detected:e}):await r(`Detected git-flow: ${po(e)}. Use it?`)?(await i(a,e),n(`git-flow: ${po(e)} (project default)`),{outcome:"wrote-project",detected:e}):(n("git-flow: keeping simple (detection declined)"),{outcome:"declined",detected:e}):kc(e,c)?await r(`This repo's git-flow (${po(e)}) differs from the project (${po(c)}). Record a per-repo override?`)?(await s(a,t.repoName,e),n(`git-flow: ${po(e)} (per-repo override for "${t.repoName}")`),{outcome:"wrote-override",detected:e}):(n(`git-flow: using the project flow for "${t.repoName}" (override declined)`),{outcome:"declined",detected:e}):{outcome:"match",detected:e}}function po(t){if(t.flow==="simple")return"simple (single branch)";let e=[`integration=${t.branches.integration}`];return t.branches.stable&&e.push(`stable=${t.branches.stable}`),t.branches.release_pattern&&e.push(`release=${t.branches.release_pattern}`),`${t.flow} (${e.join(", ")})`}async function R_(t){let e=await S_({message:t,initialValue:!0});return E_(e)?!1:e===!0}var fd=E(()=>{"use strict";M();ev()});import{simpleGit as tv}from"simple-git";async function xi(t,e){let r=tv(t),n=null;try{n=(await r.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"")||null}catch{}!n&&e&&(n=await T_(e));let o=[];try{o=(await r.raw(["for-each-ref","--format=%(refname:short)","refs/remotes/origin"])).split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).map(s=>s.replace(/^origin\//,"")).filter(s=>s!=="HEAD"&&s!=="origin")}catch{o=[]}return{defaultBranch:n,branches:o}}async function T_(t){try{let e=await tv().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}var md=E(()=>{"use strict"});import{simpleGit as I_}from"simple-git";async function rv(t,e,r){return t.host==="github"?C_(t,e,r):t.host==="gitlab"?P_(t,e,r):A_(t,e,r)}function hd(t){return new Error(`${t.owner}/${t.repoName} exists but is PUBLIC \u2014 a mirror holds the repository's full history and must be private. Make it private (or pick another name) and re-run`)}async function C_(t,e,r){let n=e.githubToken;if(!n)throw new Error("GitHub token required to create a github-hosted mirror");let o=await ct(n,"GET",`/repos/${t.owner}/${encodeURIComponent(t.repoName)}`);if(o.status===200&&o.data){if(o.data.private!==!0)throw hd(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:o.data.ssh_url,created:!1}}let i=(await ct(n,"GET","/user")).data?.login??"",s=i.toLowerCase()===t.owner.toLowerCase(),a=!s&&await id(n,t.owner);if(!s&&!a)throw new Error(`"${t.owner}" is neither the token's account ("${i}") nor an organization it can see \u2014 nothing was created. Use a GitHub username or organization (not an email)`);r.info(`creating mirror ${t.owner}/${t.repoName} (github, ${a?"org":"user"})`);let c=await ct(n,"POST",a?`/orgs/${t.owner}/repos`:"/user/repos",{name:t.repoName,private:!0,auto_init:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"});if(!c.data)throw new Error(`GitHub: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url,created:!0}}async function nv(t,e,r){try{return t==="github"?(await ct(e,"GET","/user")).data?.login??null:t==="gitlab"?(await tt(e,"GET","/user")).data?.username??null:r?(await Kt({email:r,apiToken:e},"GET","/workspaces?role=contributor&pagelen=1")).data?.values?.[0]?.slug??null:null}catch{return null}}async function P_(t,e,r){let n=e.gitlabToken;if(!n)throw new Error("GitLab PAT required to create a gitlab-hosted mirror");let o=encodeURIComponent(`${t.owner}/${t.repoName}`),i=await tt(n,"GET",`/projects/${o}`);if(i.status===200&&i.data){if(i.data.visibility!=="private")throw hd(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i.data.ssh_url_to_repo,created:!1}}let s={name:t.repoName,path:t.repoName,visibility:"private",initialize_with_readme:!1,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"};if((await tt(n,"GET","/user")).data?.username!==t.owner){let l=await tt(n,"GET",`/namespaces/${encodeURIComponent(t.owner)}`);if(l.status===404||!l.data)throw new Error(`GitLab namespace "${t.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);s.namespace_id=l.data.id}r.info(`creating mirror ${t.owner}/${t.repoName} (gitlab)`);let c=await tt(n,"POST","/projects",s);if(!c.data)throw new Error(`GitLab: could not create ${t.owner}/${t.repoName}`);return{spec:t,sshUrl:c.data.ssh_url_to_repo,created:!0}}async function A_(t,e,r){let n=e.bitbucket;if(!n)throw new Error("Bitbucket email + API token required to create a bitbucket-hosted mirror");let o=`/repositories/${t.owner}/${encodeURIComponent(t.repoName)}`,i=`git@bitbucket.org:${t.owner}/${t.repoName}.git`,s=await Kt(n,"GET",o);if(s.status===200&&s.data){if(s.data.is_private!==!0)throw hd(t);return r.info(`mirror ${t.owner}/${t.repoName} already exists \u2014 reusing`),{spec:t,sshUrl:i,created:!1}}r.info(`creating mirror ${t.owner}/${t.repoName} (bitbucket)`);let a=await Kt(n,"POST",o,{json:{scm:"git",is_private:!0,description:"CodePipe mirror \u2014 pipeline branches and PRs for this repository"}});if(a.status===404||!a.data?.slug)throw new Error(`Bitbucket cannot create ${t.owner}/${t.repoName} \u2014 check the workspace and that the credential may create repositories in it`);return{spec:t,sshUrl:i,created:!0}}async function ov(t,e,r){let n=I_(t);if((await n.raw(["rev-parse","--is-shallow-repository"])).trim()==="true")throw new Error("this clone is shallow \u2014 the mirror would be seeded with partial history. Run `git fetch --unshallow` first");if((await n.listRemote(["--heads",e])).trim().length>0)return r.info("mirror already has branches \u2014 leaving its content alone"),{seeded:!1};r.info("seeding mirror with the repository's branches and tags\u2026");let i=(await n.raw(["for-each-ref","refs/remotes/origin","--format=%(refname)"])).split(`
1016
+ `).map(a=>a.trim()).filter(a=>a.length>0&&a!=="refs/remotes/origin/HEAD");if(i.length===0)throw new Error("the local clone has no origin branches to seed from");let s=i.map(a=>`${a}:refs/heads/${a.slice(20)}`);return await n.push([e,...s]),await n.push([e,"--tags"]),{seeded:!0}}function __(t,e){let r=e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-");return`${t}-${r}-mirror`.replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"")}function j_(t,e,r){return e.mirror?{host:e.mirror.host,owner:e.mirror.owner,repoName:e.mirror.repoName}:{host:r.host,owner:r.owner,repoName:__(t,e.repoName)}}function iv(t,e,r){let n=new Map,o=[];for(let i of e){let s=j_(t,i,r),a=`${s.host}:${s.owner.toLowerCase()}/${s.repoName.toLowerCase()}`,c=n.get(a);if(c)throw new Error(`repositories "${c}" and "${i.name}" both map to the mirror ${s.owner}/${s.repoName} \u2014 mirroring them into one repository would merge their histories. Give one an explicit mirror name (mirror.repo in project.yaml) and re-run`);n.set(a,i.name),o.push({repo:i,spec:s})}return o}var sv=E(()=>{"use strict";ki()});var uv={};Me(uv,{ensureEmbeddedWorker:()=>$a,spawnWorkerProcess:()=>xa,upCommand:()=>Sa,workerChildEnv:()=>lv,workerStartArgs:()=>cv});import{spawn as av}from"node:child_process";import{existsSync as gd,writeFileSync as N_}from"node:fs";import{homedir as O_,hostname as L_}from"node:os";import{join as fo}from"node:path";async function M_(t,e,r){let n=Ve(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Nt(e)} points at a different HUB (${n.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let o;try{o=await ny(t.hubUrl.replace(/\/$/,""),n.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(o==="unsupported")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(o==="ok")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${n.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${Nt(e)} still holds its token.
1017
+ 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`),_f(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function D_(t,e,r){let n=Ve(e)!==null;if(!await M_(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 Gs(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof J&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof J&&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 J?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 nn({hub:t.hubUrl,token:o,name:r.name??`${L_()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function U_(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=Qe(r.sealPublicKey);if(!X(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Yi(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 $a(t,e,r){await D_(t,e,r),U_(t.projectId,e)}function cv(t){return[...t?["--profile",t]:[],"worker","start"]}function lv(t){let e={...t};for(let r of qc)delete e[r];return e}function xa(t){let e=av(process.execPath,[t.entry,...cv(t.profile)],{stdio:["ignore","pipe","pipe"],env:lv(process.env)}),r=n=>{for(let o of n.toString("utf-8").split(`
1018
+ `))o.length>0&&t.onLine(o)};return e.stdout?.on("data",r),e.stderr?.on("data",r),e}async function B_(t,e){let r=process.cwd(),n=fo(r,gt);if(_n(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(gd(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 se(t.hubUrl,t.cliToken,t.projectId)}catch(p){console.warn(`[up] could not fetch the project summary (${p instanceof Error?p.message:String(p)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await yd(r);if(!gf(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=X(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await ra({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=fo(O_(),".codepipe",e?fo("profiles",e,"context-config"):"context-config");us(c.contextDir,l,a);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};gd(fo(c.contextDir,"local.yaml"))||(Jr(c.contextDir),Ho(c.contextDir,_t(u,!0,s?.youtrack?.url)),console.log("[up] personal project config seeded with defaults \u2014 review .codepipe/local.yaml")),gd(fo(c.contextDir,"project.yaml"))||(N_(fo(c.contextDir,"project.yaml"),hs(u,s?.youtrack?.url)),console.log("[up] shared project config seeded from the HUB summary \u2014 review .codepipe/project.yaml")),console.log(`[up] project context materialized \u2192 ${n}`)}async function Sa(t){let{cfg:e,profile:r}=Nn(t.profile);if(t.debug){let f=typeof t.debug=="string"&&t.debug.trim()?t.debug.trim():"agent-request";process.env.CODEPIPE_DEBUG=f,console.log(`[up] debug logging on (${f}) \u2192 ~/.codepipe/debug/${e.projectId}/`)}await B_(e,r),await $a(e,r,t);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(f,m)=>{let y=b=>w=>{for(let k of w.toString("utf-8").split(`
1005
1019
  `))k.length>0&&b.write(`${m} ${k}
1006
- `)};f.stdout?.on("data",y(process.stdout)),f.stderr?.on("data",y(process.stderr))},i=(f,m)=>{let y=Kk(process.execPath,[n,...m],{stdio:["ignore","pipe","pipe"],env:process.env});return o(y,f),y};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=ma({entry:n,profile:r,onLine:f=>process.stdout.write(`[worker] ${f}
1020
+ `)};f.stdout?.on("data",y(process.stdout)),f.stderr?.on("data",y(process.stderr))},i=(f,m)=>{let y=av(process.execPath,[n,...m],{stdio:["ignore","pipe","pipe"],env:process.env});return o(y,f),y};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=xa({entry:n,profile:r,onLine:f=>process.stdout.write(`[worker] ${f}
1007
1021
  `)}),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=f=>{if(!l){l=!0,console.log(`
1008
- [up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${m} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:f,child:m})=>new Promise(y=>{m.on("exit",(b,w)=>y({name:f,code:b??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var ga=E(()=>{"use strict";ht();no();Ge();Jt();cu();Hr();Le();ue();Et();yi()});import{existsSync as tn,mkdirSync as Vk,readFileSync as ya,readdirSync as m_,writeFileSync as zk}from"node:fs";import{join as De,resolve as Xk}from"node:path";import{setTimeout as sd}from"node:timers/promises";import{cancel as Jk,confirm as wi,intro as Zk,isCancel as ld,log as A,multiselect as h_,outro as ad,password as bi,select as yt,spinner as ud,text as $e}from"@clack/prompts";import{simpleGit as ao}from"simple-git";function me(t){Jk(t),process.exit(1)}function ve(t){return ld(t)&&me("aborted"),t}function ae(t){return ld(t)&&me("aborted"),typeof t=="string"?t:""}async function Qk(t={}){Zk("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();gk();let r=hk(e),n,o=!1;r&&Object.keys(r.answers).length>0?ve(await wi({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(A.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new io(e,r),o=!0):(Ju(e),n=new io(e)):n=new io(e);let i=t.force===!0?null:await id(e),s=await n.ask("target",async()=>ve(await yt({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i??(t.force===!0?null:await y_(e,n)),a?A.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||tv(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ae(await $e({message:"HUB URL",placeholder:vt,initialValue:ee("HUB_URL")??vt,validate:$=>$.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>co()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>lo(c,l)),d=null;s==="farm"&&(d=await g_(c,u));let f=a?k_(a.parsed.repoName):"",m=await n.ask("projectId",async()=>ae(await $e({message:"project id (slug)",placeholder:f||"acme",...f?{initialValue:f}:{},validate:$=>nr.test($.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>ae(await $e({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()),b=await n.ask("language",()=>A_()),w=await n.ask("automationLevel",async()=>ve(await yt({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),x=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>ve(await yt({message:"how much access should CodePipe have to your repositories?",options:[{value:"no",label:"read and write \u2014 branches and pull requests go into your repositories"},{value:"yes",label:"read only \u2014 CodePipe mirrors them and works in the mirrors",hint:"a mirror is a full copy of the history, in the account you choose next"}],initialValue:"no"}))))==="yes";x&&A.message("read-only token tip: if you want CodePipe to review pull requests people open in your repositories, the token also needs PR-comment permission (GitHub: Pull requests write; Bitbucket: pullrequest:write). Code stays read-only either way.");let h=await n.ask("trackerProvider",async()=>ve(await yt({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"}))),T=h==="internal",R=null,v,_=!0;if(T){let $,P=ud();P.start("checking task-key prefixes on your account\u2026");try{$=await Dg(c,u,{excludeProjectId:m}),P.stop("prefixes checked")}catch{P.stop("could not reach the HUB",1),me("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 S=jc(_c(y),$);v=await n.ask("trackerPrefix",async()=>ae(await $e({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:S,initialValue:S,validate:I=>{let F=I.trim();if(!Dr.test(F))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if($.has(F.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else R=await n.ask("youtrack",()=>uv()),v=await n.ask("youtrackProjectKey",async()=>ae(await $e({message:"YouTrack project key",placeholder:"DEV",validate:$=>$.trim().length>0?void 0:"required"})).trim()),_=await n.ask("youtrackWrites",async()=>ve(await wi({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let N=n.get("tokens")??{},G=()=>n.set("tokens",N),W=await n.ask("repos",()=>E_(N,l,a,{onCred:G,initial:n.get("reposPartial")??[],onProgress:$=>n.set("reposPartial",$)}));n.delete("reposPartial");let C=null,g="",B="";if(x){let $=ve(await n.ask("mirrorHost",async()=>ve(await yt({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(V=>({value:V,label:V===W[0]?.host?`${V} (same as your repositories)`:V})),initialValue:W[0]?.host??"github"}))));g=ae(await n.ask("mirrorToken",async()=>ve(await bi({message:`token that may CREATE and PUSH repositories on ${$}`})))).trim(),$==="bitbucket"&&(B=ae(await n.ask("mirrorEmail",async()=>ve(await $e({message:"Atlassian account email for that token",...N.bitbucket?.email?{placeholder:N.bitbucket.email,defaultValue:N.bitbucket.email}:{}})))).trim());let P=await Dk($,g,B||void 0),S=$==="bitbucket"?"workspace slug":"username or organization (not an email)",F=ae(await n.ask("mirrorOwnerLogin",async()=>ve(await $e({message:`account for the mirrors \u2014 ${$} ${S}`,...P?{placeholder:P,defaultValue:P}:{},validate:V=>{let he=(V??"").trim();if(!he&&!P)return"required";if(he.includes("@"))return`that looks like an email \u2014 a ${$} ${S} is expected`;if(/\s/.test(he))return"no spaces"}})))).trim()||P||"";if(!F||F.includes("@")){Jk("mirrors need a host account to live in (a username/organization, not an email)");return}C={host:$,owner:F}}let L=await R_(await n.ask("contextRepo",()=>av(m,W,N,l,C??void 0)),m,W,N,l,G,$=>n.set("contextRepo",$),C??void 0),{spec:q,mode:te}=L,de;T||(A.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),de=await n.ask("assigneeLogin",async()=>ae(await $e({message:"your YouTrack login (the assignee value)",...R?.login?{initialValue:R.login}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()));let wt=await n.ask("llmProvider",async()=>{for(;;){if(ve(await yt({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";A.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),Ft=s==="farm"?null:Vt();Ft&&A.success(`Claude: using this machine's login${Ft.email?` (${Ft.email})`:""} \u2014 no token needed.`);let we=wt==="claude"&&!Ft?await n.ask("claudeToken",()=>ik(ok("claude"),{farm:s==="farm"})):"",We;if(we){let $=await cm(we);if($){let P=Za($);P&&(We=P,A.warn(`Claude subscription is missing some recommended models \u2014 regimen.yaml will use ${P} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/regimen.yaml.`))}}let Be={projectId:m,name:y,automationLevel:w,repos:W,trackerProvider:h,youtrackProjectKey:v,language:b};A.step(`${te==="attach"?"attaching to":"provisioning"} Context Repo ${q.owner}/${q.name} (${q.host})\u2026`);let bt;try{bt=await oo(Be,q,{...cv(N),youtrackWrites:_,...R?{trackerUrl:R.url}:{},mode:te,log:{info:$=>A.message($),warn:$=>A.warn($)}})}catch($){me(`Context Repo provisioning failed: ${$ instanceof Error?$.message:String($)}`)}Be.contextRepo=bt,A.success(`Context Repo ready: ${bt.owner}/${bt.name}@${bt.branch}`),A.step(`registering project on ${c}\u2026`);let Ie;try{Ie=await gr(c,u,Be)}catch($){if($ instanceof J&&$.status===409){A.warn(`project ${m} already exists on HUB \u2014 reusing it`);try{Ie=await se(c,u,m)}catch(P){throw P instanceof J&&me(`HUB \u2192 ${P.status} ${P.message}`),P}}else if($ instanceof J&&$.status===401)n.delete("cliToken"),me("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if($ instanceof J)me(`HUB \u2192 ${$.status} ${$.message}`);else throw $}let st=Ie.contextRepo??bt;A.success(`project ${Ie.projectId} ready (${Ie.provisioningStatus})`);let kt=R?{url:R.url,token:R.token}:void 0;if(s==="farm"){let $=d,P={...N,...we?{claude:{oauthToken:we}}:{},...kt?{youtrack:kt}:{}},S=N.github?.token;if(st.host==="github"&&S)try{let he=Py(`devpipe-${m}`);await Ay(st,S,he.publicKey,`devpipe-${m}`),P.contextSsh={privateKey:he.privateKey},A.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(he){A.warn(`could not set up Context Repo SSH deploy key (${he instanceof Error?he.message:String(he)}); the farm will fall back to the token path.`)}let I={projectId:m,config:{hubUrl:c,cliToken:u,projectId:m},secrets:P,contextRepo:st,projectConfig:Lt(Be,_,R?.url,de||void 0,wt,We)},F=Zt($.farm.publicKey,JSON.stringify(I));A.step(`handing project ${m} to farm ${$.farm.name}\u2026`);let V;try{V=await As(c,u,$.farm.farmId,{projectId:m,sealedBundle:F})}catch(he){throw he instanceof J&&me(he.status===409?`farm ${$.farm.name} is offline \u2014 start it and re-run.`:he.status===504?`farm ${$.farm.name} did not respond in time.`:`HUB \u2192 ${he.status} ${he.message}`),he}V.ok||me(`farm rejected provisioning: ${V.error??"unknown error"}`),await cd(c,u,m,st,S,Ie.repos,null,N),n.clear(),ad(`done. project ${m} is now hosted on farm ${$.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}lv(N),await ov(e,st.cloneUrl,st.branch),sv(e);try{Mn(De(e,nt),e,{info:$=>A.message($),warn:$=>A.warn($)})}catch($){A.warn(`skills materialize failed \u2014 ${$ instanceof Error?$.message:String($)}`)}a&&await $_(e);{let $=De(e,nt);Ln($);let P=Lt(Be,_,R?.url,de||void 0,wt,We),S=Do($,P);S.length>0&&A.success(`local project config \u2192 .codepipe/{${S.join(", ")}}`),pr(m,P,{info:I=>A.message(I),warn:I=>A.warn(I)})}await iv(e,Ie.repos),await S_(e,Ie.repos);let er=!1;if(x&&C&&(er=await x_(e,De(e,nt),m,Ie.repos,{host:C.host,owner:C.owner,token:g,...B?{email:B}:{}}),er)){let $=De(e,nt);pr(m,{projectYaml:ya(De($,"project.yaml"),"utf-8"),regimenYaml:ya(De($,"regimen.yaml"),"utf-8")},{info:P=>A.message(P),warn:P=>A.warn(P)})}let U={hubUrl:c,cliToken:u,projectId:m,...N,...we?{claude:{oauthToken:we}}:{},...kt?{youtrack:kt}:{},...er?{mirrorWrite:{token:g,host:C.host,...B?{email:B}:{}}}:{}};ie(U),Yt({hubUrl:c,cliToken:u,projectId:m,accountEmail:p},m),A.success(`secrets \u2192 ${Nt(m)}`),await cd(c,u,m,st,N.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,Ie.repos,e,N),n.clear();let K=`${c}/?project=${encodeURIComponent(m)}`;ur(K),ad(`done. your project on the dashboard (sign in there to work with it):
1022
+ [up] ${f} \u2014 stopping both roles`);for(let{child:m}of c)m.exitCode===null&&m.kill(f);setTimeout(()=>{for(let{name:m,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${m} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=c.map(({name:f,child:m})=>new Promise(y=>{m.on("exit",(b,w)=>y({name:f,code:b??(w?1:0)}))})),d=await Promise.race(p);l||(console.log(`[up] ${d.name} exited (code ${d.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(d.code)}var Ea=E(()=>{"use strict";kt();co();We();Bt();bu();Zr();Be();de();Ct();Si()});import{existsSync as un,mkdirSync as pv,readFileSync as fv,readdirSync as F_,writeFileSync as mv}from"node:fs";import{join as lt,resolve as hv}from"node:path";import{setTimeout as wd}from"node:timers/promises";import{cancel as gv,confirm as Ei,intro as yv,isCancel as vd,log as A,multiselect as G_,outro as bd,password as Ri,select as $t,spinner as $d,text as $e}from"@clack/prompts";import{simpleGit as mo}from"simple-git";function me(t){gv(t),process.exit(1)}function ve(t){return vd(t)&&me("aborted"),t}function ae(t){return vd(t)&&me("aborted"),typeof t=="string"?t:""}async function wv(t={}){yv("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Lk();let r=Ok(e),n,o=!1;r&&Object.keys(r.answers).length>0?ve(await Ei({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(A.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new uo(e,r),o=!0):(cd(e),n=new uo(e)):n=new uo(e);let i=t.force===!0?null:await yd(e),s=await n.ask("target",async()=>ve(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??(t.force===!0?null:await H_(e,n)),a?A.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||kv(e,t.force===!0));let c=await n.ask("hubUrl",async()=>ae(await $e({message:"HUB URL",placeholder:Et,initialValue:ee("HUB_URL")??Et,validate:$=>$.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>ho()),{cliToken:u,accountEmail:p}=await n.ask("bootstrap",()=>go(c,l)),d=null;s==="farm"&&(d=await K_(c,u));let f=a?Y_(a.parsed.repoName):"",m=await n.ask("projectId",async()=>ae(await $e({message:"project id (slug)",placeholder:f||"acme",...f?{initialValue:f}:{},validate:$=>ir.test($.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>ae(await $e({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()),b=await n.ask("language",()=>oj()),w=await n.ask("automationLevel",async()=>ve(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"}))),x=(s==="farm"?"no":await n.ask("mirrorChoice",async()=>ve(await $t({message:"how much access should CodePipe have to your repositories?",options:[{value:"no",label:"read and write \u2014 branches and pull requests go into your repositories"},{value:"yes",label:"read only \u2014 CodePipe mirrors them and works in the mirrors",hint:"a mirror is a full copy of the history, in the account you choose next"}],initialValue:"no"}))))==="yes";x&&A.message("read-only token tip: if you want CodePipe to review pull requests people open in your repositories, the token also needs PR-comment permission (GitHub: Pull requests write; Bitbucket: pullrequest:write). Code stays read-only either way.");let h=await n.ask("trackerProvider",async()=>ve(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"}))),T=h==="internal",R=null,v,P=!0;if(T){let $,_=$d();_.start("checking task-key prefixes on your account\u2026");try{$=await oy(c,u,{excludeProjectId:m}),_.stop("prefixes checked")}catch{_.stop("could not reach the HUB",1),me("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 S=Fc(Bc(y),$);v=await n.ask("trackerPrefix",async()=>ae(await $e({message:"task key prefix (tasks become <PREFIX>-1, <PREFIX>-2, \u2026)",placeholder:S,initialValue:S,validate:I=>{let F=I.trim();if(!Hr.test(F))return"uppercase letters/digits, 2\u201310 chars, starting with a letter (e.g. TASK)";if($.has(F.toUpperCase()))return"this prefix is already used by another project on your account \u2014 pick another"}})).trim())}else R=await n.ask("youtrack",()=>Cv()),v=await n.ask("youtrackProjectKey",async()=>ae(await $e({message:"YouTrack project key",placeholder:"DEV",validate:$=>$.trim().length>0?void 0:"required"})).trim()),P=await n.ask("youtrackWrites",async()=>ve(await Ei({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})));let N=n.get("tokens")??{},G=()=>n.set("tokens",N),W=await n.ask("repos",()=>Z_(N,l,a,{onCred:G,initial:n.get("reposPartial")??[],onProgress:$=>n.set("reposPartial",$)}));n.delete("reposPartial");let C=null,g="",B="";if(x){let $=ve(await n.ask("mirrorHost",async()=>ve(await $t({message:"where should the mirrors live? (your Context Repo will default there too)",options:["github","gitlab","bitbucket"].map(V=>({value:V,label:V===W[0]?.host?`${V} (same as your repositories)`:V})),initialValue:W[0]?.host??"github"}))));g=ae(await n.ask("mirrorToken",async()=>ve(await Ri({message:`token that may CREATE and PUSH repositories on ${$}`})))).trim(),$==="bitbucket"&&(B=ae(await n.ask("mirrorEmail",async()=>ve(await $e({message:"Atlassian account email for that token",...N.bitbucket?.email?{placeholder:N.bitbucket.email,defaultValue:N.bitbucket.email}:{}})))).trim());let _=await nv($,g,B||void 0),S=$==="bitbucket"?"workspace slug":"username or organization (not an email)",F=ae(await n.ask("mirrorOwnerLogin",async()=>ve(await $e({message:`account for the mirrors \u2014 ${$} ${S}`,..._?{placeholder:_,defaultValue:_}:{},validate:V=>{let he=(V??"").trim();if(!he&&!_)return"required";if(he.includes("@"))return`that looks like an email \u2014 a ${$} ${S} is expected`;if(/\s/.test(he))return"no spaces"}})))).trim()||_||"";if(!F||F.includes("@")){gv("mirrors need a host account to live in (a username/organization, not an email)");return}C={host:$,owner:F}}let L=await Q_(await n.ask("contextRepo",()=>Rv(m,W,N,l,C??void 0)),m,W,N,l,G,$=>n.set("contextRepo",$),C??void 0),{spec:q,mode:te}=L,le;T||(A.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml)."),le=await n.ask("assigneeLogin",async()=>ae(await $e({message:"your YouTrack login (the assignee value)",...R?.login?{initialValue:R.login}:{},validate:$=>$.trim().length>0?void 0:"required"})).trim()));let ut=await n.ask("llmProvider",async()=>{for(;;){if(ve(await $t({message:"LLM provider",options:[{value:"claude",label:"Claude",hint:"recommended"},{value:"codex",label:"Codex",hint:"coming soon"}],initialValue:"claude"}))==="claude")return"claude";A.warn("Codex support is coming soon \u2014 pick Claude for now.")}}),Wt=s==="farm"?null:Zt();Wt&&A.success(`Claude: using this machine's login${Wt.email?` (${Wt.email})`:""} \u2014 no token needed.`);let we=ut==="claude"&&!Wt?await n.ask("claudeToken",()=>Ek(Sk("claude"),{farm:s==="farm"})):"",Ke;if(we){let $=await km(we);if($){let _=sc($);_&&(Ke=_,A.warn(`Claude subscription is missing some recommended models \u2014 local.yaml will use ${_} for all roles. Adjust later in the dashboard (Project Settings \u2192 llm.models) or .codepipe/local.yaml.`))}}let _e={projectId:m,name:y,automationLevel:w,repos:W,trackerProvider:h,youtrackProjectKey:v,language:b};A.step(`${te==="attach"?"attaching to":"provisioning"} Context Repo ${q.owner}/${q.name} (${q.host})\u2026`);let xt;try{xt=await lo(_e,q,{...Tv(N),youtrackWrites:P,...R?{trackerUrl:R.url}:{},mode:te,log:{info:$=>A.message($),warn:$=>A.warn($)}})}catch($){me(`Context Repo provisioning failed: ${$ instanceof Error?$.message:String($)}`)}_e.contextRepo=xt,A.success(`Context Repo ready: ${xt.owner}/${xt.name}@${xt.branch}`),A.step(`registering project on ${c}\u2026`);let Ie;try{Ie=await vr(c,u,_e)}catch($){if($ instanceof J&&$.status===409){A.warn(`project ${m} already exists on HUB \u2014 reusing it`);try{Ie=await se(c,u,m)}catch(_){throw _ instanceof J&&me(`HUB \u2192 ${_.status} ${_.message}`),_}}else if($ instanceof J&&$.status===401)n.delete("cliToken"),me("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if($ instanceof J)me(`HUB \u2192 ${$.status} ${$.message}`);else throw $}let dt=Ie.contextRepo??xt;A.success(`project ${Ie.projectId} ready (${Ie.provisioningStatus})`);let St=R?{url:R.url,token:R.token}:void 0;if(s==="farm"){let $=d,_={...N,...we?{claude:{oauthToken:we}}:{},...St?{youtrack:St}:{}},S=N.github?.token;if(dt.host==="github"&&S)try{let he=Xy(`devpipe-${m}`);await Jy(dt,S,he.publicKey,`devpipe-${m}`),_.contextSsh={privateKey:he.privateKey},A.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(he){A.warn(`could not set up Context Repo SSH deploy key (${he instanceof Error?he.message:String(he)}); the farm will fall back to the token path.`)}let I={projectId:m,config:{hubUrl:c,cliToken:u,projectId:m},secrets:_,contextRepo:dt,localConfig:_t(_e,P,R?.url,le||void 0,ut,Ke),projectConfig:{projectYaml:hs(_e,R?.url),regimenYaml:_t(_e,P,R?.url,le||void 0,ut,Ke).localYaml}},F=tr($.farm.publicKey,JSON.stringify(I));A.step(`handing project ${m} to farm ${$.farm.name}\u2026`);let V;try{V=await Fs(c,u,$.farm.farmId,{projectId:m,sealedBundle:F})}catch(he){throw he instanceof J&&me(he.status===409?`farm ${$.farm.name} is offline \u2014 start it and re-run.`:he.status===504?`farm ${$.farm.name} did not respond in time.`:`HUB \u2192 ${he.status} ${he.message}`),he}V.ok||me(`farm rejected provisioning: ${V.error??"unknown error"}`),await kd(c,u,m,dt,S,Ie.repos,null,N),n.clear(),bd(`done. project ${m} is now hosted on farm ${$.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}Iv(N),await xv(e,dt.cloneUrl,dt.branch),Ev(e);try{Gn(lt(e,gt),e,{info:$=>A.message($),warn:$=>A.warn($)})}catch($){A.warn(`skills materialize failed \u2014 ${$ instanceof Error?$.message:String($)}`)}a&&await z_(e);{let $=lt(e,gt);Jr($);let _=_t(_e,P,R?.url,le||void 0,ut,Ke),S=Ho($,_);S.length>0&&A.success(`personal project config \u2192 .codepipe/{${S.join(", ")}}`),Xr(m,_,{info:I=>A.message(I),warn:I=>A.warn(I)})}await Sv(e,Ie.repos),await J_(e,Ie.repos);let Nr=!1;x&&C&&(Nr=await X_(e,lt(e,gt),m,Ie.repos,{host:C.host,owner:C.owner,token:g,...B?{email:B}:{}}));let U={hubUrl:c,cliToken:u,projectId:m,...N,...we?{claude:{oauthToken:we}}:{},...St?{youtrack:St}:{},...Nr?{mirrorWrite:{token:g,host:C.host,...B?{email:B}:{}}}:{}};ie(U),Jt({hubUrl:c,cliToken:u,projectId:m,accountEmail:p},m),A.success(`secrets \u2192 ${Ut(m)}`),await kd(c,u,m,dt,N.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,Ie.repos,e,N),n.clear();let K=`${c}/?project=${encodeURIComponent(m)}`;fr(K),bd(`done. your project on the dashboard (sign in there to work with it):
1009
1023
  ${K}
1010
- starting codepipe up \u2014 the CLI daemon and an agent worker, with their logs on screen. Ctrl+C to stop (restart anytime with \`codepipe up\` from this folder).`);let{upCommand:D}=await Promise.resolve().then(()=>(ga(),qk));await D({profile:void 0})}async function cd(t,e,r,n,o,i=[],s=null,a={}){let c=await bk(n,o),l=!1;if(!c)try{l=await $k(i,{localRoot:s,tokens:a})}catch{l=!1}let u=wk({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await h_({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(ld(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let f=je(s);if(!f)throw new Error("workspace not found");let{bootstrapWorkspaceModel:m}=await Promise.resolve().then(()=>(ni(),Ks)),y=await m(f,void 0,{onLog:b=>A.message(b)});A.success(`project map ready: ${y.events} task events mined from history`)}catch(f){A.warn(`could not build the project map: ${f instanceof Error?f.message:String(f)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:f}=await ri(t,e,r,{reindex:!1,backfill:!0});A.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){A.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:f}=await ri(t,e,r,{reindex:u.reindex});A.success(`indexing queued (job ${f}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(f){A.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function g_(t,e){let r;try{r=await Ng(t,e)}catch(c){throw c instanceof J&&me(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&me("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=ve(await yt({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=Cs(i.farmId,i.publicKey)}catch(c){me(c instanceof Error?c.message:String(c))}return ve(await wi({message:`confirm farm ${i.name} cred-channel fingerprint:
1024
+ starting codepipe up \u2014 the CLI daemon and an agent worker, with their logs on screen. Ctrl+C to stop (restart anytime with \`codepipe up\` from this folder).`);let{upCommand:D}=await Promise.resolve().then(()=>(Ea(),uv));await D({profile:void 0})}async function kd(t,e,r,n,o,i=[],s=null,a={}){let c=await Uk(n,o),l=!1;if(!c)try{l=await Gk(i,{localRoot:s,tokens:a})}catch{l=!1}let u=Dk({indexExists:c,localClones:s!==null,reposNonEmpty:l}),p=await G_({message:u.message,options:u.options,initialValues:u.initialValues,required:!1});if(vd(p))return;let d=new Set(p);if(d.has("map")&&s!==null)try{let f=Ne(s);if(!f)throw new Error("workspace not found");let{bootstrapWorkspaceModel:m}=await Promise.resolve().then(()=>(ui(),Qs)),y=await m(f,void 0,{onLog:b=>A.message(b)});A.success(`project map ready: ${y.events} task events mined from history`)}catch(f){A.warn(`could not build the project map: ${f instanceof Error?f.message:String(f)}. Registration is not affected \u2014 run \`codepipe model bootstrap\` later.`)}if(d.has("backfill"))try{let{jobId:f}=await li(t,e,r,{reindex:!1,backfill:!0});A.success(`retrospective architecture analysis queued (job ${f}); decision drafts will appear on the project card for review once a SANDBOX picks up the job.`)}catch(f){A.warn(`could not start the retrospective analysis: ${f instanceof Error?f.message:String(f)}. Registration is not affected.`)}if(d.has("index"))try{let{jobId:f}=await li(t,e,r,{reindex:u.reindex});A.success(`indexing queued (job ${f}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(f){A.warn(`could not start indexing: ${f instanceof Error?f.message:String(f)}. You can retry later \u2014 registration is not affected.`)}}async function K_(t,e){let r;try{r=await ey(t,e)}catch(c){throw c instanceof J&&me(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&me("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=ve(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=Us(i.farmId,i.publicKey)}catch(c){me(c instanceof Error?c.message:String(c))}return ve(await Ei({message:`confirm farm ${i.name} cred-channel fingerprint:
1011
1025
  ${s}
1012
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||me("farm fingerprint not confirmed \u2014 aborting."),Is(i.farmId,s),{farm:i,fingerprint:s}}async function ev(t){Zk(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();tv(e,t.force===!0);let r=ae(await $e({message:"HUB URL",initialValue:ee("HUB_URL")??vt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await co(),{cliToken:o,accountEmail:i}=await lo(r,n);A.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await se(r,o,t.projectId)}catch(d){throw d instanceof J&&me(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||me(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await uv(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let f=s.repos.find(m=>m.host===d);await wa(d,l,f?.owner??s.contextRepo.owner,n,f?.repoName)}lv(l),await ov(e,s.contextRepo.cloneUrl,s.contextRepo.branch),sv(e);{let d=De(e,nt);Ln(d);let f={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},m=Lt(f,!0,c?.url,void 0,s.llmProvider??tt),y=Do(d,m);y.length>0&&A.success(`local project config \u2192 .codepipe/{${y.join(", ")}} (defaults \u2014 review and adjust)`),pr(t.projectId,m,{info:b=>A.message(b),warn:b=>A.warn(b)})}await iv(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ie(p),Yt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),A.success(`secrets \u2192 ${Nt(t.projectId)}`),await cd(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),ad("done.")}function tv(t,e){if(!tn(t)){Vk(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=m_(t).filter(o=>!r.has(o));n.length!==0&&(e||me(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function id(t){if(!tn(De(t,".git")))return null;try{let e=Ze(await rv(t));return e?{parsed:e,defaultBranch:await nv(t)}:null}catch{return null}}async function rv(t){try{return(await ao(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function y_(t,e){if(!tn(De(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await rv(t);return A.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),ae(await $e({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:i=>!i||!i.trim()||Ze(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?Ze(r):null;return n?{parsed:n,defaultBranch:await nv(t)}:null}async function w_(t){try{let e=await ao().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}async function b_(t,e){try{return(await ao().listRemote([t,`refs/heads/${e}`])).trim().length>0}catch{return!0}}async function nv(t){let e=ao(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 k_(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return nr.test(e)?e:""}function v_(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function $_(t){let e=De(t,".gitignore"),r=tn(e)?ya(e,"utf-8"):"";if(v_(r))return;if(!ve(await wi({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){A.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
1026
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||me("farm fingerprint not confirmed \u2014 aborting."),Ds(i.farmId,s),{farm:i,fingerprint:s}}async function bv(t){yv(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();kv(e,t.force===!0);let r=ae(await $e({message:"HUB URL",initialValue:ee("HUB_URL")??Et,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await ho(),{cliToken:o,accountEmail:i}=await go(r,n);A.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await se(r,o,t.projectId)}catch(d){throw d instanceof J&&me(`HUB \u2192 ${d.status} ${d.message}`),d}s.contextRepo||me(`project ${t.projectId} has no Context Repo on HUB`);let c=s.trackerProvider==="internal"?null:await Cv(),l={},u=new Set(s.repos.map(d=>d.host));u.add(s.contextRepo.host);for(let d of u){let f=s.repos.find(m=>m.host===d);await Ra(d,l,f?.owner??s.contextRepo.owner,n,f?.repoName)}Iv(l),await xv(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Ev(e);{let d=lt(e,gt);Jr(d);let f={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.trackerProvider?{trackerProvider:s.trackerProvider}:{},...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{},...s.language?{language:s.language}:{}},m=_t(f,!0,c?.url,void 0,s.llmProvider??it),y=Ho(d,m);y.length>0&&A.success(`local project config \u2192 .codepipe/{${y.join(", ")}} (defaults \u2014 review and adjust)`),Xr(t.projectId,m,{info:b=>A.message(b),warn:b=>A.warn(b)})}await Sv(e,s.repos);let p={hubUrl:r,cliToken:o,projectId:t.projectId,...l,...c?{youtrack:{url:c.url,token:c.token}}:{}};ie(p),Jt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),A.success(`secrets \u2192 ${Ut(t.projectId)}`),await kd(r,o,t.projectId,s.contextRepo,l.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,s.repos,e,l),bd("done.")}function kv(t,e){if(!un(t)){pv(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=F_(t).filter(o=>!r.has(o));n.length!==0&&(e||me(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function yd(t){if(!un(lt(t,".git")))return null;try{let e=rt(await vv(t));return e?{parsed:e,defaultBranch:await $v(t)}:null}catch{return null}}async function vv(t){try{return(await mo(t).remote(["get-url","origin"])||"").toString().trim()}catch{return""}}async function H_(t,e){if(!un(lt(t,".git")))return null;let r=await e.ask("inPlaceOrigin",async()=>{let o=await vv(t);return A.warn(o?`this folder is a git checkout, but its origin (${o}) is not a github.com / gitlab.com / bitbucket.org URL`:"this folder is a git checkout without an `origin` remote"),ae(await $e({message:"clone URL of this repository \u2014 blank if this folder is not the project repo",placeholder:"git@github.com:acme/api.git",validate:i=>!i||!i.trim()||rt(i)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim()}),n=r?rt(r):null;return n?{parsed:n,defaultBranch:await $v(t)}:null}async function W_(t){try{let e=await mo().listRemote(["--symref",t,"HEAD"]);return/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m.exec(e)?.[1]??null}catch{return null}}async function q_(t,e){try{return(await mo().listRemote([t,`refs/heads/${e}`])).trim().length>0}catch{return!0}}async function $v(t){let e=mo(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 Y_(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return ir.test(e)?e:""}function V_(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function z_(t){let e=lt(t,".gitignore"),r=un(e)?fv(e,"utf-8"):"";if(V_(r))return;if(!ve(await Ei({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){A.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
1013
1027
  `)?"":`
1014
- `;zk(e,r+o+`
1028
+ `;mv(e,r+o+`
1015
1029
  # codepipe workspace (added by \`codepipe init\`)
1016
1030
  .codepipe/
1017
- `),A.success(`.codepipe/ added to ${Xk(e)}`)}async function co(){let t="";try{t=(await ao().raw(["config","--global","user.email"])||"").trim()}catch{}return ae(await $e({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function lo(t,e){A.step(`connecting account ${e}`);let r;try{r=await Ug(t,e)}catch(s){throw s instanceof ti&&me(`${e} is not authorized on this HUB yet.
1031
+ `),A.success(`.codepipe/ added to ${hv(e)}`)}async function ho(){let t="";try{t=(await mo().raw(["config","--global","user.email"])||"").trim()}catch{}return ae(await $e({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function go(t,e){A.step(`connecting account ${e}`);let r;try{r=await iy(t,e)}catch(s){throw s instanceof ci&&me(`${e} is not authorized on this HUB yet.
1018
1032
  Sign up at ${t} (registration form on the login screen),
1019
1033
  wait for the operator to approve it by email, then re-run
1020
- \`codepipe init\` with the same email.`),s}r.accountCreated&&A.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&A.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(ur(r.authorizeUrl),A.message(`a browser tab was opened to confirm this CLI:
1034
+ \`codepipe init\` with the same email.`),s}r.accountCreated&&A.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&A.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(fr(r.authorizeUrl),A.message(`a browser tab was opened to confirm this CLI:
1021
1035
  ${r.authorizeUrl}
1022
1036
  `+(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
1023
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&A.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),A.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await Bg(t,r.requestId)}catch(a){A.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await sd(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&A.message(`connected as ${a} (the account confirmed in the browser).`),A.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&me("the HUB rejected this account"),s.status==="expired"&&me("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,A.message(`email confirmed. waiting for the operator to approve your account\u2026
1024
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await sd(5e3);continue}await sd(2e3)}me("bootstrap timed out")}async function ov(t,e,r){let n=De(t,nt);if(tn(De(n,".git"))){A.message(`${n} already cloned \u2014 skipping`);return}tn(n)&&me(`${n} exists but is not a git repo \u2014 remove it and re-run`),Vk(n,{recursive:!0}),A.step(`cloning Context Repo \u2192 ${n}`);try{await ao().clone(e,n,["--branch",r]),A.success(`cloned ${e}`)}catch(o){me(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function x_(t,e,r,n,o){if(n.length===0)return!1;A.step(`setting up ${n.length} mirror(s) \u2014 your repositories stay read-only`);let i={info:l=>A.message(` ${l}`),warn:l=>A.warn(` ${l}`)},s={...o.host==="github"?{githubToken:o.token}:{},...o.host==="gitlab"?{gitlabToken:o.token}:{},...o.host==="bitbucket"&&o.email?{bitbucket:{email:o.email,apiToken:o.token}}:{}},a;try{a=Bk(r,n,o)}catch(l){return A.warn(` ${l instanceof Error?l.message:String(l)}`),A.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}let c=[];for(let{repo:l,spec:u}of a)try{let p=await Mk(u,s,i);await Uk(De(t,l.mountAs??l.name),p.sshUrl,i),c.push({repoName:l.name,spec:u})}catch(p){return A.warn(` ${l.name}: mirror not set up \u2014 ${p instanceof Error?p.message:String(p)}`),A.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}for(let l of c)Th(e,l.repoName,l.spec);for(let l of c)A.success(` ${l.repoName} \u2192 ${l.spec.owner}/${l.spec.repoName}`);return!0}async function iv(t,e){if(e.length===0)return;A.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await hi(t,r,{log:{info:o=>A.message(o),warn:o=>A.warn(o)}});for(let o of n)A.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}async function S_(t,e){let r=De(t,nt);for(let n of e){let o=De(t,n.mountAs??n.name),i;try{i=await gi(o)}catch(s){A.warn(`git-flow detection skipped for "${n.name}": ${s instanceof Error?s.message:String(s)}`);continue}try{await da({contextDir:r,repoName:n.name,facts:i,log:s=>A.message(s)})}catch(s){throw A.error(`git-flow for "${n.name}" was NOT saved: ${s instanceof Error?s.message:String(s)}`),s}}}function sv(t){let e=De(t,nt,".gitignore"),r="";if(tn(e)&&(r=ya(e,"utf-8")),Yk.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
1037
+ otherwise use the emailed link the page offers.`))),r.approvalRequired&&A.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),A.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await sy(t,r.requestId)}catch(a){A.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await wd(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&A.message(`connected as ${a} (the account confirmed in the browser).`),A.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&me("the HUB rejected this account"),s.status==="expired"&&me("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,A.message(`email confirmed. waiting for the operator to approve your account\u2026
1038
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await wd(5e3);continue}await wd(2e3)}me("bootstrap timed out")}async function xv(t,e,r){let n=lt(t,gt);if(un(lt(n,".git"))){A.message(`${n} already cloned \u2014 skipping`);return}un(n)&&me(`${n} exists but is not a git repo \u2014 remove it and re-run`),pv(n,{recursive:!0}),A.step(`cloning Context Repo \u2192 ${n}`);try{await mo().clone(e,n,["--branch",r]),A.success(`cloned ${e}`)}catch(o){me(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function X_(t,e,r,n,o){if(n.length===0)return!1;A.step(`setting up ${n.length} mirror(s) \u2014 your repositories stay read-only`);let i={info:l=>A.message(` ${l}`),warn:l=>A.warn(` ${l}`)},s={...o.host==="github"?{githubToken:o.token}:{},...o.host==="gitlab"?{gitlabToken:o.token}:{},...o.host==="bitbucket"&&o.email?{bitbucket:{email:o.email,apiToken:o.token}}:{}},a;try{a=iv(r,n,o)}catch(l){return A.warn(` ${l instanceof Error?l.message:String(l)}`),A.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}let c=[];for(let{repo:l,spec:u}of a)try{let p=await rv(u,s,i);await ov(lt(t,l.mountAs??l.name),p.sshUrl,i),c.push({repoName:l.name,spec:u})}catch(p){return A.warn(` ${l.name}: mirror not set up \u2014 ${p instanceof Error?p.message:String(p)}`),A.warn("mirroring is all-or-nothing: NO mirrors were recorded and the project keeps working against its own repositories. Fix the cause and re-run `codepipe init`"),!1}for(let l of c)await qh(e,l.repoName,l.spec);for(let l of c)A.success(` ${l.repoName} \u2192 ${l.spec.owner}/${l.spec.repoName}`);return!0}async function Sv(t,e){if(e.length===0)return;A.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await $i(t,r,{log:{info:o=>A.message(o),warn:o=>A.warn(o)}});for(let o of n)A.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}async function J_(t,e){let r=lt(t,gt);for(let n of e){let o=lt(t,n.mountAs??n.name),i;try{i=await xi(o)}catch(s){A.warn(`git-flow detection skipped for "${n.name}": ${s instanceof Error?s.message:String(s)}`);continue}try{await va({contextDir:r,repoName:n.name,facts:i,log:s=>A.message(s)})}catch(s){throw A.error(`git-flow for "${n.name}" was NOT saved: ${s instanceof Error?s.message:String(s)}`),s}}}function Ev(t){let e=lt(t,gt,".gitignore"),r="";if(un(e)&&(r=fv(e,"utf-8")),dv.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
1025
1039
  `)||r.length===0?"":`
1026
- `,i=Yk.join(`
1040
+ `,i=dv.join(`
1027
1041
  `)+`
1028
- `;zk(e,r+o+(r?`
1029
- `:"")+i),A.message(`appended runtime entries to ${Xk(e)}`)}async function E_(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await wa(s.host,t,s.owner,e,s.repoName),i?.(),o.push({name:s.repoName,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:a,mountAs:"."}),n.onProgress?.(o),A.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;ve(await wi({message:o.length===0?"Add a project repository?":`Project repositories: ${o.map(m=>m.name).join(", ")}. Add another one?`,initialValue:o.length===0}));){let a=ae(await $e({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||Ze(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=Ze(a);A.message(`${c.host}: ${c.owner}/${c.repoName}`),await wa(c.host,t,c.owner,e,c.repoName),i?.();let l=ae(await $e({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=await w_(a),p="";for(;p=ae(await $e({message:"default branch",placeholder:u??"main",...u?{initialValue:u}:{}})).trim(),!(!p||!u||p===u||await b_(a,p));)A.warn(`branch "${p}" does not exist in ${c.owner}/${c.repoName} (the repository's default is "${u}")`);let d=ae(await $e({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),f={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(f.defaultBranch=p),d&&d!==l&&(f.mountAs=d),o.push(f),n.onProgress?.(o)}return o}async function av(t,e,r,n,o){A.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let i=ve(await yt({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));i==="attach"&&A.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=ae(await $e({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:jt(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!Ze(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=Ze(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await T_(),u=ae(await $e({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=ae(await $e({message:"Context Repo name",placeholder:jt(t),initialValue:jt(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function cv(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??Pn()}}async function R_(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await wa(l.host,n,l.owner,o),i?.();let p=ud();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await ak(l,cv(n),{explain:u==="attach"});if(d.found===!0)return p.stop(`${l.owner}/${l.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),c;if(d.found==="unknown")return p.stop(`could not check ${l.owner}/${l.name} (${d.detail}) \u2014 continuing`,1),c;if(u==="create")return p.stop(`${l.owner}/${l.name} not found \u2014 will be created`),c;p.stop(d.detail,1);let f=ve(await yt({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(f==="abort"&&me("aborted"),f==="create")return c={spec:l,mode:"create"},s(c),c;c=await av(e,r,n,o,a),s(c)}}async function T_(){return ve(await yt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function ba(t,e){let r=ud();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 lv(t){Ho(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Wo(t.gitlab?.token??process.env.GITLAB_TOKEN),qo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function wa(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await I_(r);i?e.github=i:A.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await C_(r,n,o);i?e.bitbucket=i:A.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await P_();i?e.gitlab=i:A.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function I_(t){for(;;){let e=ae(await bi({message:`GitHub PAT \u2014 blank to skip
1042
+ `;mv(e,r+o+(r?`
1043
+ `:"")+i),A.message(`appended runtime entries to ${hv(e)}`)}async function Z_(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;await Ra(s.host,t,s.owner,e,s.repoName),i?.(),o.push({name:s.repoName,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:a,mountAs:"."}),n.onProgress?.(o),A.success(`added this repository: ${s.host}: ${s.owner}/${s.repoName} (this folder, default branch ${a})`)}for(;ve(await Ei({message:o.length===0?"Add a project repository?":`Project repositories: ${o.map(m=>m.name).join(", ")}. Add another one?`,initialValue:o.length===0}));){let a=ae(await $e({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:m=>!m||!m.trim()||rt(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=rt(a);A.message(`${c.host}: ${c.owner}/${c.repoName}`),await Ra(c.host,t,c.owner,e,c.repoName),i?.();let l=ae(await $e({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=await W_(a),p="";for(;p=ae(await $e({message:"default branch",placeholder:u??"main",...u?{initialValue:u}:{}})).trim(),!(!p||!u||p===u||await q_(a,p));)A.warn(`branch "${p}" does not exist in ${c.owner}/${c.repoName} (the repository's default is "${u}")`);let d=ae(await $e({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),f={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(f.defaultBranch=p),d&&d!==l&&(f.mountAs=d),o.push(f),n.onProgress?.(o)}return o}async function Rv(t,e,r,n,o){A.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let i=ve(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"}));i==="attach"&&A.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let s=o?.host??e[0]?.host,a=o?.owner??e[0]?.owner,c;if(s&&a){let l=ae(await $e({message:`Context Repo \u2014 a name (hosted at ${s}: ${a}/<name>) or a full clone URL`,initialValue:Dt(t),validate:p=>{let d=(p??"").trim();if(!d)return"required";if(!rt(d)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(d))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=rt(l);c=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:s,owner:a,name:l}}else{let l=await ej(),u=ae(await $e({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=ae(await $e({message:"Context Repo name",placeholder:Dt(t),initialValue:Dt(t),validate:d=>d.trim().length>0?void 0:"required"})).trim();c={host:l,owner:u,name:p}}return{spec:c,mode:i}}function Tv(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??Mn()}}async function Q_(t,e,r,n,o,i,s,a){let c=t;for(;;){let{spec:l,mode:u}=c;await Ra(l.host,n,l.owner,o),i?.();let p=$d();p.start(`checking ${l.owner}/${l.name} on ${l.host}\u2026`);let d=await Tk(l,Tv(n),{explain:u==="attach"});if(d.found===!0)return p.stop(`${l.owner}/${l.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),c;if(d.found==="unknown")return p.stop(`could not check ${l.owner}/${l.name} (${d.detail}) \u2014 continuing`,1),c;if(u==="create")return p.stop(`${l.owner}/${l.name} not found \u2014 will be created`),c;p.stop(d.detail,1);let f=ve(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(f==="abort"&&me("aborted"),f==="create")return c={spec:l,mode:"create"},s(c),c;c=await Rv(e,r,n,o,a),s(c)}}async function ej(){return ve(await $t({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Ta(t,e){let r=$d();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 Iv(t){Jo(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Zo(t.gitlab?.token??process.env.GITLAB_TOKEN),Qo(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Ra(t,e,r,n,o){if(!e[t])if(t==="github"){let i=await tj(r);i?e.github=i:A.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let i=await rj(r,n,o);i?e.bitbucket=i:A.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let i=await nj();i?e.gitlab=i:A.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function tj(t){for(;;){let e=ae(await Ri({message:`GitHub PAT \u2014 blank to skip
1030
1044
  classic PAT: 'repo' + 'workflow'
1031
1045
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
1032
1046
  if org: approve token in org Settings \u2192 Personal access tokens.
1033
- (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await ba("GitHub",()=>or(e,t?{owner:t}:void 0)))return{token:e};A.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function C_(t,e,r){for(A.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
1047
+ (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo.)`})).trim();if(!e)return;if(await Ta("GitHub",()=>ar(e,t?{owner:t}:void 0)))return{token:e};A.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function rj(t,e,r){for(A.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
1034
1048
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
1035
1049
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes:
1036
1050
  read:repository:bitbucket + write:repository:bitbucket +
1037
1051
  read:pullrequest:bitbucket + write:pullrequest:bitbucket
1038
1052
  \u2014 write scopes do NOT include read: pick BOTH scopes of each pair
1039
1053
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
1040
- The token is shown ONCE \u2014 copy it right away.`);;){let n=ae(await $e({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=ae(await bi({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){A.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await ba("Bitbucket",async()=>{let i=await ir(n,o,t);if(t&&r){let s=await qi(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};A.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function P_(){for(;;){let t=ae(await bi({message:`GitLab PAT \u2014 blank to skip
1041
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await ba("GitLab",()=>sr(t))){let e=await Pf(t);return e&&A.warn(e),{token:t}}A.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function A_(){let t="__other__",e=async()=>ae(await $e({message:"language name (in English, e.g. Ukrainian)",validate:s=>{let a=s.trim();if(a.length===0)return"required";if(a.length>40)return`\u2264 ${40} chars`}})).trim(),r=ve(await yt({message:"project language",options:[...bn.map(s=>({value:s,label:s==="English"?"English (default)":s})),{value:t,label:"other\u2026"}],initialValue:"English"})),n=r===t?await e():r;if(n==="English")return{primary:n,context:n,tasks:n,docs:n,code_comments:n,chat:ke};let o=[{key:"context",label:"context documents (knowledge, ADRs, task artifacts)",initial:n},{key:"tasks",label:"tracker issues the agent drafts",initial:n},{key:"docs",label:"documentation in the project repos",initial:n},{key:"code_comments",label:"code comments",initial:n},{key:"chat",label:"chat with the agent",initial:ke}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",ke].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===ke?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=ve(await yt({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function uv(){for(;;){let t=ae(await $e({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=ae(await bi({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await ba("YouTrack",()=>lr({baseUrl:t,token:e}))){let r=await Hf({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}A.warn("re-enter the YouTrack URL / token.")}}var Yk,yi=E(()=>{"use strict";Ye();M();ht();sk();Vi();Ge();Jt();Hr();jn();fi();au();ca();zt();Kr();yk();Le();kk();xk();Kl();cs();ue();ua();us();rd();nd();Fk();ts();Oo();Et();Yk=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});M();Ye();Ge();import{Command as Mj}from"commander";Ge();ue();async function vf(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=Rt(e);r&&!t.force&&(console.error(`already configured at ${Rn(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Yt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...X(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ie(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Rn(e)}`)}Uc();Ge();import{homedir as lu}from"node:os";import{join as oi}from"node:path";Ye();M();import{existsSync as Ty,rmSync as HT}from"node:fs";import{join as Vr}from"node:path";import{simpleGit as WT}from"simple-git";import"ws";Ye();Oo();ue();import{createHash as Gx}from"node:crypto";import{hostname as Kx}from"node:os";function Bc(t){return Gx("sha256").update(t).digest("hex").slice(0,12)}function Hx(){let t=ee("ACCOUNT_EMAIL")?.trim();return t?t.toLowerCase():Vt()?.email?.toLowerCase()}function Tf(t){let e=Vt(),r=Hx(),n=ee("ACCOUNT_ID")?.trim(),o=ee("ACCOUNT_LABEL")?.trim();if(n)return{accountId:n,sourceKey:`explicit:${n}`,label:o||n,...r?{email:r}:{}};let i=Cn(t),s=o||(r?`${r}${e?.organizationType?` \xB7 ${e.organizationType}`:""}`:Kx());if(i)return{accountId:`acct-${Bc(i)}`,sourceKey:`token:${Bc(i)}`,label:s,...r?{email:r}:{}};let a=Gi(e);return{accountId:`acct-${Bc(a)}`,sourceKey:a,label:s,...r?{email:r}:{}}}Ye();jn();ue();el();async function pm(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(ee("ORIGIN")==="farm"||ee("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await Qc(Yi())}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 Xt(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=X(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},ie(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()}}Ye();function fm(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?ee("ORIGIN")==="farm"||ee("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function tl(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}Vi();import{existsSync as gS}from"node:fs";import{join as yS}from"node:path";import{simpleGit as wS}from"simple-git";async function mm(t,e){if(!gS(yS(t,".git")))return{status:"skipped"};let r=wS(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${bS(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 bS(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as nl,readFileSync as bm,readdirSync as $S,watch as xS}from"node:fs";import{join as Mo}from"node:path";M();import{existsSync as hm,readFileSync as gm,readdirSync as kS,statSync as vS}from"node:fs";import{join as rl}from"node:path";import{parse as ym}from"yaml";function zi(t){let e=rl(t,"actions"),r=[],n=[];if(!hm(e))return{defs:r,errors:n};let o;try{o=kS(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=rl(e,s);try{if(!vS(a).isFile())continue;let c=nc(s,ym(gm(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 wm(t){let e={},r=rl(t,"project.yaml");if(!hm(r))return e;let n;try{n=ym(gm(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))!rt.test(i)||Wt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}var Xi=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,Mo(this.contextDir,"prompts"),Mo(this.contextDir,"actions")];for(let n of r)if(nl(n))try{let o=xS(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=zi(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=Mo(this.contextDir,e);if(!nl(r))return null;try{return bm(r,"utf-8")}catch{return null}}readPrompts(){let e=Mo(this.contextDir,"prompts"),r={};if(!nl(e))return r;let n;try{n=$S(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=bm(Mo(e,o),"utf-8")}catch{}}return r}};ft();import{existsSync as dl,readFileSync as Rm,readdirSync as LS}from"node:fs";import{join as Tm}from"node:path";import{simpleGit as MS}from"simple-git";var DS=/^(\d{4})-(.+)\.md$/,US="0000-template.md";function BS(t){let e=t.split(`
1042
- `),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 FS(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
1054
+ The token is shown ONCE \u2014 copy it right away.`);;){let n=ae(await $e({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=ae(await Ri({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){A.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Ta("Bitbucket",async()=>{let i=await cr(n,o,t);if(t&&r){let s=await ts(n,o,t,r);if(s)throw new Error(s)}return i}))return{email:n,apiToken:o};A.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function nj(){for(;;){let t=ae(await Ri({message:`GitLab PAT \u2014 blank to skip
1055
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Ta("GitLab",()=>lr(t))){let e=await Gf(t);return e&&A.warn(e),{token:t}}A.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function oj(){let t="__other__",e=async()=>ae(await $e({message:"language name (in English, e.g. Ukrainian)",validate:s=>{let a=s.trim();if(a.length===0)return"required";if(a.length>40)return`\u2264 ${40} chars`}})).trim(),r=ve(await $t({message:"project language",options:[...In.map(s=>({value:s,label:s==="English"?"English (default)":s})),{value:t,label:"other\u2026"}],initialValue:"English"})),n=r===t?await e():r;if(n==="English")return{primary:n,context:n,tasks:n,docs:n,code_comments:n,chat:ke};let o=[{key:"context",label:"context documents (knowledge, ADRs, task artifacts)",initial:n},{key:"tasks",label:"tracker issues the agent drafts",initial:n},{key:"docs",label:"documentation in the project repos",initial:n},{key:"code_comments",label:"code comments",initial:n},{key:"chat",label:"chat with the agent",initial:ke}],i={primary:n};for(let s of o){let a=new Set,c=[s.initial,n,"English",ke].filter(u=>a.has(u)?!1:(a.add(u),!0)).map(u=>({value:u,label:u===ke?"auto \u2014 mirror the language of the user's material":u}));c.push({value:t,label:"other\u2026"});let l=ve(await $t({message:`language for ${s.label}`,options:c,initialValue:s.initial}));i[s.key]=l===t?await e():l}return i}async function Cv(){for(;;){let t=ae(await $e({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=ae(await Ri({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Ta("YouTrack",()=>pr({baseUrl:t,token:e}))){let r=await rm({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}A.warn("re-enter the YouTrack URL / token.")}}var dv,Si=E(()=>{"use strict";Je();M();kt();Rk();ns();We();Bt();Zr();Bn();ki();wu();wa();Qt();zr();Mk();Be();Bk();Kk();eu();ks();de();ka();vs();fd();md();sv();ps();Fo();Ct();dv=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"]});M();Je();We();import{Command as u0}from"commander";We();de();async function jf(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=Pt(e);r&&!t.force&&(console.error(`already configured at ${jn(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Jt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...X(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};ie(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${jn(e)}`)}Yc();We();import{homedir as ku}from"node:os";import{join as di}from"node:path";Je();M();import{existsSync as Yy,rmSync as gI}from"node:fs";import{join as rn}from"node:path";import{simpleGit as yI}from"simple-git";import"ws";Je();Fo();de();import{createHash as aS}from"node:crypto";import{hostname as cS}from"node:os";function Vc(t){return aS("sha256").update(t).digest("hex").slice(0,12)}function lS(){let t=ee("ACCOUNT_EMAIL")?.trim();return t?t.toLowerCase():Zt()?.email?.toLowerCase()}function Uf(t){let e=Zt(),r=lS(),n=ee("ACCOUNT_ID")?.trim(),o=ee("ACCOUNT_LABEL")?.trim();if(n)return{accountId:n,sourceKey:`explicit:${n}`,label:o||n,...r?{email:r}:{}};let i=Ln(t),s=o||(r?`${r}${e?.organizationType?` \xB7 ${e.organizationType}`:""}`:cS());if(i)return{accountId:`acct-${Vc(i)}`,sourceKey:`token:${Vc(i)}`,label:s,...r?{email:r}:{}};let a=Ji(e);return{accountId:`acct-${Vc(a)}`,sourceKey:a,label:s,...r?{email:r}:{}}}Je();Bn();de();cl();async function Sm(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(ee("ORIGIN")==="farm"||ee("CLAUDE_AUTOLOGIN")!=="1"){s("autologin_disabled");return}let a;try{a=await al(rs())}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 er(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=X(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},ie(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()}}Je();function Em(t,e){let r=t.find(n=>n.kind==="claude");return r?.present===!0&&r.ok===!1?ee("ORIGIN")==="farm"||ee("CLAUDE_AUTOLOGIN")!=="1"||e?"none":"open":r?.ok===!0?"rearm":"none"}function ll(t,e){return`${t.replace(/\/$/,"")}/?project=${encodeURIComponent(e)}`}ns();import{existsSync as OS}from"node:fs";import{join as LS}from"node:path";import{simpleGit as MS}from"simple-git";async function Rm(t,e){if(!OS(LS(t,".git")))return{status:"skipped"};let r=MS(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${DS(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 DS(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as hl,readFileSync as Km,readdirSync as uE,watch as dE}from"node:fs";import{join as Wo}from"node:path";M();import{existsSync as Tm,readFileSync as Im,readdirSync as US,statSync as BS}from"node:fs";import{join as ul}from"node:path";import{parse as Cm}from"yaml";function os(t){let e=ul(t,"actions"),r=[],n=[];if(!Tm(e))return{defs:r,errors:n};let o;try{o=US(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=ul(e,s);try{if(!BS(a).isFile())continue;let c=dc(s,Cm(Im(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 Pm(t){let e={},r=ul(t,"project.yaml");if(!Tm(r))return e;let n;try{n=Cm(Im(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))!st.test(i)||zt(i)||(typeof s=="string"?e[i]=s:(typeof s=="number"||typeof s=="boolean")&&(e[i]=String(s)));return e}Bt();var ds=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,Wo(this.contextDir,"prompts"),Wo(this.contextDir,"actions")];for(let n of r)if(hl(n))try{let o=dE(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=os(this.contextDir),r=this.readFile("project.yaml"),n=this.readFile("regimen.yaml"),o=n!==null?null:Um(r,this.readFile("local.yaml"),this.log).merged;return{type:"config_observation",projectId:this.projectId,projectYaml:n!==null?r:o,regimenYaml:n!==null?n:o,prompts:this.readPrompts(),actions:e.defs,actionErrors:e.errors}}readFile(e){let r=Wo(this.contextDir,e);if(!hl(r))return null;try{return Km(r,"utf-8")}catch{return null}}readPrompts(){let e=Wo(this.contextDir,"prompts"),r={};if(!hl(e))return r;let n;try{n=uE(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=Km(Wo(e,o),"utf-8")}catch{}}return r}};Le();import{existsSync as gl,readFileSync as Hm,readdirSync as pE}from"node:fs";import{join as Wm}from"node:path";import{simpleGit as fE}from"simple-git";var mE=/^(\d{4})-(.+)\.md$/,hE="0000-template.md";function gE(t){let e=t.split(`
1056
+ `),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 yE(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
1043
1057
  `),a=s.findIndex(w=>w.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],p="",d=null,f=a>=0?a+1:0;for(let w=f;w<s.length;w++){let k=(s[w]??"").trim();if(k===""){f=w+1;continue}let x=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(k);if(!x)break;let h=(x[1]??"").trim().toLowerCase(),T=(x[2]??"").trim(),R=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(k);R&&(d=parseInt(R[1]??"",10)),h==="tasks"&&(p=T),l.has(h)||u.push(k),f=w+1}let m=p?p.includes(n)?p:`${p}, ${n}`:n,y=s.slice(f).join(`
1044
1058
  `).replace(/^\n+/,""),b=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${m}`,...u,"",y].join(`
1045
1059
  `);return{content:b.endsWith(`
1046
1060
  `)?b:b+`
1047
- `,supersedes:d}}function GS(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
1061
+ `,supersedes:d}}function wE(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
1048
1062
 
1049
- - **Status:** superseded by ADR-${r}`):n}function KS(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(`
1063
+ - **Status:** superseded by ADR-${r}`):n}function bE(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(`
1050
1064
  `)+`
1051
- `}async function Im(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await MS(t).pull(void 0,void 0,["--rebase"])}catch{}let i=b=>o==="staging"?`adr/DRAFT-${b}.md`:`tasks/${e}/adr/DRAFT-${b}.md`,s=[],a=[];for(let b of r){let w=Te(t,i(b));if(!dl(w)){a.push(b);continue}s.push({slug:b,content:Rm(w,"utf-8")})}let c=Tm(t,"adr"),l=new Map;if(dl(c))for(let b of LS(c)){let w=DS.exec(b);!w||b===US||l.set(b,{num:parseInt(w[1]??"",10),slug:w[2]??"",content:Rm(Tm(c,b),"utf-8")})}let u=Math.max(0,...[...l.values()].map(b=>b.num))+1,p=new Map,d=[],f=[];for(let b of s){if([...l.entries()].find(([,R])=>R.slug===b.slug&&R.content.includes(e))){f.push(b.slug);continue}let k=u++,x=`${String(k).padStart(4,"0")}-${b.slug}.md`,{content:h,supersedes:T}=FS(b.content,k,b.slug,e,n);if(p.set(x,h),l.set(x,{num:k,slug:b.slug,content:h}),d.push(`adr/${x}`),T!==null){let R=[...l.keys()].find(v=>v.startsWith(`${String(T).padStart(4,"0")}-`));if(R&&R!==x){let v=GS(p.get(R)??l.get(R).content,k);p.set(R,v),l.set(R,{...l.get(R),content:v})}}}let m=[];if(o==="staging")for(let b of s)dl(Te(t,`adr/DRAFT-${b.slug}.md`))&&m.push({path:`adr/DRAFT-${b.slug}.md`,content:"",deleted:!0});if(d.length===0&&m.length===0)return{promoted:d,skipped:f,missing:a};if(d.length>0){let b=[...l.entries()].map(([w,k])=>({num:k.num,file:w,header:BS(k.content)}));p.set("INDEX.md",KS(b))}for(let[b,w]of p.entries())m.push({path:`adr/${b}`,content:w});let y=d.length>0?`adr(${e}): promote ${s.map(b=>b.slug).join(", ")}`:`adr(${e}): drop stale staged ${f.join(", ")}`;return await Pe(t,m,y),{promoted:d,skipped:f,missing:a}}ft();ts();Jt();M();import{existsSync as Am,readFileSync as ZS}from"node:fs";import{join as _m}from"node:path";function QS(t){for(let e of[xt,fn]){let r=_m(t,e);if(Am(r))try{return Ca(ZS(r,"utf-8"))}catch{return 0}}return 0}function eE(t,e,r,n=6){let o=e<n,i=o?Pa(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function rs(t,e){return eE(e,QS(t),r=>Am(_m(t,r)))}M();zt();import{existsSync as Hm,mkdirSync as IE,mkdtempSync as CE,rmSync as Wm,writeFileSync as qm}from"node:fs";import{tmpdir as PE}from"node:os";import{dirname as AE,join as os}from"node:path";import{simpleGit as hl}from"simple-git";Hr();function _E(t){return`codepipe/context-migration-v${t}`}function jE(t){let e=Aa(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 \`${xt}\` stamp (renamed from \`${fn}\``,"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(`
1052
- `)}async function Ym(t,e,r,n){let o=hl(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=rs(t,e);if(!i.outdated)return i;let s=_E(i.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await NE(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Gr(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:jE(i)});return n.info(`[ctx] migration PR opened: ${p.url}`),{...i,migrationPrUrl:p.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function NE(t,e,r,n,o,i,s){let a=hl(t),c=CE(os(PE(),"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(Un(l,u).map(y=>[y.path,y.content])),d=0;for(let y of n.missingPaths){if(y===xt)continue;let b=p.get(y);if(b==null){s.warn(`[ctx] migration: no template for ${y} \u2014 skipped`);continue}let w=os(c,y);Hm(w)||(IE(AE(w),{recursive:!0}),qm(w,b),d++)}qm(os(c,xt),ko(n.currentVersion)),d++;let f=os(c,fn);Hm(f)&&(Wm(f,{force:!0}),d++);let m=hl(c);await m.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await m.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await m.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Wm(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as OE,readFileSync as LE,writeFileSync as ME}from"node:fs";import{homedir as DE}from"node:os";import{join as Vm}from"node:path";import{parseDocument as UE}from"yaml";function BE(t,e,r){let n={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(n.default_branch=t.defaultBranch),e!==void 0&&(n.mirror=e),r!==void 0&&(n.git=r),n}function FE(t,e){let r=UE(t),n=new Map,o=new Map,i=r.toJS();for(let s of i?.repos??[]){if(!s||typeof s!="object")continue;let a=typeof s.name=="string"?s.name:String(s.repo??"");a&&(s.mirror!==void 0&&s.mirror!==null&&n.set(a,s.mirror),s.git!==void 0&&s.git!==null&&o.set(a,s.git))}return r.set("repos",e.map(s=>BE(s,n.get(s.name),o.get(s.name)))),r.toString()}function GE(t,e){let r=[Vm(DE(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(Vm(e,"project.yaml")),r}function Ko(t,e,r){let n=[],o=[];for(let i of GE(t,r))if(OE(i))try{let s=LE(i,"utf-8"),a=FE(s,e);a!==s&&(ME(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}Gn();ht();ue();function QE(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),t.mirrorWrite?.token&&(r.mirrorWrite={token:t.mirrorWrite.token,...t.mirrorWrite.host?{host:t.mirrorWrite.host}:{}}),r}function ah(t,e,r,n){let o=QE(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=Di(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=Zt(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}ht();ue();zt();Kr();jn();cs();function dh(t){let e=X(t);if(!e)return null;if(!e.sealKey){let r=as();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ie(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ze(e.sealKey.publicKey)}}async function ph(t,e,r,n){let o;try{o=JSON.parse(Kn(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=X(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 or(o.token);return i.github={token:o.token},Hn(i,()=>{process.env.GH_TOKEN=o.token,ch(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await sr(o.token);return i.gitlab={token:o.token},Hn(i,()=>{process.env.GITLAB_TOKEN=o.token,lh(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 ir(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Hn(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,uh(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 lr({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Hn(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 Xt(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Hn(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Hn(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 Hn(t,e){ie(t),e()}M();M();import{spawn as eR}from"node:child_process";var tR=124,fh=16*1024,mh=4e3;function rR(t,e,r,n,o,i){let s={...t},a=(c,l)=>{Wt(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 hh(t){let{def:e,onEvent:r}=t,n=rR(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
1053
- `,o.length>fh&&(o=o.slice(o.length-fh))},s=(a,c)=>{let l=c.length>mh?c.slice(0,mh)+"\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 nR(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 nR(t,e,r,n,o){return new Promise(i=>{let s=eR("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??rc)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=f=>{let m="";return{data:y=>{m+=y.toString("utf-8");let b;for(;(b=m.indexOf(`
1054
- `))!==-1;)o(f,m.slice(0,b).replace(/\r$/,"")),m=m.slice(b+1)},flush:()=>{m.length>0&&o(f,m.replace(/\r$/,"")),m=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",f=>{clearTimeout(l),o("stderr",`spawn failed: ${f.message}`),i(127)}),s.on("close",(f,m)=>{clearTimeout(l),p.flush(),d.flush(),i(a?tR:f??(m?1:0))})})}ft();ft();import{existsSync as oR,readFileSync as iR,statSync as gh}from"node:fs";var yh=2*1024*1024;function sR(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function wh(t,e){let r=Te(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!oR(r)||!gh(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=gh(r);if(n>yh)throw new Error(`file too large: ${e} is ${n} bytes (limit ${yh})`);let o=iR(r);return sR(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}ue();M();import{existsSync as aR,readFileSync as cR,writeFileSync as lR}from"node:fs";import{join as uR}from"node:path";import{parseDocument as dR}from"yaml";async function bh(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=dc(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=uR(t,o);if(!aR(s))throw new Error(`${o} not found in context repo (${t})`);let a=dR(cR(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);lR(s,a.toString()),n.push(o)}return{files:n}}us();import{existsSync as $l,readFileSync as xl,writeFileSync as pR}from"node:fs";import{join as ds}from"node:path";import{parseDocument as Sl}from"yaml";async function Ih(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=ds(t,"project.yaml");if(!$l(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Sl(xl(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=ds(t,"regimen.yaml");if(!$l(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Sl(xl(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)pR(ds(t,i.path),i.content);return{files:r.map(i=>i.path)}}function ps(t){if(!t)return"Stage";try{let e=ds(t,"project.yaml");if(!$l(e))return"Stage";let n=Sl(xl(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}zt();is();Gn();M();ft();import{existsSync as OR,readFileSync as LR}from"node:fs";import{join as bg}from"node:path";import{simpleGit as Dl}from"simple-git";M();import{existsSync as Ch,readFileSync as Ph,readdirSync as fR}from"node:fs";import{join as El}from"node:path";import{simpleGit as mR}from"simple-git";function hR(t,e){let r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(e);if(!r)return null;let n="",o="";for(let s of r[1].split(`
1055
- `)){let a=/^(\w+):\s*(.+)$/.exec(s.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let i=r[2].trim();return!n||!o||!i||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:i,source:t}}function gR(t,e){let r=El(t,`tasks/${e}/annotations`);if(!Ch(r))return[];let n=[];for(let o of fR(r).sort())if(o.endsWith(".md")){try{let i=hR(o,Ph(El(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=Ba)break}return n}var yR=12;async function Ah(t){let{contextDir:e,taskKey:r,repoName:n,repoDir:o,commitSha:i,date:s,touchedKeys:a,identity:c}=t;if(!c)return[];let l=new Map(c.entities.filter(d=>d.status==="active").map(d=>[d.currentKey,d.entityId])),u=mR(o),p=[];for(let d of gR(e,r)){if(d.repo!==n)continue;let f=be("code",n,d.path);if(!a.has(f))continue;let m=l.get(f);if(!m)continue;let y=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,yR),b=Na(m),w=El(e,b),k=p.find(_=>_.path===b),x=k?.content??(Ch(w)?Ph(w,"utf-8"):null),h=`<!-- ${r}${y?`:${y}`:""} -->`;if(x?.includes(h))continue;let T=x??`---
1065
+ `}async function qm(t,e,r,n=new Date().toISOString().slice(0,10),o="task"){try{await fE(t).pull(void 0,void 0,["--rebase"])}catch{}let i=b=>o==="staging"?`adr/DRAFT-${b}.md`:`tasks/${e}/adr/DRAFT-${b}.md`,s=[],a=[];for(let b of r){let w=Te(t,i(b));if(!gl(w)){a.push(b);continue}s.push({slug:b,content:Hm(w,"utf-8")})}let c=Wm(t,"adr"),l=new Map;if(gl(c))for(let b of pE(c)){let w=mE.exec(b);!w||b===hE||l.set(b,{num:parseInt(w[1]??"",10),slug:w[2]??"",content:Hm(Wm(c,b),"utf-8")})}let u=Math.max(0,...[...l.values()].map(b=>b.num))+1,p=new Map,d=[],f=[];for(let b of s){if([...l.entries()].find(([,R])=>R.slug===b.slug&&R.content.includes(e))){f.push(b.slug);continue}let k=u++,x=`${String(k).padStart(4,"0")}-${b.slug}.md`,{content:h,supersedes:T}=yE(b.content,k,b.slug,e,n);if(p.set(x,h),l.set(x,{num:k,slug:b.slug,content:h}),d.push(`adr/${x}`),T!==null){let R=[...l.keys()].find(v=>v.startsWith(`${String(T).padStart(4,"0")}-`));if(R&&R!==x){let v=wE(p.get(R)??l.get(R).content,k);p.set(R,v),l.set(R,{...l.get(R),content:v})}}}let m=[];if(o==="staging")for(let b of s)gl(Te(t,`adr/DRAFT-${b.slug}.md`))&&m.push({path:`adr/DRAFT-${b.slug}.md`,content:"",deleted:!0});if(d.length===0&&m.length===0)return{promoted:d,skipped:f,missing:a};if(d.length>0){let b=[...l.entries()].map(([w,k])=>({num:k.num,file:w,header:gE(k.content)}));p.set("INDEX.md",bE(b))}for(let[b,w]of p.entries())m.push({path:`adr/${b}`,content:w});let y=d.length>0?`adr(${e}): promote ${s.map(b=>b.slug).join(", ")}`:`adr(${e}): drop stale staged ${f.join(", ")}`;return await Pe(t,m,y),{promoted:d,skipped:f,missing:a}}Le();ps();Bt();M();import{existsSync as zm,readFileSync as IE}from"node:fs";import{join as Xm}from"node:path";function CE(t){for(let e of[Tt,vn]){let r=Xm(t,e);if(zm(r))try{return Ma(IE(r,"utf-8"))}catch{return 0}}return 0}function PE(t,e,r,n=6){let o=e<n,i=o?Da(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function fs(t,e){return PE(e,CE(t),r=>zm(Xm(t,r)))}M();Qt();import{existsSync as dh,mkdirSync as rR,mkdtempSync as nR,rmSync as ph,writeFileSync as fh}from"node:fs";import{tmpdir as oR}from"node:os";import{dirname as iR,join as gs}from"node:path";import{simpleGit as kl}from"simple-git";Zr();function sR(t){return`codepipe/context-migration-v${t}`}function aR(t){let e=Ua(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 \`${vn}\``,"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(`
1066
+ `)}async function mh(t,e,r,n){let o=kl(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=fs(t,e);if(!i.outdated)return i;let s=sR(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 cR(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=Vr(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:aR(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 cR(t,e,r,n,o,i,s){let a=kl(t),c=nR(gs(oR(),"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(Hn(l,u).map(y=>[y.path,y.content])),d=0;for(let y of n.missingPaths){if(y===Tt)continue;let b=p.get(y);if(b==null){s.warn(`[ctx] migration: no template for ${y} \u2014 skipped`);continue}let w=gs(c,y);dh(w)||(rR(iR(w),{recursive:!0}),fh(w,b),d++)}fh(gs(c,Tt),Ro(n.currentVersion)),d++;let f=gs(c,vn);dh(f)&&(ph(f,{force:!0}),d++);let m=kl(c);await m.add(["-A","--",".",":(exclude)local.yaml"]),await m.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await m.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${d} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),ph(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}Le();import{existsSync as vl,readFileSync as $l,writeFileSync as hh}from"node:fs";import{homedir as lR}from"node:os";import{join as Sl}from"node:path";import{parseDocument as uR}from"yaml";function dR(t,e,r){let n={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(n.default_branch=t.defaultBranch),e!==void 0&&(n.mirror=e),r!==void 0&&(n.git=r),n}function xl(t,e){let r=uR(t),n=new Map,o=new Map,i=r.toJS();for(let s of i?.repos??[]){if(!s||typeof s!="object")continue;let a=typeof s.name=="string"?s.name:String(s.repo??"");a&&(s.mirror!==void 0&&s.mirror!==null&&n.set(a,s.mirror),s.git!==void 0&&s.git!==null&&o.set(a,s.git))}return r.set("repos",e.map(s=>dR(s,n.get(s.name),o.get(s.name)))),r.toString()}function pR(t){return Sl(lR(),".codepipe","profiles",t,"context-config","project.yaml")}async function Xo(t,e,r){let n=[],o=[],i=pR(t);if(vl(i))try{let s=$l(i,"utf-8"),a=xl(s,e);a!==s&&(hh(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}if(r){let s=Sl(r,"project.yaml");if(vl(s))try{if(vl(Sl(r,".git")))await Oe(r,async()=>{let a=$l(s,"utf-8"),c=xl(a,e);c!==a&&(await qe(r,[{path:"project.yaml",content:c}],"chore(config): update repos"),n.push(s))});else{let a=$l(s,"utf-8"),c=xl(a,e);c!==a&&(hh(s,c),n.push(s))}}catch(a){o.push({path:s,error:a instanceof Error?a.message:String(a)})}}return{updated:n,errors:o}}Yn();kt();de();function xR(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),t.mirrorWrite?.token&&(r.mirrorWrite={token:t.mirrorWrite.token,...t.mirrorWrite.host?{host:t.mirrorWrite.host}:{}}),r}function Ih(t,e,r,n){let o=xR(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=Yi(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=tr(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}kt();de();Qt();zr();Bn();ks();function _h(t){let e=X(t);if(!e)return null;if(!e.sealKey){let r=bs();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},ie(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Qe(e.sealKey.publicKey)}}async function jh(t,e,r,n){let o;try{o=JSON.parse(Vn(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=X(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 ar(o.token);return i.github={token:o.token},zn(i,()=>{process.env.GH_TOKEN=o.token,Ch(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await lr(o.token);return i.gitlab={token:o.token},zn(i,()=>{process.env.GITLAB_TOKEN=o.token,Ph(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 cr(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},zn(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Ah(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 pr({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},zn(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 er(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},zn(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},zn(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 zn(t,e){ie(t),e()}M();M();import{spawn as SR}from"node:child_process";var ER=124,Nh=16*1024,Oh=4e3;function RR(t,e,r,n,o,i){let s={...t},a=(c,l)=>{zt(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 Lh(t){let{def:e,onEvent:r}=t,n=RR(t.baseEnv??process.env,t.variables,t.secrets,e.env,t.credEnv,t.input),o="",i=a=>{o+=a+`
1067
+ `,o.length>Nh&&(o=o.slice(o.length-Nh))},s=(a,c)=>{let l=c.length>Oh?c.slice(0,Oh)+"\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 TR(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 TR(t,e,r,n,o){return new Promise(i=>{let s=SR("bash",["-lc",t],{cwd:r,env:n,stdio:["ignore","pipe","pipe"]}),a=!1,c=(e??uc)*1e3,l=setTimeout(()=>{a=!0,o("stderr",`step timed out after ${c/1e3}s \u2014 killing`),s.kill("SIGTERM"),setTimeout(()=>s.kill("SIGKILL"),5e3).unref()},c);l.unref?.();let u=f=>{let m="";return{data:y=>{m+=y.toString("utf-8");let b;for(;(b=m.indexOf(`
1068
+ `))!==-1;)o(f,m.slice(0,b).replace(/\r$/,"")),m=m.slice(b+1)},flush:()=>{m.length>0&&o(f,m.replace(/\r$/,"")),m=""}}},p=u("stdout"),d=u("stderr");s.stdout?.on("data",p.data),s.stderr?.on("data",d.data),s.on("error",f=>{clearTimeout(l),o("stderr",`spawn failed: ${f.message}`),i(127)}),s.on("close",(f,m)=>{clearTimeout(l),p.flush(),d.flush(),i(a?ER:f??(m?1:0))})})}Le();Le();import{existsSync as IR,readFileSync as CR,statSync as Mh}from"node:fs";var Dh=2*1024*1024;function PR(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function Uh(t,e){let r=Te(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!IR(r)||!Mh(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=Mh(r);if(n>Dh)throw new Error(`file too large: ${e} is ${n} bytes (limit ${Dh})`);let o=CR(r);return PR(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}de();M();Le();import{existsSync as Bh,readFileSync as Fh,writeFileSync as AR}from"node:fs";import{join as _R}from"node:path";import{parseDocument as jR}from"yaml";function Gh(t){return t==null?!0:typeof t!="object"||Array.isArray(t)?!1:Object.values(t).every(Gh)}async function Kh(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let s of e){let a=Rc(s);if(!a.ok)throw new Error(a.error);let c=r.get(a.field.file)??[];c.push({key:a.field.id,path:a.field.path,value:a.value}),r.set(a.field.file,c)}let n=(s,a,c)=>{let l=jR(a);for(let u of c)u.value===null?l.getIn(u.path)!==void 0&&l.deleteIn(u.path):l.setIn(u.path,u.value);if(s==="project.yaml"&&c.some(u=>u.path[0]==="git")){let u=l.toJS()?.git;if(Gh(u))l.deleteIn(["git"]);else{let p=sr(u);if(p.errors.length>0)throw new Error(`git section invalid after edit: ${p.errors.join("; ")}`)}}return l.toString()},o=[...r.entries()].sort(([s])=>s==="project.yaml"?-1:1),i=[];for(let[s,a]of o){let c=_R(t,s);if(s==="project.yaml"){if(!Bh(c))throw new Error(`${s} not found in context repo (${t})`);let l=a.map(u=>u.key).join(", ");await Oe(t,async()=>{let u=n(s,Fh(c,"utf-8"),a);await qe(t,[{path:s,content:u}],`chore(config): update ${l}`)}),i.push(s)}else{let l=Bh(c)?Fh(c,"utf-8"):"";AR(c,n(s,l,a)),i.push(s)}}return{files:i}}vs();Le();import{existsSync as _l,readFileSync as jl,writeFileSync as DR}from"node:fs";import{join as Nl}from"node:path";import{parseDocument as Ol}from"yaml";function kr(t,e){t.getIn(e)!==void 0&&t.deleteIn(e)}async function Vh(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.backlogScope!==void 0||e.reviewStatus!==void 0){let i=Nl(t,"project.yaml");await Oe(t,async()=>{if(!_l(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Ol(jl(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):kr(s,["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):kr(s,["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):kr(s,["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):kr(s,["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):kr(s,["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):kr(s,["youtrack","backlog_column"])}if(e.backlogScope!==void 0&&(e.backlogScope==="personal"?s.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?s.setIn(["youtrack","backlog_scope"],"shared"):kr(s,["youtrack","backlog_scope"])),e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&s.setIn(["youtrack","review_status"],a)}await qe(t,[{path:"project.yaml",content:s.toString()}],"chore(config): update youtrack settings")}),r.push("project.yaml")}if(e.assignee!==void 0||e.requireAssignee!==void 0||e.writes!==void 0){let i=Nl(t,"local.yaml"),s=Ol(_l(i)?jl(i,"utf-8"):"");if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):kr(s,["youtrack","assignee"])}if(e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),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)}DR(i,s.toString()),r.push("local.yaml")}return{files:r}}function $s(t){if(!t)return"Stage";try{let e=Nl(t,"project.yaml");if(!_l(e))return"Stage";let n=Ol(jl(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}Qt();ys();Yn();M();Le();import{existsSync as aT,readFileSync as cT}from"node:fs";import{join as Ug}from"node:path";import{simpleGit as zl}from"simple-git";M();import{existsSync as zh,readFileSync as Xh,readdirSync as UR}from"node:fs";import{join as Ll}from"node:path";import{simpleGit as BR}from"simple-git";function FR(t,e){let r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(e);if(!r)return null;let n="",o="";for(let s of r[1].split(`
1069
+ `)){let a=/^(\w+):\s*(.+)$/.exec(s.trim());a&&(a[1]==="repo"&&(n=a[2].trim()),a[1]==="path"&&(o=a[2].trim().replace(/^\.\//,"")))}let i=r[2].trim();return!n||!o||!i||o.includes("..")||o.startsWith("/")?null:{repo:n,path:o,body:i,source:t}}function GR(t,e){let r=Ll(t,`tasks/${e}/annotations`);if(!zh(r))return[];let n=[];for(let o of UR(r).sort())if(o.endsWith(".md")){try{let i=FR(o,Xh(Ll(r,o),"utf-8"));i&&n.push(i)}catch{}if(n.length>=Va)break}return n}var KR=12;async function Jh(t){let{contextDir:e,taskKey:r,repoName:n,repoDir:o,commitSha:i,date:s,touchedKeys:a,identity:c}=t;if(!c)return[];let l=new Map(c.entities.filter(d=>d.status==="active").map(d=>[d.currentKey,d.entityId])),u=BR(o),p=[];for(let d of GR(e,r)){if(d.repo!==n)continue;let f=be("code",n,d.path);if(!a.has(f))continue;let m=l.get(f);if(!m)continue;let y=(await u.raw(["rev-parse",`${i}:${d.path}`]).catch(()=>"")).trim().slice(0,KR),b=Ga(m),w=Ll(e,b),k=p.find(P=>P.path===b),x=k?.content??(zh(w)?Xh(w,"utf-8"):null),h=`<!-- ${r}${y?`:${y}`:""} -->`;if(x?.includes(h))continue;let T=x??`---
1056
1070
  entityId: ${m}
1057
1071
  ---
1058
1072
 
@@ -1060,39 +1074,39 @@ entityId: ${m}
1060
1074
 
1061
1075
  Append-only. Keyed by entityId \u2014 never by path; entries survive renames.
1062
1076
  `,R=["",`## ${s} \u2014 ${r}`,h,"",d.body,""].join(`
1063
- `),v=T+R;k?k.content=v:p.push({path:b,content:v})}return p}Al();Nl();hs();Ll();Vo();async function MR(t,e){let n=await Dl(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
1064
- `)){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 DR(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>OR(bg(t,i)));if(!n)return{};let o=bg(t,n);try{let i=LR(o,"utf-8"),s=[...new Set(i.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:n,...s.length>0?{adr:s}:{}}}catch{return{solution:n}}}async function kg(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=qr(e),a=Wr([...s.ignore,...Wn]),c=await MR(r,i),l=(await Dl(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=_l(e,n),u&&(p=new Map(u.entities.filter(T=>T.status==="active").map(T=>[T.currentKey,T.entityId])))}catch{}let d=[];for(let T of c){if(a(T.path))continue;let R=be("code",n,T.path),v=p.get(R);d.push({key:R,...v?{entityId:v}:{},churn:T.churn})}if(d.length===0)return{recorded:!1};let f=DR(e,o),m=fs(e,o),y=m?.origin==="pipeline"?m.files.filter(T=>re(T.key)?.repo!==n):[],b=m?.origin==="pipeline"?m.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...m?.title?{title:m.title}:{},...l?{date:l}:{},commits:[...new Set([...b,i])],files:[...y,...d],links:{...m?.origin==="pipeline"?m.links:{},...f}};w.links&&Object.keys(w.links).length===0&&delete w.links;let k=[...ys(e).filter(T=>T.taskKey!==o),w],x=fg(mg(e),k,o,s.cochange.halfLifeDays),h=await Ah({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(T=>T.key)),identity:u}).catch(()=>[]);await Pe(e,[{path:_r(o),content:hn(w)},{path:Ar,content:ws(x)},...h],`model: task event ${o}`);{let{rebuildSearchIndex:T}=await Promise.resolve().then(()=>(Xo(),zo));await T(e).catch(()=>{})}return{recorded:!0}}async function vg(t){let e=new Set([t.fallbackTaskKey]);try{let r=Dl(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(`
1065
- `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await UR(t.contextDir,r,t.prUrl)}async function UR(t,e,r){let n=fs(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Pe(t,[{path:_r(e),content:hn(o)}],`model: pr link for ${e}`)}Kr();import{existsSync as Sg,readFileSync as Eg}from"node:fs";import{join as Rg}from"node:path";import{parseDocument as Tg}from"yaml";Kr();var Jo=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return tm(this.cfg,e)}getIssue(e,r){return rm(this.cfg,e,r??ps(this.contextDir))}listComments(e,r){return nm(this.cfg,e,r)}downloadAttachment(e){return em(this.cfg,e)}updateStatus(e,r){return Wf(this.cfg,e,r,ps(this.contextDir))}addComment(e,r,n){return qf(this.cfg,e,r)}createIssue(e){return zf(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,ps(this.contextDir))}editIssue(e,r){return Yf(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return Xf(this.cfg,e,r,n)}fetchStateFields(e){return im(this.cfg,e)}};M();ft();import{existsSync as qR,readFileSync as YR}from"node:fs";import{randomBytes as VR}from"node:crypto";import{existsSync as Ul,readFileSync as BR,readdirSync as FR}from"node:fs";M();ft();function xs(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=WR(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:GR(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:HR(KR(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 $g(t,e,r,n=10){let o=new Set(e.map(c=>c.issue.key)),i=[],s=c=>(c.links??[]).filter(l=>l.type==="subtask").map(l=>l.targetKey);for(let c of e)i.push(...s(c.issue));let a=[];for(;i.length>0&&a.length<n;){let c=i.shift();if(o.has(c)||(o.add(c),Ul(Te(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),i.push(...s(l)))}return a}async function Ss(t,e,r){if(r.length===0)return;let n=xs(t,e,r),o=r.map(i=>i.issue.key);await Pe(t,n,`sync(${o.join(", ")}): task data`)}function GR(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(`
1066
- `)}function KR(t,e,r){let n=new Map,o=Te(t,`tasks/${e}/comments.jsonl`);if(Ul(o))for(let i of BR(o,"utf-8").split(`
1067
- `)){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=Mr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function HR(t){return t.map(e=>JSON.stringify(e)).join(`
1077
+ `),v=T+R;k?k.content=v:p.push({path:b,content:v})}return p}Gl();Wl();Es();Yl();ti();async function lT(t,e){let n=await zl(t).raw(["diff","--numstat",`${e}^`,e]).catch(()=>""),o=[];for(let i of n.split(`
1078
+ `)){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 uT(t,e){let n=[`tasks/${e}/PLAN.md`,`tasks/${e}/SOLUTION.md`].find(i=>aT(Ug(t,i)));if(!n)return{};let o=Ug(t,n);try{let i=cT(o,"utf-8"),s=[...new Set(i.match(/\bADR-\d{3,4}\b/g)??[])].sort();return{solution:n,...s.length>0?{adr:s}:{}}}catch{return{solution:n}}}async function Bg(t){let{contextDir:e,repoDir:r,repoName:n,taskKey:o,commitSha:i}=t,s=en(e),a=Qr([...s.ignore,...Xn]),c=await lT(r,i),l=(await zl(r).raw(["show","-s","--format=%cs",i])).trim(),u=null,p=new Map;try{u=Kl(e,n),u&&(p=new Map(u.entities.filter(T=>T.status==="active").map(T=>[T.currentKey,T.entityId])))}catch{}let d=[];for(let T of c){if(a(T.path))continue;let R=be("code",n,T.path),v=p.get(R);d.push({key:R,...v?{entityId:v}:{},churn:T.churn})}if(d.length===0)return{recorded:!1};let f=uT(e,o),m=xs(e,o),y=m?.origin==="pipeline"?m.files.filter(T=>re(T.key)?.repo!==n):[],b=m?.origin==="pipeline"?m.commits:[],w={modelFormatVersion:2,taskKey:o,origin:"pipeline",...m?.title?{title:m.title}:{},...l?{date:l}:{},commits:[...new Set([...b,i])],files:[...y,...d],links:{...m?.origin==="pipeline"?m.links:{},...f}};w.links&&Object.keys(w.links).length===0&&delete w.links;let k=[...Ts(e).filter(T=>T.taskKey!==o),w],x=jg(Ng(e),k,o,s.cochange.halfLifeDays),h=await Jh({contextDir:e,taskKey:o,repoName:n,repoDir:r,commitSha:i,date:l,touchedKeys:new Set(d.map(T=>T.key)),identity:u}).catch(()=>[]);await Pe(e,[{path:Dr(o),content:xn(w)},{path:Mr,content:Is(x)},...h],`model: task event ${o}`);{let{rebuildSearchIndex:T}=await Promise.resolve().then(()=>(ni(),ri));await T(e).catch(()=>{})}return{recorded:!0}}async function Fg(t){let e=new Set([t.fallbackTaskKey]);try{let r=zl(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(`
1079
+ `)){let s=i.trim();s&&e.add(s)}}catch{}for(let r of[...e].sort())await dT(t.contextDir,r,t.prUrl)}async function dT(t,e,r){let n=xs(t,e);if(!n||n.origin!=="pipeline"||n.links?.pr===r)return;let o={...n,links:{...n.links??{},pr:r}};await Pe(t,[{path:Dr(e),content:xn(o)}],`model: pr link for ${e}`)}zr();import{existsSync as Hg,readFileSync as Wg}from"node:fs";import{join as qg}from"node:path";import{parseDocument as Yg}from"yaml";zr();var oi=class{constructor(e,r){this.cfg=e;this.contextDir=r}kind="youtrack";listIssues(e){return fm(this.cfg,e)}getIssue(e,r){return mm(this.cfg,e,r??$s(this.contextDir))}listComments(e,r){return hm(this.cfg,e,r)}downloadAttachment(e){return pm(this.cfg,e)}updateStatus(e,r){return nm(this.cfg,e,r,$s(this.contextDir))}addComment(e,r,n){return om(this.cfg,e,r)}createIssue(e){return am(this.cfg,e.projectKey,e.title,e.body,e.targetStatus,$s(this.contextDir))}editIssue(e,r){return im(this.cfg,e,{...r.title!==void 0?{summary:r.title}:{},...r.body!==void 0?{description:r.body}:{}})}applyLink(e,r,n){return cm(this.cfg,e,r,n)}fetchStateFields(e){return ym(this.cfg,e)}};M();Le();import{existsSync as wT,readFileSync as bT}from"node:fs";import{randomBytes as kT}from"node:crypto";import{existsSync as Xl,readFileSync as pT,readdirSync as fT}from"node:fs";M();Le();function js(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=yT(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:mT(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:gT(hT(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 Gg(t,e,r,n=10){let o=new Set(e.map(c=>c.issue.key)),i=[],s=c=>(c.links??[]).filter(l=>l.type==="subtask").map(l=>l.targetKey);for(let c of e)i.push(...s(c.issue));let a=[];for(;i.length>0&&a.length<n;){let c=i.shift();if(o.has(c)||(o.add(c),Xl(Te(t,`tasks/${c}/task.md`))))continue;let l=null;try{l=await r(c)}catch{continue}l&&(a.push({issue:l,comments:[],attachments:[]}),i.push(...s(l)))}return a}async function Ns(t,e,r){if(r.length===0)return;let n=js(t,e,r),o=r.map(i=>i.issue.key);await Pe(t,n,`sync(${o.join(", ")}): task data`)}function mT(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(`
1080
+ `)}function hT(t,e,r){let n=new Map,o=Te(t,`tasks/${e}/comments.jsonl`);if(Xl(o))for(let i of pT(o,"utf-8").split(`
1081
+ `)){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=Kr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function gT(t){return t.map(e=>JSON.stringify(e)).join(`
1068
1082
  `)+(t.length>0?`
1069
- `:"")}function WR(t,e,r){let n=[],o=Te(t,`tasks/${e}/attachments`);if(Ul(o))for(let i of FR(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}ns();var Zo=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Bo(this.contextDir);let r=e.columns??[];return Um(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>Go(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Fo(this.contextDir,e);return r?Go(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return xg(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 Bo(this.contextDir),!Fo(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${VR(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Mr(r);s&&(i.parsedCommand=s);let c=[...xg(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
1083
+ `:"")}function yT(t,e,r){let n=[],o=Te(t,`tasks/${e}/attachments`);if(Xl(o))for(let i of fT(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}ms();var ii=class{constructor(e,r,n){this.contextDir=e;this.projectId=r;this.config=n}kind="internal";async listIssues(e){await Yo(this.contextDir);let r=e.columns??[];return nh(this.contextDir).filter(o=>r.length===0||r.includes(o.status)).map(o=>zo(this.contextDir,o,{withDescription:!0}))}async getIssue(e){let r=Vo(this.contextDir,e);return r?zo(this.contextDir,r,{withDescription:!0}):null}async listComments(e,r){return Kg(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 Yo(this.contextDir),!Vo(this.contextDir,e))throw new Error(`internal tracker: unknown issue ${e}`);let i={id:`int-${Date.now().toString(36)}-${kT(4).toString("hex")}`,author:n&&n.trim().length>0?n.trim():"dashboard",origin:"internal",body:r,createdAt:new Date().toISOString()},s=Kr(r);s&&(i.parsedCommand=s);let c=[...Kg(this.contextDir,e),i].map(l=>JSON.stringify(l)).join(`
1070
1084
  `)+`
1071
- `;return await Pe(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 Bm(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:Oi.statusColumns}]}async mutateRecord(e,r,n){let o=Fo(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=Go(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:xn(e),content:ml(i)},...xs(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Pe(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Po,status:r.targetStatus,links:[],created:n,updated:n},i=Go(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:xn(e),content:ml(o)},...xs(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function xg(t,e){let r=Te(t,`tasks/${e}/comments.jsonl`);if(!qR(r))return[];let n=[];for(let o of YR(r,"utf-8").split(`
1072
- `)){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}ns();function Bl(t){if(!t)return"youtrack";try{let e=Rg(t,"project.yaml");return Sg(e)&&Tg(Eg(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Mt(t){let e=Bl(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=Mm(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=zR(n);return i?{ok:!0,kind:e,provider:new Zo(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=Kf();return r?{ok:!0,kind:e,provider:new Jo(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function zR(t){try{let e=Rg(t,"project.yaml");if(!Sg(e))return null;let r=Tg(Eg(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Ts=new Map;async function Qo(t,e){let n=(Ts.get(t)??Promise.resolve()).catch(()=>{}).then(e);Ts.set(t,n);try{return await n}finally{Ts.get(t)===n&&Ts.delete(t)}}function ei(t,e){return ar(t.split(":",2)[0]??"",e)}function Ag(t){let{mirror:e,...r}=t;return{spec:r,host:Gr(r)}}async function _g(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;mt(`[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 Qo(`${i}/${r.name}`,async()=>{let s=await hr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir);if(r.mirror){let{syncUpstream:p}=await Promise.resolve().then(()=>(Rs(),Es)),d=await p(r,a,{info:f=>mt(`[mirror] ${f}`),warn:f=>mt(`[mirror] WARN ${f}`)});d.error&&mt(`[mirror] ${r.name}: pre-apply sync failed \u2014 ${d.error}`)}let{commit:c,pushed:l,baseMoved:u}=await Zm(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let p=e.taskId.split(":")[1]??"";p&&await kg({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{mt(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return ce({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...typeof u=="number"&&u>0?{baseMoved:u}:{},...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Qo(`${i}/${r.name}`,async()=>{let s=await hr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir);return await Qm(s,a,{branchName:e.branchName,force:e.force}),ce({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=ei(e.taskId,r),a=await s.createPullRequest(i,e);if(t.contextDir){let c=e.taskId.split(":")[1]??"",l=e.taskId.split(":",2)[0]??"?";c&&await vg({contextDir:t.contextDir,repoDir:Oe(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{mt(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return ce({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=ei(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return ce({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=ei(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),ce({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Qo(`${i}/${r.name}`,async()=>{let s=await hr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir),{commit:c,dropped:l}=await eh(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:vn(r)});return ce({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 Qo(`${i}/${r.name}`,async()=>{let s=await hr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Oe(i,r.name,t.baseDir),{mergedSha:c}=await th(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ce({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Q("no repo spec");let i=t.cloneUrlOverride??Fn(r),a=(await ss(i)).filter(u=>rh(u,e.issueKey)),c=Gr(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return ce({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Q("no repo spec");let{spec:i,host:s}=e.upstream?Ag(r):ei(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),ce({prNumber:e.prNumber,host:s.name})}case"add_pr_inline_comment":{if(!r)return Q("no repo spec");let{spec:i,host:s}=e.upstream?Ag(r):ei(e.taskId,r);if(s.addPRInlineComment)try{return await s.addPRInlineComment(i,e.prNumber,e.path,e.line,e.body),ce({prNumber:e.prNumber,inline:!0,host:s.name})}catch(a){mt(`[exec] inline comment ${e.path}:${e.line} failed (${a instanceof Error?a.message.split(`
1085
+ `;return await Pe(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 oh(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:Hi.statusColumns}]}async mutateRecord(e,r,n){let o=Vo(this.contextDir,e);if(!o)throw new Error(`internal tracker: unknown issue ${e}`);let i={...r(o),updated:new Date().toISOString()},s=zo(this.contextDir,i,{withDescription:!0});n!==void 0&&(n.trim().length>0?s.description=n:delete s.description);let a=[{path:Pn(e),content:bl(i)},...js(this.contextDir,this.projectId,[{issue:s,comments:[],attachments:[]}])];await Pe(this.contextDir,a,`tracker(${e}): update`)}renderNewIssueFiles(e,r,n){let o={key:e,title:r.title,type:Lo,status:r.targetStatus,links:[],created:n,updated:n},i=zo(this.contextDir,o);return r.body.trim().length>0&&(i.description=r.body),[{path:Pn(e),content:bl(o)},...js(this.contextDir,this.projectId,[{issue:i,comments:[],attachments:[]}])]}};function Kg(t,e){let r=Te(t,`tasks/${e}/comments.jsonl`);if(!wT(r))return[];let n=[];for(let o of bT(r,"utf-8").split(`
1086
+ `)){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}ms();function Jl(t){if(!t)return"youtrack";try{let e=qg(t,"project.yaml");return Hg(e)&&Yg(Wg(e,"utf-8")).getIn(["adapters","tracker"])==="internal"?"internal":"youtrack"}catch{return"youtrack"}}function Ft(t){let e=Jl(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=th(n);if(!o)return{ok:!1,kind:e,error:"internal tracker: tracker/config.yaml missing or has an invalid prefix"};let i=vT(n);return i?{ok:!0,kind:e,provider:new ii(n,i,o)}:{ok:!1,kind:e,error:"internal tracker: project.yaml has no id"}}let r=tm();return r?{ok:!0,kind:e,provider:new oi(r,t.contextDir??void 0)}:{ok:!1,kind:e,error:"YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env"}}function vT(t){try{let e=qg(t,"project.yaml");if(!Hg(e))return null;let r=Yg(Wg(e,"utf-8")).getIn(["id"]);return typeof r=="string"&&r.trim().length>0?r.trim():null}catch{return null}}var Ms=new Map;async function si(t,e){let n=(Ms.get(t)??Promise.resolve()).catch(()=>{}).then(e);Ms.set(t,n);try{return await n}finally{Ms.get(t)===n&&Ms.delete(t)}}function ai(t,e){return ur(t.split(":",2)[0]??"",e)}function Jg(t){let{mirror:e,...r}=t;return{spec:r,host:Vr(r)}}async function Zg(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;bt(`[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 si(`${i}/${r.name}`,async()=>{let s=await br(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ue(i,r.name,t.baseDir);if(r.mirror){let{syncUpstream:p}=await Promise.resolve().then(()=>(Ls(),Os)),d=await p(r,a,{info:f=>bt(`[mirror] ${f}`),warn:f=>bt(`[mirror] WARN ${f}`)});d.error&&bt(`[mirror] ${r.name}: pre-apply sync failed \u2014 ${d.error}`)}let{commit:c,pushed:l,baseMoved:u}=await bh(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force,push:e.push});if(t.contextDir){let p=e.taskId.split(":")[1]??"";p&&await Bg({contextDir:t.contextDir,repoDir:a,repoName:r.name,taskKey:p,commitSha:c}).catch(d=>{bt(`[model] task event for ${p} failed: ${d instanceof Error?d.message:String(d)}`)})}return ce({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,pushed:l,...typeof u=="number"&&u>0?{baseMoved:u}:{},...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"push_branch":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return si(`${i}/${r.name}`,async()=>{let s=await br(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ue(i,r.name,t.baseDir);return await kh(s,a,{branchName:e.branchName,force:e.force}),ce({branch:e.branchName,pushed:!0,...e.force?{force:!0}:{}})})}case"create_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=ai(e.taskId,r),a=await s.createPullRequest(i,e);if(t.contextDir){let c=e.taskId.split(":")[1]??"",l=e.taskId.split(":",2)[0]??"?";c&&await Fg({contextDir:t.contextDir,repoDir:Ue(l,r.name,t.baseDir),branchName:e.branchName,baseBranch:e.baseBranch,fallbackTaskKey:c,prUrl:a.url}).catch(u=>{bt(`[model] pr link for ${c} failed: ${u instanceof Error?u.message:String(u)}`)})}return ce({url:a.url,number:a.number,host:s.name})}case"merge_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=ai(e.taskId,r),a=await s.mergePR(i,e.prNumber,e.mergeMethod,e.deleteBranch);return ce({prNumber:e.prNumber,host:s.name,...a.mergedSha?{mergedSha:a.mergedSha}:{}})}case"close_pr":{if(!r)return Q("no repo spec");let{spec:i,host:s}=ai(e.taskId,r);return await s.closePR(i,e.prNumber,e.comment),ce({prNumber:e.prNumber,host:s.name})}case"rewrite_cluster_branch":{if(!r)return Q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return si(`${i}/${r.name}`,async()=>{let s=await br(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ue(i,r.name,t.baseDir),{commit:c,dropped:l}=await vh(s,a,{branchName:e.branchName,dropTaskKeys:e.dropTaskKeys,defaultBranch:Tn(r)});return ce({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 si(`${i}/${r.name}`,async()=>{let s=await br(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ue(i,r.name,t.baseDir),{mergedSha:c}=await $h(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ce({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"resolve_review_branch":{if(!r)return Q("no repo spec");let i=t.cloneUrlOverride??qn(r),a=(await ws(i)).filter(u=>xh(u,e.issueKey)),c=Vr(r),l=null;if(c.findOpenPrByBranch)for(let u of a){let p=await c.findOpenPrByBranch(r,u).catch(()=>null);if(p){l={number:p.number,url:p.url};break}}return ce({branches:a,...l?{pr:l}:{}})}case"add_pr_comment":{if(!r)return Q("no repo spec");let{spec:i,host:s}=e.upstream?Jg(r):ai(e.taskId,r);return await s.addPRComment(i,e.prNumber,e.body),ce({prNumber:e.prNumber,host:s.name})}case"add_pr_inline_comment":{if(!r)return Q("no repo spec");let{spec:i,host:s}=e.upstream?Jg(r):ai(e.taskId,r);if(s.addPRInlineComment)try{return await s.addPRInlineComment(i,e.prNumber,e.path,e.line,e.body),ce({prNumber:e.prNumber,inline:!0,host:s.name})}catch(a){bt(`[exec] inline comment ${e.path}:${e.line} failed (${a instanceof Error?a.message.split(`
1073
1087
  `)[0]:String(a)}) \u2014 posting as a plain comment`)}return await s.addPRComment(i,e.prNumber,`\u{1F4CD} \`${e.path}:${e.line}\`
1074
1088
 
1075
- ${e.body}`),ce({prNumber:e.prNumber,inline:!1,host:s.name})}case"tracker_status":{let i=Mt({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ce({issueId:t.trackerIssueId,newStatus:e.newStatus})):Q("no tracker_issue_id provided"):Q(i.error)}case"tracker_comment":{let i=Mt({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 ce({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Mt({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 ce({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Mt({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 ce({applied:s})}case"set_project_setting":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await bh(t.contextDir,e.edits);return ce({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return Q("no context repo clone on this CLI");if(!gc(e.role))return Q(`unknown prompt operation: ${e.role}`);let i=yc(e.role);return await Pe(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),ce({path:i,reset:e.content===null})}case"tracker_edit":{let i=Mt({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 Ss(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ce({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await Ih(t.contextDir,e);return ce({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await Rh(t.contextDir,e);return ce({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ce({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 ce({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}=zi(t.contextDir),c=s.find(f=>f.id===e.actionId);if(!c){let f=a.find(m=>m.file===`actions/${e.actionId}.yml`);return Q(f?`action "${e.actionId}" failed to parse: ${f.error}`:`unknown action "${e.actionId}"`)}let l=oc(c,e.input);if(!l.ok)return Q(l.error);let u=wm(t.contextDir),p=X(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),Qo(`${e.projectId}/${r.name}`,async()=>{await hr(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let f=Oe(e.projectId,r.name,t.baseDir),m=await hh({cwd:f,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:y=>i(e.runId,y)});return ce({runId:e.runId,status:m.status,exitCode:m.exitCode,...m.failedStep?{failedStep:m.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=wh(t.contextDir,e.path);return ce({path:e.path,...i})}case"search_model":{if(!t.contextDir)return Q("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(Xo(),zo)),s=await i(t.contextDir,e.q,e.limit);return ce({hits:s})}case"model_drift":return Q("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return Q("model_bootstrap 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 ce(t){return{status:"done",result:t}}function Q(t){return{status:"failed",error:t}}ht();Kl();Le();ue();import{existsSync as qg,readFileSync as Yg}from"node:fs";import{join as Vg}from"node:path";async function zg(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=ze(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Cs(e.farmId,e.farmPublicKey);let s=X(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await se(t.hubUrl,t.cliToken,t.projectId),c;if(r){let d=Vg(r,"project.yaml"),f=Vg(r,"regimen.yaml");qg(d)&&qg(f)?c={projectYaml:Yg(d,"utf-8"),regimenYaml:Yg(f,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Zt(e.farmPublicKey,JSON.stringify(l));Is(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let p=await As(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))}}M();ht();Ye();ht();import{homedir as uT}from"node:os";import{existsSync as dT,mkdirSync as pT,readFileSync as fT,writeFileSync as mT}from"node:fs";import{dirname as hT,join as gT}from"node:path";function ql(){return ee("RUNNER_PINS")??gT(uT(),".codepipe","runner-pins.json")}function Xg(){let t=ql();if(!dT(t))return{};try{return JSON.parse(fT(t,"utf-8"))}catch{return{}}}function yT(t){let e=ql();pT(hT(e),{recursive:!0}),mT(e,JSON.stringify(t,null,2)+`
1076
- `,{mode:384})}function wT(t){return Xg()[t]}function Yl(t,e){let r=Xg();r[t]=e,yT(r)}function Jg(t,e){let r=ze(e),n=wT(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 ${ql()}.`);return r}Le();ue();var Qg=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Zg(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Qg(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var bT={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Qg(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)=>Zg(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Zg(t,e,r,"remove-token")},ey={api:bT,fetchProject:se,provisionOnRunner:Og,teardownOnRunner:Lg};async function ty(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(ze(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Jg(e.runnerId,e.runnerPublicKey);let i=X(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 ry(t,e,r,n=ey){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 ty(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:[xc(e.runnerId)]},c=Zt(e.runnerPublicKey,JSON.stringify(a));Yl(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 ny(t,e,r,n=ey){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 ty(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=Zt(e.runnerPublicKey,JSON.stringify(c));Yl(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))}}Le();M();import{existsSync as kT}from"node:fs";import{join as oy}from"node:path";import{simpleGit as sy}from"simple-git";async function Vl(t,e,r,n,o){for(let i of r.repos){let s=e.find(u=>u.name===i.repoName);if(!s)continue;let a=`${r.taskKey}:${s.name}:${i.branchName}`;if(!rr(i.branchName)){n.has(a)||(n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: refusing suspicious branch name`));continue}let c=oy(t,s.mountAs);if(!kT(oy(c,".git")))continue;let l=sy(c);try{let u=await xT(l,i.branchName);await l.fetch(await vT(l,s),`refs/heads/${i.branchName}`);let p=(await l.revparse(["FETCH_HEAD"])).trim();if(u===p)continue;if(await $T(l,c,i.branchName)){n.has(a)||(n.add(a),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} is checked out here \u2014 fetched ${p.slice(0,10)}; merge or pull it in that checkout yourself`));continue}await l.raw(["branch","-f",i.branchName,p]),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} ${p.slice(0,10)} (checkout untouched)`)}catch(u){if(n.has(a))continue;n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: ${i.branchName} unavailable \u2014 `+(u instanceof Error?u.message.split(`
1077
- `)[0]:String(u)))}}}async function vT(t,e){if(e.mirror)return iy(e.mirror);try{if((await t.getRemotes(!0)).find(n=>n.name==="origin")?.refs?.fetch)return"origin"}catch{}return e.host&&e.owner&&e.repoName?iy({host:e.host,owner:e.owner,repoName:e.repoName}):"origin"}function iy(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 $T(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
1078
- `).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await sy(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function xT(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}var Ns=class{constructor(e,r,n,o){this.intervalMs=e;this.fetchDeliverables=r;this.workspace=n;this.log=o}timer=null;running=!1;caughtUp=!1;warned=new Set;start(){if(this.timer)return;this.log.info(`[pull] local delivery started (interval=${this.intervalMs}ms)`);let e=()=>void this.runOnce();e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[pull] local delivery stopped"))}poke(){this.runOnce()}async runOnce(){if(!this.running){this.running=!0;try{let e=await this.fetchDeliverables(),r=this.caughtUp?e.filter(n=>n.phase==="TRACKING"||n.phase==="AWAITING_CLUSTER"):e;for(let n of r)await Vl(this.workspace.root,this.workspace.repos,n,this.warned,this.log);this.caughtUp=!0}catch(e){this.log.warn(`[pull] pass failed: ${e instanceof Error?e.message:String(e)}`)}finally{this.running=!1}}}};M();ht();ue();var ay=16*1024;function ST(t){return rt.test(t)?Wt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${rt}`}function cy(t,e,r,n){let o=ST(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Kn(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>ay)return{ok:!1,detail:`secret value too large (max ${ay} chars)`};try{return yf(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function ly(t,e){try{return wf(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)}}}jn();ue();zt();var Os=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[],o=e.split(":",2)[0]??"";for(let a of r.prs){let{spec:c,host:l}=ar(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,repoName:a.repoSpec.name,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof Fr){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.repoName??""}#${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=ar(o,r.prs[a].repoSpec);if(u.getCiFailureLog)try{let p=await u.getCiFailureLog(l,c.number);p&&(c.ciFailureLog=p)}catch(p){this.log.warn(`[track] task=${e} pr=${c.url} ci-log fetch failed: ${p instanceof Error?p.message:String(p)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,i);let s=ET(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function ET(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}M();Gn();var Ls=class{constructor(e,r,n,o=i=>ss(Fn(i))){this.intervalMs=e;this.send=r;this.log=n;this.listBranches=o}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r,this.lastSig.clear()}start(){if(this.timer)return;this.log.info(`[branches] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branches] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[branches] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let e of this.repos)await this.processRepo(e)}finally{this.running=!1}}}async processRepo(e){let r=e.gitFlow;if(!r||r.flow==="simple")return;let n;try{n=await this.listBranches(e)}catch(s){this.log.warn(`[branches] repo=${e.name} ls-remote failed: ${s instanceof Error?s.message:String(s)}`);return}let o=n.filter(s=>Cc(s,r)).sort(),i=o.join("|");this.lastSig.get(e.name)!==i&&(this.send({type:"branches_observation",projectId:this.projectId,repoName:e.name,branches:o}),this.lastSig.set(e.name,i),this.log.info(`[branches] repo=${e.name} reported ${o.length} base candidate(s)`))}};M();zt();var Ms=class{constructor(e,r,n,o=RT,i=TT){this.intervalMs=e;this.send=r;this.log=n;this.read=o;this.readFailureLog=i}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r;let n=new Set(r.map(o=>o.name));for(let o of[...this.lastSig.keys()])n.has(o)||this.lastSig.delete(o)}start(){if(this.timer)return;this.log.info(`[branch-ci] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branch-ci] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async tick(){if(!(this.running||!this.projectId)){this.running=!0;try{for(let e of this.repos){let r=vn(e);try{let n=await this.read(this.projectId,e,r);if(!n||n.ci==="none")continue;let o=`${r}:${n.ci}:${n.headSha}`;if(this.lastSig.get(e.name)===o)continue;let i;n.ci==="failed"&&(i=await this.readFailureLog(this.projectId,e,n.headSha).catch(()=>{})),this.send({type:"branch_ci_observed",projectId:this.projectId,repoName:e.name,branch:r,ci:n.ci,headSha:n.headSha,...i?{ciFailureLog:i}:{}}),this.lastSig.set(e.name,o),this.log.info(`[branch-ci] ${e.name}#${r}: ${n.ci} @ ${n.headSha.slice(0,10)}`)}catch(n){this.log.warn(`[branch-ci] ${e.name}#${r}: read failed \u2014 ${n instanceof Error?n.message:String(n)}`)}}}finally{this.running=!1}}}};async function RT(t,e,r){let{spec:n,host:o}=ar(t,e);if(!o.getBranchCi)return null;let i=await o.getBranchCi(n,r);return i?{ci:i.ci,headSha:i.headSha}:null}async function TT(t,e,r){let{spec:n,host:o}=ar(t,e);if(o.getCiFailureLogForSha)return await o.getCiFailureLogForSha(n,r)}M();var Ds=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??(()=>Mt({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let x=e.stageField?{stageField:e.stageField}:{},h=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},R=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(R){let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[_,N]=await Promise.all([v.length>0?r.listIssues({projectKey:e.projectKey,columns:v,...x,...h}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...x})]),G=new Map;for(let W of[..._,...N])G.set(W.id,W);o=[...G.values()]}else{let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:v,...x,...h})}}catch(x){let h=x instanceof Error?x.message:String(x);h.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${h}`):this.log.warn(`[yt-sync] listIssues failed: ${h}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let x of o){if(s.add(x.id),a.has(x.status))continue;let h=await py(r,x.id,e.sinceMs,this.log);h&&i.set(x.id,h)}let c=[];for(let x of e.offBoardIssueIds){if(s.has(x))continue;let h=await py(r,x,e.sinceMs,this.log);h&&h.length>0&&i.set(x,h);let T=await dy(r,x,e.stageField,this.log);if(T)c.push(T);else if(h&&h.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}let l=o.filter(x=>!a.has(x.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map(x=>({issue:x,comments:i.get(x.id)??[],attachments:u.get(x.id)??[]}));d.push(...await $g(this.options.contextDir,d,x=>dy(r,x,e.stageField,this.log)));try{await Ss(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let x of p)this.shippedAttachments.add(x)}catch(x){let h=x instanceof Error?x.message:String(x);this.abandonTick(`context task sync failed: ${h}`);return}let f=this.options.isSelfComment??(()=>!1),m=[],y=[];for(let[x,h]of i){let T=h.filter(v=>!f(v.id));if(T.length===0)continue;m.push({issueId:x,comments:T.map(IT)});let R=T.flatMap(v=>{let _=Mr(v.body);return _?[{commentId:v.id,author:v.author,name:_.name,args:_.args,createdAt:v.createdAt}]:[]});R.length>0&&y.push({issueId:x,commands:R})}let b={type:"youtrack_observation",projectId:e.projectId,issues:o.map(uy),commentsBatch:m,...y.length>0?{commandsBatch:y}:{},...c.length>0?{offBoardIssues:c.map(uy)}:{},observedAtMs:n};this.send(b);let w=m.reduce((x,h)=>x+h.comments.length,0),k=y.reduce((x,h)=>x+h.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${k} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(m){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${m instanceof Error?m.message:String(m)}`);continue}let f=CT(u.name);l.has(f)&&(f=`${u.id}-${f}`),l.add(f),c.push({name:f,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function uy(t){let{description:e,...r}=t;return r}function IT(t){let{body:e,...r}=t;return r}function CT(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 dy(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 py(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function qT(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(Rs(),Es)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:Vr(t.root,i.mountAs);try{o.push({repo:i.name,behind:await n(i,s)})}catch(a){e.warn(`[mirror] lag for ${i.name} unknown: ${a instanceof Error?a.message:String(a)}`),o.push({repo:i.name,behind:null})}}return o}var ou="npm i -g @code-partner/codepipe@latest";function Hs(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${et} (protocol ${$t})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&vm(o.contextDir,r);let i=()=>{if(o?.contextDir)try{Mn(o.contextDir,o.root,r)}catch(h){r.warn(`[skills] materialize failed (non-fatal): ${h instanceof Error?h.message:String(h)}`)}};i();let s=su("CLI_TRACKING_POLL_INTERVAL_SEC"),a=parseInt(process.env.CLI_BRANCH_CI_POLL_INTERVAL_SEC??"300",10),c=Number.isFinite(a)&&a>0?a*1e3:3e5,l=su("CLI_YOUTRACK_POLL_INTERVAL_SEC"),u=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),p=!1,d=!1,f=!1,m=!1,y=new Set,b=!1,w=new Set,k=x();function x(){let h=Ps(t.hubUrl,t.cliToken),T=null,R=new Os(s,U=>{h.readyState===h.OPEN&&h.send(JSON.stringify(U))},r),v=new Ls(s,U=>{h.readyState===h.OPEN&&h.send(JSON.stringify(U))},r),_=new Ms(c,U=>{h.readyState===h.OPEN&&h.send(JSON.stringify(U))},r),N=o&&o.repos.length>0?new Ns(su("CLI_LOCAL_PULL_INTERVAL_SEC"),()=>js(t.hubUrl,t.cliToken,t.projectId),{root:o.root,repos:o.repos},r):null,G=new Ds(l,U=>{h.readyState===h.OPEN&&h.send(JSON.stringify(U))},r,{contextDir:o?.contextDir??null,isSelfComment:U=>w.has(U)}),W=null,C=async()=>{try{let U={trackerProvider:Bl(o?.contextDir??null)};try{let S=await se(t.hubUrl,t.cliToken,t.projectId);U={...U,repos:S.repos,contextRepo:S.contextRepo},v.setRepos(t.projectId,S.repos),_.setRepos(t.projectId,S.repos)}catch(S){r.warn(`[readiness] could not fetch project summary for push checks: ${S instanceof Error?S.message:String(S)}`)}let K=await am(t.projectId,U),D=o?await qT(o,r):[];if(i(),h.readyState!==h.OPEN)return;let $={type:"cli_readiness",projectId:t.projectId,ready:K.ready,checks:K.checks,creds:K.creds,secretNames:bf(t.projectId),...o?{mirrors:D}:{},checkedAt:K.checkedAt};if(h.send(JSON.stringify($)),K.ready)r.info("[readiness] ready");else{let S=K.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${S.join(", ")}`)}let P=fm(K.creds,f);if(P==="open"){f=!0;let S=tl(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${S}`),ur(S)}else P==="rearm"&&(f=!1)}catch(U){r.warn(`[readiness] check failed: ${U instanceof Error?U.message:String(U)}`)}},g=()=>{C(),W=setInterval(()=>void C(),u),typeof W.unref=="function"&&W.unref()},B=()=>{W&&(clearInterval(W),W=null)},L=150,q=new Map,te=U=>{let K=q.get(U);if(!K||(K.timer&&clearTimeout(K.timer),q.delete(U),K.events.length===0||h.readyState!==h.OPEN))return;let D={type:"run_activity",projectId:t.projectId,runId:U,events:K.events};h.send(JSON.stringify(D))},de=(U,K)=>{let D=q.get(U);if(D||(D={events:[],timer:null},q.set(U,D)),D.events.push(K),K.kind==="result"){te(U);return}D.timer||(D.timer=setTimeout(()=>te(U),L),D.timer.unref?.())},wt=o?.contextDir?new Xi(o.contextDir,t.projectId,U=>{h.readyState===h.OPEN&&h.send(JSON.stringify(U))},r):null,Ft=async()=>{let U=o?.contextDir;if(!U)throw new Error("no context repo clone on this CLI");let K;try{K=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let D=await Ym(U,t.projectId,K,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(D)),D},we=null,We=async()=>{let U=o?.contextDir;if(U)try{let{readContextIndexHub:K,collectSearchRows:D}=await Promise.resolve().then(()=>(Xo(),zo));if(K(U)!=="metadata")return;let $=D(U);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:$})),r.info(`[model] tier-2 index snapshot pushed (${$.length} rows)`))}catch(K){r.warn(`[model] tier-2 index push failed (non-fatal): ${K instanceof Error?K.message:String(K)}`)}},Be=()=>{we&&clearTimeout(we),we=setTimeout(()=>void We(),5e3)},bt=async()=>{if(!o?.contextDir)throw new Error("no Context Repo clone on this CLI");if(b)throw new Error("model bootstrap is already running");b=!0;try{let U=await se(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:K}=await Promise.resolve().then(()=>(ni(),Ks)),D=await K(t.projectId,{root:o.root,contextDir:o.contextDir},U.repos,$=>r.info(`[model] ${$}`));return r.info(`[model] bootstrap done: ${D.repos} repos, ${D.events} task events`),Be(),D}finally{b=!1}},Ie=null,st=async U=>{if(o?.contextDir)try{let K=await Promise.resolve().then(()=>(ni(),Ks)),D={root:o.root,contextDir:o.contextDir,repos:o.repos};if(K.shouldAutoBootstrapModel(o.contextDir)){await K.syncWorkspaceMirrors(D,P=>r.info(P));try{await bt()}catch(P){r.warn(`[model] auto-bootstrap failed (non-fatal): ${P instanceof Error?P.message:String(P)}`)}return}(await K.rebuildWorkspaceModelIfStale(D,{fetch:U,onLog:P=>r.info(P)})).rebuilt.length>0&&Be()}catch(K){r.warn(`[model] release-path rebuild failed (non-fatal): ${K instanceof Error?K.message:String(K)}`)}},kt=U=>{Ie&&clearTimeout(Ie),Ie=setTimeout(()=>void st(U),6e4)},er=setInterval(()=>void st(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let U=Tf(t.projectId),K=ee("ORIGIN")==="farm"?"farm":"local",D=ee("FARM_ID"),$=t.accountEmail??U.email,P;try{let I=dh(t.projectId);I&&(P=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let S={type:"register",projectId:t.projectId,platformVersion:et,protocolVersion:$t,accountId:U.accountId,accountSourceKey:U.sourceKey,accountLabel:U.label,origin:K,inFlightActionIds:[...y],...$?{accountEmail:$}:{},...K==="farm"&&D?{farmId:D}:{},...P?{sealPublicKey:P}:{}};h.send(JSON.stringify(S))}),h.on("message",async U=>{let K=U.toString("utf-8");if(K==="pong"||K==="ping")return;let D;try{D=JSON.parse(K)}catch{return}if(!D||typeof D!="object")return;let $=D.type;if($==="registered"){let S=D;if(S.ok){if(r.info(`[ws] registered for project ${S.projectId}`),n({kind:"registered",projectId:S.projectId??t.projectId}),R.start(),v.start(),_.start(),N?.start(),wt?.start(),g(),iu(t,o,r),o?.contextDir){try{let I=rs(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),d||(d=!0,Ft().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}We(),kt(!0)}}else r.warn(`[ws] register rejected: ${S.reason??"unknown"}`),n({kind:"register_rejected",reason:S.reason??"unknown"}),p=!0,h.close();return}if($==="hello"){let S=D;T=bo(S.protocolVersion);let I=T?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${I}`),T||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${et}, protocol ${$t}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${ou}`),n({kind:"incompatible",hubVersion:typeof S.platformVersion=="string"?S.platformVersion:null,hubProtocol:typeof S.protocolVersion=="number"?S.protocolVersion:null,updateCommand:ou}));return}if($==="tracking_targets"){R.setTargets(D.targets),N?.poke();return}if($==="youtrack_sync_request"){G.setRequest(D);return}if($==="youtrack_force_sync"){G.forceSync();return}if($==="sync_local"){await zT(D,o,h,r);return}if($==="provision_repo"){let S=D;r.info(`[repo] provision_repo: ${S.repo.name} (${S.repo.host}:${S.repo.owner}/${S.repo.repoName})`),await YT(t,o,S.repo,r),await iu(t,o,r);return}if($==="remove_repo"){let S=D;r.info(`[repo] remove_repo: ${S.repoName}${S.purge?" (purge)":""}`),await iu(t,o,r),S.purge&&VT(t,o,S.repoName,r);return}if($==="context_write"){await XT(D,o,h,r),i();return}if($==="adr_promote"){await JT(D,o,h,r),i();return}if($==="cred_update"){let S=D,I=X(t.projectId),F=I?.sealKey?await ph(t.projectId,S.kind,S.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},V={type:"cred_update_result",updateId:S.updateId,projectId:t.projectId,ok:F.ok,...F.detail?{detail:F.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(V)),F.ok?(r.info(`[cred] ${S.kind} replaced${F.detail?` \u2014 ${F.detail}`:""}`),C()):r.warn(`[cred] ${S.kind} replacement rejected: ${F.detail??"unknown"}`);return}if($==="readiness_check"){r.info("[readiness] on-demand check requested"),C();return}if($==="agent_auth_required"){let S=tl(t.hubUrl,t.projectId);r.warn(`[agent-auth] the agent has no working Claude login \u2014 the project is paused.
1089
+ ${e.body}`),ce({prNumber:e.prNumber,inline:!1,host:s.name})}case"tracker_status":{let i=Ft({contextDir:t.contextDir});return i.ok?t.trackerIssueId?(await i.provider.updateStatus(t.trackerIssueId,e.newStatus),ce({issueId:t.trackerIssueId,newStatus:e.newStatus})):Q("no tracker_issue_id provided"):Q(i.error)}case"tracker_comment":{let i=Ft({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 ce({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ft({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 ce({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ft({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 ce({applied:s})}case"set_project_setting":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await Kh(t.contextDir,e.edits);return t.requestConfigReport?.(),ce({files:i.files})}case"set_prompt_override":{if(!t.contextDir)return Q("no context repo clone on this CLI");if(!Ac(e.role))return Q(`unknown prompt operation: ${e.role}`);let i=_c(e.role);return await Pe(t.contextDir,[e.content===null?{path:i,content:"",deleted:!0}:{path:i,content:e.content}],e.commitMessage),t.requestConfigReport?.(),ce({path:i,reset:e.content===null})}case"tracker_edit":{let i=Ft({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 Ns(t.contextDir,e.projectId,[{issue:s,comments:[],attachments:[]}]),ce({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await Vh(t.contextDir,e);return t.requestConfigReport?.(),ce({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=await Wh(t.contextDir,e);return t.requestConfigReport?.(),ce({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ce({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 ce({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}=os(t.contextDir),c=s.find(f=>f.id===e.actionId);if(!c){let f=a.find(m=>m.file===`actions/${e.actionId}.yml`);return Q(f?`action "${e.actionId}" failed to parse: ${f.error}`:`unknown action "${e.actionId}"`)}let l=pc(c,e.input);if(!l.ok)return Q(l.error);let u=Pm(t.contextDir),p=X(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),si(`${e.projectId}/${r.name}`,async()=>{await br(e.projectId,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride});let f=Ue(e.projectId,r.name,t.baseDir),m=await Lh({cwd:f,def:c,input:l.values,variables:u,secrets:p?.secrets??{},credEnv:d,onEvent:y=>i(e.runId,y)});return ce({runId:e.runId,status:m.status,exitCode:m.exitCode,...m.failedStep?{failedStep:m.failedStep}:{}})})}case"read_context_file":{if(!t.contextDir)return Q("no context repo clone on this CLI");let i=Uh(t.contextDir,e.path);return ce({path:e.path,...i})}case"search_model":{if(!t.contextDir)return Q("no context repo clone on this CLI");let{searchModelIndex:i}=await Promise.resolve().then(()=>(ni(),ri)),s=await i(t.contextDir,e.q,e.limit);return ce({hits:s})}case"model_drift":return Q("model_drift requires a local workspace (handled by the daemon)");case"model_bootstrap":return Q("model_bootstrap 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 ce(t){return{status:"done",result:t}}function Q(t){return{status:"failed",error:t}}kt();eu();Be();de();import{existsSync as py,readFileSync as fy}from"node:fs";import{join as my}from"node:path";async function hy(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=Qe(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Us(e.farmId,e.farmPublicKey);let s=X(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await se(t.hubUrl,t.cliToken,t.projectId),c,l;if(r){let f=my(r,"local.yaml");py(f)?c={localYaml:fy(f,"utf-8")}:n.warn("[farm-move] local.yaml not found \u2014 the farm will seed defaults");let m=my(r,"project.yaml");py(m)&&(l={projectYaml:fy(m,"utf-8"),regimenYaml:c?.localYaml??""})}let u={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?{localConfig:c}:{},...l?{projectConfig:l}:{}},p=tr(e.farmPublicKey,JSON.stringify(u));Ds(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let d=await Fs(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:p});return d.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...d.daemonStatus?{daemonStatus:d.daemonStatus}:{}}:o(d.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}M();kt();Je();kt();import{homedir as LT}from"node:os";import{existsSync as MT,mkdirSync as DT,readFileSync as UT,writeFileSync as BT}from"node:fs";import{dirname as FT,join as GT}from"node:path";function nu(){return ee("RUNNER_PINS")??GT(LT(),".codepipe","runner-pins.json")}function gy(){let t=nu();if(!MT(t))return{};try{return JSON.parse(UT(t,"utf-8"))}catch{return{}}}function KT(t){let e=nu();DT(FT(e),{recursive:!0}),BT(e,JSON.stringify(t,null,2)+`
1090
+ `,{mode:384})}function HT(t){return gy()[t]}function ou(t,e){let r=gy();r[t]=e,KT(r)}function yy(t,e){let r=Qe(e),n=HT(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 ${nu()}.`);return r}Be();de();var by=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function wy(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:by(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var WT={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:by(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)=>wy(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>wy(t,e,r,"remove-token")},ky={api:WT,fetchProject:se,provisionOnRunner:ty,teardownOnRunner:ry};async function vy(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(Qe(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");yy(e.runnerId,e.runnerPublicKey);let i=X(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 $y(t,e,r,n=ky){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 vy(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:[Dc(e.runnerId)]},c=tr(e.runnerPublicKey,JSON.stringify(a));ou(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 xy(t,e,r,n=ky){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 vy(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=tr(e.runnerPublicKey,JSON.stringify(c));ou(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))}}Be();M();import{existsSync as qT}from"node:fs";import{join as Sy}from"node:path";import{simpleGit as Ry}from"simple-git";async function iu(t,e,r,n,o){for(let i of r.repos){let s=e.find(u=>u.name===i.repoName);if(!s)continue;let a=`${r.taskKey}:${s.name}:${i.branchName}`;if(!or(i.branchName)){n.has(a)||(n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: refusing suspicious branch name`));continue}let c=Sy(t,s.mountAs);if(!qT(Sy(c,".git")))continue;let l=Ry(c);try{let u=await zT(l,i.branchName);await l.fetch(await YT(l,s),`refs/heads/${i.branchName}`);let p=(await l.revparse(["FETCH_HEAD"])).trim();if(u===p)continue;if(await VT(l,c,i.branchName)){n.has(a)||(n.add(a),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} is checked out here \u2014 fetched ${p.slice(0,10)}; merge or pull it in that checkout yourself`));continue}await l.raw(["branch","-f",i.branchName,p]),o.info(`[pull] ${r.taskKey} \u2192 ${s.mountAs}: ${i.branchName} ${p.slice(0,10)} (checkout untouched)`)}catch(u){if(n.has(a))continue;n.add(a),o.warn(`[pull] ${r.taskKey} ${s.mountAs}: ${i.branchName} unavailable \u2014 `+(u instanceof Error?u.message.split(`
1091
+ `)[0]:String(u)))}}}async function YT(t,e){if(e.mirror)return Ey(e.mirror);try{if((await t.getRemotes(!0)).find(n=>n.name==="origin")?.refs?.fetch)return"origin"}catch{}return e.host&&e.owner&&e.repoName?Ey({host:e.host,owner:e.owner,repoName:e.repoName}):"origin"}function Ey(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 VT(t,e,r){try{return(await t.raw(["worktree","list","--porcelain"])).split(`
1092
+ `).some(o=>o.trim()===`branch refs/heads/${r}`)}catch{try{return(await Ry(e).revparse(["--abbrev-ref","HEAD"])).trim()===r}catch{return!1}}}async function zT(t,e){try{return(await t.revparse([e])).trim()}catch{return null}}var Hs=class{constructor(e,r,n,o){this.intervalMs=e;this.fetchDeliverables=r;this.workspace=n;this.log=o}timer=null;running=!1;caughtUp=!1;warned=new Set;start(){if(this.timer)return;this.log.info(`[pull] local delivery started (interval=${this.intervalMs}ms)`);let e=()=>void this.runOnce();e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[pull] local delivery stopped"))}poke(){this.runOnce()}async runOnce(){if(!this.running){this.running=!0;try{let e=await this.fetchDeliverables(),r=this.caughtUp?e.filter(n=>n.phase==="TRACKING"||n.phase==="AWAITING_CLUSTER"):e;for(let n of r)await iu(this.workspace.root,this.workspace.repos,n,this.warned,this.log);this.caughtUp=!0}catch(e){this.log.warn(`[pull] pass failed: ${e instanceof Error?e.message:String(e)}`)}finally{this.running=!1}}}};M();kt();de();var Ty=16*1024;function XT(t){return st.test(t)?zt(t)?`secret name "${t}" is reserved`:null:`secret name must match ${st}`}function Iy(t,e,r,n){let o=XT(e);if(o)return{ok:!1,detail:o};let i;try{let s=JSON.parse(Vn(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>Ty)return{ok:!1,detail:`secret value too large (max ${Ty} chars)`};try{return Cf(t,e,i),{ok:!0}}catch(s){return{ok:!1,detail:s instanceof Error?s.message:String(s)}}}function Cy(t,e){try{return Pf(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)}}}Bn();de();Qt();var Ws=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[],o=e.split(":",2)[0]??"";for(let a of r.prs){let{spec:c,host:l}=ur(o,a.repoSpec);try{let u=await l.getPullRequest(c,a.number);n.push({number:a.number,repoName:a.repoSpec.name,url:a.url,state:u.state,merged:u.merged,ci:u.ci,mergeable:u.mergeable})}catch(u){if(u instanceof Yr){this.log.warn(`[track] task=${e} pr=${a.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${a.url} fetch failed: ${u instanceof Error?u.message:String(u)}`);return}}let i=n.map(a=>`${a.repoName??""}#${a.number}:${a.state}:${a.merged?1:0}:${a.ci}:${a.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let a=0;a<n.length;a++){let c=n[a];if(c.ci!=="failed")continue;let{spec:l,host:u}=ur(o,r.prs[a].repoSpec);if(u.getCiFailureLog)try{let p=await u.getCiFailureLog(l,c.number);p&&(c.ciFailureLog=p)}catch(p){this.log.warn(`[track] task=${e} pr=${c.url} ci-log fetch failed: ${p instanceof Error?p.message:String(p)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,i);let s=JT(n);this.log.info(`[track] task=${e} snapshot signalled${s?` \u2192 ${s}`:""} (${n.length} PR(s))`)}};function JT(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}M();Yn();var qs=class{constructor(e,r,n,o=i=>ws(qn(i))){this.intervalMs=e;this.send=r;this.log=n;this.listBranches=o}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r,this.lastSig.clear()}start(){if(this.timer)return;this.log.info(`[branches] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branches] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[branches] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let e of this.repos)await this.processRepo(e)}finally{this.running=!1}}}async processRepo(e){let r=e.gitFlow;if(!r||r.flow==="simple")return;let n;try{n=await this.listBranches(e)}catch(s){this.log.warn(`[branches] repo=${e.name} ls-remote failed: ${s instanceof Error?s.message:String(s)}`);return}let o=n.filter(s=>bc(s,r)).sort(),i=o.join("|");this.lastSig.get(e.name)!==i&&(this.send({type:"branches_observation",projectId:this.projectId,repoName:e.name,branches:o}),this.lastSig.set(e.name,i),this.log.info(`[branches] repo=${e.name} reported ${o.length} base candidate(s)`))}};M();Qt();var Ys=class{constructor(e,r,n,o=ZT,i=QT){this.intervalMs=e;this.send=r;this.log=n;this.read=o;this.readFailureLog=i}projectId="";repos=[];lastSig=new Map;timer=null;running=!1;setRepos(e,r){this.projectId=e,this.repos=r;let n=new Set(r.map(o=>o.name));for(let o of[...this.lastSig.keys()])n.has(o)||this.lastSig.delete(o)}start(){if(this.timer)return;this.log.info(`[branch-ci] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[branch-ci] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs),typeof this.timer.unref=="function"&&this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}async tick(){if(!(this.running||!this.projectId)){this.running=!0;try{for(let e of this.repos){let r=Tn(e);try{let n=await this.read(this.projectId,e,r);if(!n||n.ci==="none")continue;let o=`${r}:${n.ci}:${n.headSha}`;if(this.lastSig.get(e.name)===o)continue;let i;n.ci==="failed"&&(i=await this.readFailureLog(this.projectId,e,n.headSha).catch(()=>{})),this.send({type:"branch_ci_observed",projectId:this.projectId,repoName:e.name,branch:r,ci:n.ci,headSha:n.headSha,...i?{ciFailureLog:i}:{}}),this.lastSig.set(e.name,o),this.log.info(`[branch-ci] ${e.name}#${r}: ${n.ci} @ ${n.headSha.slice(0,10)}`)}catch(n){this.log.warn(`[branch-ci] ${e.name}#${r}: read failed \u2014 ${n instanceof Error?n.message:String(n)}`)}}}finally{this.running=!1}}}};async function ZT(t,e,r){let{spec:n,host:o}=ur(t,e);if(!o.getBranchCi)return null;let i=await o.getBranchCi(n,r);return i?{ci:i.ci,headSha:i.headSha}:null}async function QT(t,e,r){let{spec:n,host:o}=ur(t,e);if(o.getCiFailureLogForSha)return await o.getCiFailureLogForSha(n,r)}M();var Vs=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let r=(this.options.resolveProvider??(()=>Ft({contextDir:this.options.contextDir})))();if(!r.ok){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn(`[yt-sync] tracker provider unavailable (${r.error}) \u2014 poller idle.`));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,r.provider)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let x=e.stageField?{stageField:e.stageField}:{},h=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{},R=(e.backlogScope??"personal")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn;if(r.kind==="internal")o=await r.listIssues({projectKey:e.projectKey});else if(R){let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[]])],[P,N]=await Promise.all([v.length>0?r.listIssues({projectKey:e.projectKey,columns:v,...x,...h}):Promise.resolve([]),r.listIssues({projectKey:e.projectKey,columns:[e.backlogColumn],...x})]),G=new Map;for(let W of[...P,...N])G.set(W.id,W);o=[...G.values()]}else{let v=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.reviewColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await r.listIssues({projectKey:e.projectKey,columns:v,...x,...h})}}catch(x){let h=x instanceof Error?x.message:String(x);h.includes("stage_field")?this.log.warn(`[yt-sync] CONFIGURATION ERROR \u2014 ${h}`):this.log.warn(`[yt-sync] listIssues failed: ${h}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let x of o){if(s.add(x.id),a.has(x.status))continue;let h=await _y(r,x.id,e.sinceMs,this.log);h&&i.set(x.id,h)}let c=[];for(let x of e.offBoardIssueIds){if(s.has(x))continue;let h=await _y(r,x,e.sinceMs,this.log);h&&h.length>0&&i.set(x,h);let T=await Ay(r,x,e.stageField,this.log);if(T)c.push(T);else if(h&&h.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}let l=o.filter(x=>!a.has(x.status)),{attachmentsByIssue:u,attachmentKeys:p}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let d=[...l,...c].map(x=>({issue:x,comments:i.get(x.id)??[],attachments:u.get(x.id)??[]}));d.push(...await Gg(this.options.contextDir,d,x=>Ay(r,x,e.stageField,this.log)));try{await Ns(this.options.contextDir,e.projectId,d),this.abandonedTicks=0;for(let x of p)this.shippedAttachments.add(x)}catch(x){let h=x instanceof Error?x.message:String(x);this.abandonTick(`context task sync failed: ${h}`);return}let f=this.options.isSelfComment??(()=>!1),m=[],y=[];for(let[x,h]of i){let T=h.filter(v=>!f(v.id));if(T.length===0)continue;m.push({issueId:x,comments:T.map(eI)});let R=T.flatMap(v=>{let P=Kr(v.body);return P?[{commentId:v.id,author:v.author,name:P.name,args:P.args,createdAt:v.createdAt}]:[]});R.length>0&&y.push({issueId:x,commands:R})}let b={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Py),commentsBatch:m,...y.length>0?{commandsBatch:y}:{},...c.length>0?{offBoardIssues:c.map(Py)}:{},observedAtMs:n};this.send(b);let w=m.reduce((x,h)=>x+h.comments.length,0),k=y.reduce((x,h)=>x+h.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${w} commands=${k} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let p=`${s.id}:${u.id}`;if(this.shippedAttachments.has(p))continue;let d;try{d=await n.downloadAttachment(u.url)}catch(m){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${m instanceof Error?m.message:String(m)}`);continue}let f=tI(u.name);l.has(f)&&(f=`${u.id}-${f}`),l.add(f),c.push({name:f,contentBase64:d.toString("base64")}),i.push(p)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Py(t){let{description:e,...r}=t;return r}function eI(t){let{body:e,...r}=t;return r}function tI(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 Ay(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 _y(t,e,r,n){try{return await t.listComments(e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function wI(t,e){let r=t.repos.filter(i=>i.mirror);if(r.length===0)return[];let{mirrorLag:n}=await Promise.resolve().then(()=>(Ls(),Os)),o=[];for(let i of r){let s=i.mountAs==="."?t.root:rn(t.root,i.mountAs);try{o.push({repo:i.name,behind:await n(i,s)})}catch(a){e.warn(`[mirror] lag for ${i.name} unknown: ${a instanceof Error?a.message:String(a)}`),o.push({repo:i.name,behind:null})}}return o}var hu="npm i -g @code-partner/codepipe@latest";function ea(t,e={}){let r=e.log??{info:h=>console.log(h),warn:h=>console.warn(h)};r.info(`codepipe-cli v${ot} (protocol ${Rt})`);let n=h=>e.onEvent?.(h),o=e.workspace;o?.contextDir&&Gm(o.contextDir,r);let i=()=>{if(o?.contextDir)try{Gn(o.contextDir,o.root,r)}catch(h){r.warn(`[skills] materialize failed (non-fatal): ${h instanceof Error?h.message:String(h)}`)}};i();let s=yu("CLI_TRACKING_POLL_INTERVAL_SEC"),a=parseInt(process.env.CLI_BRANCH_CI_POLL_INTERVAL_SEC??"300",10),c=Number.isFinite(a)&&a>0?a*1e3:3e5,l=yu("CLI_YOUTRACK_POLL_INTERVAL_SEC"),u=(()=>{let h=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(h)&&h>0?h*1e3:6e5})(),p=!1,d=!1,f=!1,m=!1,y=new Set,b=!1,w=new Set,k=x();function x(){let h=Bs(t.hubUrl,t.cliToken),T=null,R=new Ws(s,U=>{h.readyState===h.OPEN&&h.send(JSON.stringify(U))},r),v=new qs(s,U=>{h.readyState===h.OPEN&&h.send(JSON.stringify(U))},r),P=new Ys(c,U=>{h.readyState===h.OPEN&&h.send(JSON.stringify(U))},r),N=o&&o.repos.length>0?new Hs(yu("CLI_LOCAL_PULL_INTERVAL_SEC"),()=>Ks(t.hubUrl,t.cliToken,t.projectId),{root:o.root,repos:o.repos},r):null,G=new Vs(l,U=>{h.readyState===h.OPEN&&h.send(JSON.stringify(U))},r,{contextDir:o?.contextDir??null,isSelfComment:U=>w.has(U)}),W=null,C=async()=>{try{let U={trackerProvider:Jl(o?.contextDir??null)};try{let S=await se(t.hubUrl,t.cliToken,t.projectId);U={...U,repos:S.repos,contextRepo:S.contextRepo},v.setRepos(t.projectId,S.repos),P.setRepos(t.projectId,S.repos)}catch(S){r.warn(`[readiness] could not fetch project summary for push checks: ${S instanceof Error?S.message:String(S)}`)}let K=await bm(t.projectId,U),D=o?await wI(o,r):[];if(i(),h.readyState!==h.OPEN)return;let $={type:"cli_readiness",projectId:t.projectId,ready:K.ready,checks:K.checks,creds:K.creds,secretNames:Af(t.projectId),...o?{mirrors:D}:{},checkedAt:K.checkedAt};if(h.send(JSON.stringify($)),K.ready)r.info("[readiness] ready");else{let S=K.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${S.join(", ")}`)}let _=Em(K.creds,f);if(_==="open"){f=!0;let S=ll(t.hubUrl,t.projectId);r.info(`[agent-auth] Claude token invalid (401) \u2014 opening the dashboard to re-authorize: ${S}`),fr(S)}else _==="rearm"&&(f=!1)}catch(U){r.warn(`[readiness] check failed: ${U instanceof Error?U.message:String(U)}`)}},g=()=>{C(),W=setInterval(()=>void C(),u),typeof W.unref=="function"&&W.unref()},B=()=>{W&&(clearInterval(W),W=null)},L=150,q=new Map,te=U=>{let K=q.get(U);if(!K||(K.timer&&clearTimeout(K.timer),q.delete(U),K.events.length===0||h.readyState!==h.OPEN))return;let D={type:"run_activity",projectId:t.projectId,runId:U,events:K.events};h.send(JSON.stringify(D))},le=(U,K)=>{let D=q.get(U);if(D||(D={events:[],timer:null},q.set(U,D)),D.events.push(K),K.kind==="result"){te(U);return}D.timer||(D.timer=setTimeout(()=>te(U),L),D.timer.unref?.())},ut=o?.contextDir?new ds(o.contextDir,t.projectId,U=>{h.readyState===h.OPEN&&h.send(JSON.stringify(U))},r):null,Wt=async()=>{let U=o?.contextDir;if(!U)throw new Error("no context repo clone on this CLI");let K;try{K=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let D=await mh(U,t.projectId,K,r);return h.readyState===h.OPEN&&h.send(JSON.stringify(D)),D},we=null,Ke=async()=>{let U=o?.contextDir;if(U)try{let{readContextIndexHub:K,collectSearchRows:D}=await Promise.resolve().then(()=>(ni(),ri));if(K(U)!=="metadata")return;let $=D(U);h.readyState===h.OPEN&&(h.send(JSON.stringify({type:"model_index",projectId:t.projectId,rows:$})),r.info(`[model] tier-2 index snapshot pushed (${$.length} rows)`))}catch(K){r.warn(`[model] tier-2 index push failed (non-fatal): ${K instanceof Error?K.message:String(K)}`)}},_e=()=>{we&&clearTimeout(we),we=setTimeout(()=>void Ke(),5e3)},xt=async()=>{if(!o?.contextDir)throw new Error("no Context Repo clone on this CLI");if(b)throw new Error("model bootstrap is already running");b=!0;try{let U=await se(t.hubUrl,t.cliToken,t.projectId),{bootstrapDaemonModel:K}=await Promise.resolve().then(()=>(ui(),Qs)),D=await K(t.projectId,{root:o.root,contextDir:o.contextDir},U.repos,$=>r.info(`[model] ${$}`));return r.info(`[model] bootstrap done: ${D.repos} repos, ${D.events} task events`),_e(),D}finally{b=!1}},Ie=null,dt=async U=>{if(o?.contextDir)try{let K=await Promise.resolve().then(()=>(ui(),Qs)),D={root:o.root,contextDir:o.contextDir,repos:o.repos};if(K.shouldAutoBootstrapModel(o.contextDir)){await K.syncWorkspaceMirrors(D,_=>r.info(_));try{await xt()}catch(_){r.warn(`[model] auto-bootstrap failed (non-fatal): ${_ instanceof Error?_.message:String(_)}`)}return}(await K.rebuildWorkspaceModelIfStale(D,{fetch:U,onLog:_=>r.info(_)})).rebuilt.length>0&&_e()}catch(K){r.warn(`[model] release-path rebuild failed (non-fatal): ${K instanceof Error?K.message:String(K)}`)}},St=U=>{Ie&&clearTimeout(Ie),Ie=setTimeout(()=>void dt(U),6e4)},Nr=setInterval(()=>void dt(!0),6*36e5);return h.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let U=Uf(t.projectId),K=ee("ORIGIN")==="farm"?"farm":"local",D=ee("FARM_ID"),$=t.accountEmail??U.email,_;try{let I=_h(t.projectId);I&&(_=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let S={type:"register",projectId:t.projectId,platformVersion:ot,protocolVersion:Rt,accountId:U.accountId,accountSourceKey:U.sourceKey,accountLabel:U.label,origin:K,inFlightActionIds:[...y],...$?{accountEmail:$}:{},...K==="farm"&&D?{farmId:D}:{},..._?{sealPublicKey:_}:{}};h.send(JSON.stringify(S))}),h.on("message",async U=>{let K=U.toString("utf-8");if(K==="pong"||K==="ping")return;let D;try{D=JSON.parse(K)}catch{return}if(!D||typeof D!="object")return;let $=D.type;if($==="registered"){let S=D;if(S.ok){if(r.info(`[ws] registered for project ${S.projectId}`),n({kind:"registered",projectId:S.projectId??t.projectId}),R.start(),v.start(),P.start(),N?.start(),ut?.start(),g(),gu(t,o,r),o?.contextDir){try{let I=fs(o.contextDir,t.projectId);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),d||(d=!0,Wt().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}Ke(),St(!0)}}else r.warn(`[ws] register rejected: ${S.reason??"unknown"}`),n({kind:"register_rejected",reason:S.reason??"unknown"}),p=!0,h.close();return}if($==="hello"){let S=D;T=Eo(S.protocolVersion);let I=T?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${I}`),T||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ot}, protocol ${Rt}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${hu}`),n({kind:"incompatible",hubVersion:typeof S.platformVersion=="string"?S.platformVersion:null,hubProtocol:typeof S.protocolVersion=="number"?S.protocolVersion:null,updateCommand:hu}));return}if($==="tracking_targets"){R.setTargets(D.targets),N?.poke();return}if($==="youtrack_sync_request"){G.setRequest(D);return}if($==="youtrack_force_sync"){G.forceSync();return}if($==="sync_local"){await vI(D,o,h,r);return}if($==="provision_repo"){let S=D;r.info(`[repo] provision_repo: ${S.repo.name} (${S.repo.host}:${S.repo.owner}/${S.repo.repoName})`),await bI(t,o,S.repo,r),await gu(t,o,r);return}if($==="remove_repo"){let S=D;r.info(`[repo] remove_repo: ${S.repoName}${S.purge?" (purge)":""}`),await gu(t,o,r),S.purge&&kI(t,o,S.repoName,r);return}if($==="context_write"){await $I(D,o,h,r),i();return}if($==="adr_promote"){await xI(D,o,h,r),i();return}if($==="cred_update"){let S=D,I=X(t.projectId),F=I?.sealKey?await jh(t.projectId,S.kind,S.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},V={type:"cred_update_result",updateId:S.updateId,projectId:t.projectId,ok:F.ok,...F.detail?{detail:F.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(V)),F.ok?(r.info(`[cred] ${S.kind} replaced${F.detail?` \u2014 ${F.detail}`:""}`),C()):r.warn(`[cred] ${S.kind} replacement rejected: ${F.detail??"unknown"}`);return}if($==="readiness_check"){r.info("[readiness] on-demand check requested"),C();return}if($==="agent_auth_required"){let S=ll(t.hubUrl,t.projectId);r.warn(`[agent-auth] the agent has no working Claude login \u2014 the project is paused.
1079
1093
  fix either way:
1080
1094
  1. sign this machine in: run \`claude\` and log in, then the pipeline resumes on its own
1081
1095
  2. give the project its own token: \`codepipe login\` (or paste one in the dashboard)
1082
- dashboard: ${S}`),m||(m=!0,ur(S));return}if($==="agent_login_start"){pm(t,h,D,r,C);return}if($==="move_to_farm"){let S=D;r.info(`[farm-move] request to move ${t.projectId} onto farm ${S.farmName} (${S.farmId})`);let I=await zg(t,S,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if($==="gh_runner_setup"){let S=D;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let I=await ry(t,S,r);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${S.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if($==="gh_runner_teardown"){let S=D;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let I=await ny(t,S,r);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${S.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if($==="tracker_fields_request"){let S=D,I={type:"tracker_fields_result",requestId:S.requestId,projectId:t.projectId,ok:!1},F=Mt({contextDir:o?.contextDir??null});if(!F.ok)I.error=F.error;else try{I.fields=await F.provider.fetchStateFields(S.projectKey),I.ok=!0}catch(V){I.error=V instanceof Error?V.message:String(V)}h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if($==="project_secret_update"||$==="project_secret_delete"){let S=D,I;if(S.type==="project_secret_update"){let V=X(t.projectId);I=V?.sealKey?cy(t.projectId,S.name,S.sealed,V.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else I=ly(t.projectId,S.name);let F={type:"project_secret_update_result",updateId:S.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(F)),I.ok?(r.info(`[secret] ${S.name} ${S.type==="project_secret_update"?"saved":"deleted"}`+(I.detail?` \u2014 ${I.detail}`:"")),C()):r.warn(`[secret] ${S.name} rejected: ${I.detail??"unknown"}`);return}if($==="sandbox_keys"){let S=X(t.projectId);if(!S){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=Cn(t.projectId),F=ah(D,S,I,r);for(let V of F)h.readyState===h.OPEN&&h.send(JSON.stringify(V));return}if($!=="dispatch_action")return;let P=D;if(T===!1){let S=`refused: HUB protocol incompatible with CLI v${et} (protocol ${$t})`;h.send(JSON.stringify({type:"action_result",actionId:P.actionId,status:"failed",error:S})),r.warn(`[exec] ${P.actionId} (${P.action.type}) \u2192 REFUSED: ${S}`),r.warn(`[exec] update the CLI to clear this: ${ou}`),n({kind:"action",actionId:P.actionId,actionType:P.action.type,ok:!1,error:S});return}if(P.action.type==="model_drift"){y.add(P.actionId);try{let S,I=o?.repos.find(F=>F.name===P.action.repoName);if(!o?.contextDir||!I)S={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:F}=await Promise.resolve().then(()=>(Ry(),Ey)),V=I.mountAs==="."?o.root:Vr(o.root,I.mountAs);S={status:"done",result:{report:await F(V,o.contextDir,I.name)}}}catch(F){S={status:"failed",error:F instanceof Error?F.message:String(F)}}h.send(JSON.stringify({type:"action_result",actionId:P.actionId,...S}))}finally{y.delete(P.actionId)}return}if(P.action.type==="model_bootstrap"){y.add(P.actionId);try{let S;try{let I=await bt();S={status:"done",result:{repos:I.repos,events:I.events}}}catch(I){S={status:"failed",error:I instanceof Error?I.message:String(I)},r.warn(`[model] bootstrap failed: ${S.error}`)}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:P.actionId,...S}))}finally{y.delete(P.actionId)}return}y.add(P.actionId);try{let S=await _g({action:P.action,repo:P.repo,trackerIssueId:P.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:wt?()=>wt.reportNow():void 0,refreshContextStatus:o?.contextDir?Ft:void 0,onRunActivity:de}).catch(V=>({status:"failed",error:V instanceof Error?V.message:String(V)}));P.action.type==="tracker_comment"&&S.status==="done"&&"result"in S&&typeof S.result?.commentId=="string"&&w.add(S.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:P.actionId,...S}));let I=S.status!=="failed",F=!I&&"error"in S?S.error:void 0;I?r.info(`[exec] ${P.actionId} (${P.action.type}) \u2192 done`):r.warn(`[exec] ${P.actionId} (${P.action.type}) \u2192 FAILED: ${F??"?"}`),n({kind:"action",actionId:P.actionId,actionType:P.action.type,ok:I,...F?{error:F}:{}}),I&&["apply_delivery","context_write","create_pr"].includes(P.action.type)&&Be(),I&&["merge_pr","merge_branch"].includes(P.action.type)&&kt(!0)}finally{y.delete(P.actionId)}}),h.on("close",(U,K)=>{let D=K?.toString("utf-8")??"";if(r.info(`[ws] closed code=${U}${D?` reason=${D}`:""}`),R.stop(),v.stop(),_.stop(),N?.stop(),G.stop(),wt?.stop(),B(),clearInterval(er),Ie&&clearTimeout(Ie),we&&clearTimeout(we),D==="replaced"){p=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:U}),!p&&setTimeout(()=>{k=x()},2e3)}),h.on("error",U=>r.warn(`[ws] error: ${U.message}`)),h}return{stop(){p=!0,k.close()}}}async function iu(t,e,r){try{let n=await se(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=Ko(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 YT(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?Vr(e.root,o):Oe(t.projectId,r.name);if(Ty(Vr(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await WT().clone(e?Fn(r):bl(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 VT(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?Vr(e.root,o):Oe(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Ty(Vr(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{HT(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 zT(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=Vr(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await mm(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 XT(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 Pe(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 JT(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 Im(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 su(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}Le();ue();Jt();cu();Et();cs();async function Uy(t={profile:void 0}){let{cfg:e,profile:r}=Tn(t.profile),n=X(e.projectId);n&&No(n),Ho(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Wo(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),qo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=oi(lu(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Bi("CLI_LOG",i,o);if(s.enabled){let d=new An(s);Fi(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=En(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=oi(lu(),".codepipe",r?oi("profiles",r,"context"):"context");if(await Wl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await My(()=>qs({cfg:e,secrets:n,contextDir:d,log:{info:f=>console.log(f),warn:f=>console.warn(f)}}),{log:{warn:f=>console.warn(f)}}),a||await Wl(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let f=oi(lu(),".codepipe",r?oi("profiles",r,"context-config"):"context-config");Ji(a.contextDir,f,{info:m=>console.log(m),warn:m=>console.warn(m)})}}let l=Hs(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(`
1083
- [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}no();Ge();Le();async function Zb(t={profile:void 0}){let e=Ve(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Ps(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await se(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=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`)")}yi();import{readFileSync as __}from"node:fs";M();Ge();Jt();fi();Hr();zt();Kr();Le();ue();function Ee(t){throw new Error(t)}function Ae(t,e){return(typeof t!="string"||t.trim().length===0)&&Ee(`config: '${e}' must be a non-empty string`),t.trim()}function ki(t,e){if(t==null)return;typeof t!="string"&&Ee(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function j_(t){(!t||typeof t!="object")&&Ee("config: expected a JSON object");let e=t,r=Ae(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Ee("config: 'hubUrl' must start with http(s)://");let n=Ae(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&Ee("config: 'project' is required");let i=o,s=Ae(i.id,"project.id");nr.test(s)||Ee("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Ae(i.name,"project.name"),c=Ae(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Ee("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Ee("config: 'project.repos' must be an array");let u=l.map((k,x)=>{(!k||typeof k!="object")&&Ee(`config: project.repos[${x}] must be an object`);let h=k,T=Ae(h.host,`project.repos[${x}].host`);T!=="github"&&T!=="bitbucket"&&T!=="gitlab"&&Ee(`config: project.repos[${x}].host must be 'github', 'bitbucket' or 'gitlab'`);let R={name:Ae(h.name,`project.repos[${x}].name`),host:T,owner:Ae(h.owner,`project.repos[${x}].owner`),repoName:Ae(h.repoName,`project.repos[${x}].repoName`)},v=ki(h.defaultBranch,`project.repos[${x}].defaultBranch`);v&&(R.defaultBranch=v);let _=ki(h.mountAs,`project.repos[${x}].mountAs`);return _&&(R.mountAs=_),R}),p=i.contextRepo;(!p||typeof p!="object")&&Ee("config: 'project.contextRepo' is required");let d=p,f=ki(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&Ee("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:Ae(d.owner,"project.contextRepo.owner"),name:ki(d.name,"project.contextRepo.name")??jt(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},b=ki(i.youtrackProjectKey,"project.youtrackProjectKey");if(b&&(y.project.youtrackProjectKey=b),i.index!==void 0&&(typeof i.index!="boolean"&&Ee("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Ee("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let k=Ae(i.llmProvider,"project.llmProvider");k==="codex"&&Ee(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),k!=="claude"&&Ee("config: 'project.llmProvider' must be 'claude'"),y.project.llmProvider=k}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&Ee("config: 'secrets' must be an object");let k=w,x={};if(k.github){let h=k.github;x.github={token:Ae(h.token,"secrets.github.token")}}if(k.bitbucket){let h=k.bitbucket;x.bitbucket={email:Ae(h.email,"secrets.bitbucket.email"),apiToken:Ae(h.apiToken,"secrets.bitbucket.apiToken")}}if(k.gitlab){let h=k.gitlab;x.gitlab={token:Ae(h.token,"secrets.gitlab.token")}}if(k.youtrack){let h=k.youtrack;x.youtrack={url:Ae(h.url,"secrets.youtrack.url").replace(/\/$/,""),token:Ae(h.token,"secrets.youtrack.token")}}if(k.contextWrite){let h=k.contextWrite;x.contextWrite={token:Ae(h.token,"secrets.contextWrite.token")}}y.secrets=x}return y}async function N_(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function O_(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await or(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 ir(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await qi(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 sr(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await lr({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function dv(t){let e=!t.configPath||t.configPath==="-"?await N_():__(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){Ee(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=j_(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 O_(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 oo(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Pn(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){Ee(`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 gr(o,i,a)}catch(d){if(d instanceof J&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await se(o,i,s.id);else if(d instanceof J)Ee(`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(ie(p),Yt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Nt(s.id)}`),pr(s.id,Lt(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??tt),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await ri(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`)}Ge();ue();import{cancel as pv,intro as fv,isCancel as mv,log as dd,outro as L_,password as hv}from"@clack/prompts";async function M_(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function gv(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await M_(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){fv("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),dd.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await hv({message:"Claude OAuth token"});mv(i)&&(pv("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Ui({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Br()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ve(t.profile);if(!e){fv(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),dd.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await hv({message:"Claude OAuth token"});mv(i)&&(pv("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=X(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ie(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(dd.success("Claude OAuth token saved."),L_("It will be sealed into job bundles when a SANDBOX (re)connects."))}Ge();ue();Oo();async function yv(t){if(t.shared){let n=In();if(!n?.claude?.oauthToken){console.log(`No shared Claude token set (${Br()}).`);return}let{claude:o,...i}=n;Ui(i),console.log(`Shared Claude token removed from ${Br()}.`),pd();return}let e=Ve(t.profile),r=X(e.projectId);if(!r?.claude?.oauthToken){console.log(`Project ${e.projectId} has no Claude token of its own.`),pd();return}delete r.claude,ie(r),console.log(`Claude token removed for project ${e.projectId}.`),pd(),console.log("Restart `codepipe up` (or the daemon) so runners get a re-sealed bundle.")}function pd(){if(In()?.claude?.oauthToken){console.log("Jobs will now use the machine/farm-wide token (`codepipe logout --shared` clears that too).");return}let e=Vt();if(e){console.log(`Jobs will now run on this machine's Claude Code login${e.email?` (${e.email})`:""}.`);return}console.log("This machine has no Claude Code login either \u2014 sign in with `claude`, or set a token with `codepipe login`.")}ni();M();Ge();Jt();fi();Hr();ca();Le();ue();import{cancel as D_,confirm as U_,intro as B_,isCancel as wv,log as He,outro as F_,select as bv,text as Rr}from"@clack/prompts";function kv(t){D_(t),process.exit(1)}function uo(t){return wv(t)&&kv("aborted"),t}function vi(t){return wv(t)&&kv("aborted"),typeof t=="string"?t:""}async function G_(t,e){let r=uo(await bv({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=vi(await Rr({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=vi(await Rr({message:"Context Repo name",placeholder:jt(t),initialValue:jt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function vv(t={profile:void 0}){let e=Ve(t.profile);B_(`codepipe project add \u2192 ${e.hubUrl}`);let r=uo(await Rr({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>nr.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=uo(await Rr({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=uo(await bv({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=uo(await Rr({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=uo(await U_({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=vi(await Rr({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:w=>!w||!w.trim()||Ze(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let f=Ze(d);He.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=vi(await Rr({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),y=vi(await Rr({message:"default branch (optional)",placeholder:"main"})).trim(),b={name:m,host:f.host,owner:f.owner,repoName:f.repoName};y&&(b.defaultBranch=y),a.push(b)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await G_(r,a),u=X(e.projectId);He.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await oo(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??Pn(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>He.message(d),warn:d=>He.warn(d)}})}catch(d){He.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,He.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await gr(e.hubUrl,e.cliToken,c);He.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),pr(r,Lt(c,s,u?.youtrack?.url),{info:f=>He.message(f),warn:f=>He.warn(f)}),d.contextRepo&&(He.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),He.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&He.error(` error: ${d.provisioningError}`),F_("done")}catch(d){d instanceof J?(He.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&He.message(JSON.stringify(d.payload,null,2))):He.error(d instanceof Error?d.message:String(d)),process.exit(1)}}no();Ge();Le();ue();Et();yi();import{existsSync as K_,rmSync as H_}from"node:fs";import{confirm as W_,intro as q_,isCancel as Y_,log as Tr,outro as V_,spinner as z_}from"@clack/prompts";function Bt(t){Tr.error(t),process.exit(1)}var $v=t=>t.trim().replace(/\/+$/,"");async function xv(t){q_("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??je()?.spec.projectId??void 0;e||Bt("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Rt(e);r||Bt(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=$v(r.hubUrl),o=r.projectId,i=$v(t.hub);i.startsWith("http")||Bt("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Bt(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=z_();w.start(`reading project ${o} from ${n}\u2026`);try{l=await se(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(k){throw w.stop("could not read the source project",1),k instanceof J&&Bt(`source HUB ${n} \u2192 ${k.status} ${k.message}. The source HUB must be reachable with a valid token to move a project.`),k}}l.contextRepo||Bt(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=X(o),p=(t.account??r.accountEmail??await co()).trim().toLowerCase();if(Tr.message(`move project '${o}'
1096
+ dashboard: ${S}`),m||(m=!0,fr(S));return}if($==="agent_login_start"){Sm(t,h,D,r,C);return}if($==="move_to_farm"){let S=D;r.info(`[farm-move] request to move ${t.projectId} onto farm ${S.farmName} (${S.farmId})`);let I=await hy(t,S,o?.contextDir,r);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if($==="gh_runner_setup"){let S=D;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let I=await $y(t,S,r);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${S.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if($==="gh_runner_teardown"){let S=D;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${S.runnerName} (${S.runnerId})`);let I=await xy(t,S,r);h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${S.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if($==="tracker_fields_request"){let S=D,I={type:"tracker_fields_result",requestId:S.requestId,projectId:t.projectId,ok:!1},F=Ft({contextDir:o?.contextDir??null});if(!F.ok)I.error=F.error;else try{I.fields=await F.provider.fetchStateFields(S.projectKey),I.ok=!0}catch(V){I.error=V instanceof Error?V.message:String(V)}h.readyState===h.OPEN&&h.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if($==="project_secret_update"||$==="project_secret_delete"){let S=D,I;if(S.type==="project_secret_update"){let V=X(t.projectId);I=V?.sealKey?Iy(t.projectId,S.name,S.sealed,V.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"}}else I=Cy(t.projectId,S.name);let F={type:"project_secret_update_result",updateId:S.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};h.readyState===h.OPEN&&h.send(JSON.stringify(F)),I.ok?(r.info(`[secret] ${S.name} ${S.type==="project_secret_update"?"saved":"deleted"}`+(I.detail?` \u2014 ${I.detail}`:"")),C()):r.warn(`[secret] ${S.name} rejected: ${I.detail??"unknown"}`);return}if($==="sandbox_keys"){let S=X(t.projectId);if(!S){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=Ln(t.projectId),F=Ih(D,S,I,r);for(let V of F)h.readyState===h.OPEN&&h.send(JSON.stringify(V));return}if($!=="dispatch_action")return;let _=D;if(T===!1){let S=`refused: HUB protocol incompatible with CLI v${ot} (protocol ${Rt})`;h.send(JSON.stringify({type:"action_result",actionId:_.actionId,status:"failed",error:S})),r.warn(`[exec] ${_.actionId} (${_.action.type}) \u2192 REFUSED: ${S}`),r.warn(`[exec] update the CLI to clear this: ${hu}`),n({kind:"action",actionId:_.actionId,actionType:_.action.type,ok:!1,error:S});return}if(_.action.type==="model_drift"){y.add(_.actionId);try{let S,I=o?.repos.find(F=>F.name===_.action.repoName);if(!o?.contextDir||!I)S={status:"failed",error:"no local workspace/repo clone on this CLI"};else try{let{computeDriftReport:F}=await Promise.resolve().then(()=>(qy(),Wy)),V=I.mountAs==="."?o.root:rn(o.root,I.mountAs);S={status:"done",result:{report:await F(V,o.contextDir,I.name)}}}catch(F){S={status:"failed",error:F instanceof Error?F.message:String(F)}}h.send(JSON.stringify({type:"action_result",actionId:_.actionId,...S}))}finally{y.delete(_.actionId)}return}if(_.action.type==="model_bootstrap"){y.add(_.actionId);try{let S;try{let I=await xt();S={status:"done",result:{repos:I.repos,events:I.events}}}catch(I){S={status:"failed",error:I instanceof Error?I.message:String(I)},r.warn(`[model] bootstrap failed: ${S.error}`)}h.readyState===h.OPEN&&h.send(JSON.stringify({type:"action_result",actionId:_.actionId,...S}))}finally{y.delete(_.actionId)}return}y.add(_.actionId);try{let S=await Zg({action:_.action,repo:_.repo,trackerIssueId:_.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:ut?()=>ut.reportNow():void 0,refreshContextStatus:o?.contextDir?Wt:void 0,onRunActivity:le}).catch(V=>({status:"failed",error:V instanceof Error?V.message:String(V)}));_.action.type==="tracker_comment"&&S.status==="done"&&"result"in S&&typeof S.result?.commentId=="string"&&w.add(S.result.commentId),h.send(JSON.stringify({type:"action_result",actionId:_.actionId,...S}));let I=S.status!=="failed",F=!I&&"error"in S?S.error:void 0;I?r.info(`[exec] ${_.actionId} (${_.action.type}) \u2192 done`):r.warn(`[exec] ${_.actionId} (${_.action.type}) \u2192 FAILED: ${F??"?"}`),n({kind:"action",actionId:_.actionId,actionType:_.action.type,ok:I,...F?{error:F}:{}}),I&&["apply_delivery","context_write","create_pr"].includes(_.action.type)&&_e(),I&&["merge_pr","merge_branch"].includes(_.action.type)&&St(!0)}finally{y.delete(_.actionId)}}),h.on("close",(U,K)=>{let D=K?.toString("utf-8")??"";if(r.info(`[ws] closed code=${U}${D?` reason=${D}`:""}`),R.stop(),v.stop(),P.stop(),N?.stop(),G.stop(),ut?.stop(),B(),clearInterval(Nr),Ie&&clearTimeout(Ie),we&&clearTimeout(we),D==="replaced"){p=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:U}),!p&&setTimeout(()=>{k=x()},2e3)}),h.on("error",U=>r.warn(`[ws] error: ${U.message}`)),h}return{stop(){p=!0,k.close()}}}async function gu(t,e,r){try{let n=await se(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=await Xo(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 bI(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?rn(e.root,o):Ue(t.projectId,r.name);if(Yy(rn(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await yI().clone(e?qn(r):Il(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 kI(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?rn(e.root,o):Ue(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Yy(rn(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{gI(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 vI(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=rn(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Rm(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 $I(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 Pe(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 xI(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 qm(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 yu(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}Be();de();Bt();bu();Ct();ks();async function iw(t={profile:void 0}){let{cfg:e,profile:r}=Nn(t.profile),n=X(e.projectId);n&&Bo(n),Jo(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Zo(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Qo(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=di(ku(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=zi("CLI_LOG",i,o);if(s.enabled){let d=new Dn(s);Xi(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=_n(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=di(ku(),".codepipe",r?di("profiles",r,"context"):"context");if(await ru(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await nw(()=>ra({cfg:e,secrets:n,contextDir:d,log:{info:f=>console.log(f),warn:f=>console.warn(f)}}),{log:{warn:f=>console.warn(f)}}),a||await ru(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let f=di(ku(),".codepipe",r?di("profiles",r,"context-config"):"context-config");us(a.contextDir,f,{info:m=>console.log(m),warn:m=>console.warn(m)})}}let l=ea(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(`
1097
+ [${d}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}co();We();Be();async function wk(t={profile:void 0}){let e=Ze(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Bs(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let p=JSON.parse(u);p.type==="registered"?(a=!!p.ok,clearTimeout(c),r.send("ping")):p.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await se(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=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`)")}Si();import{readFileSync as ij}from"node:fs";M();We();Bt();ki();Zr();Qt();zr();Be();de();function Ee(t){throw new Error(t)}function Ae(t,e){return(typeof t!="string"||t.trim().length===0)&&Ee(`config: '${e}' must be a non-empty string`),t.trim()}function Ti(t,e){if(t==null)return;typeof t!="string"&&Ee(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function sj(t){(!t||typeof t!="object")&&Ee("config: expected a JSON object");let e=t,r=Ae(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Ee("config: 'hubUrl' must start with http(s)://");let n=Ae(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&Ee("config: 'project' is required");let i=o,s=Ae(i.id,"project.id");ir.test(s)||Ee("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Ae(i.name,"project.name"),c=Ae(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Ee("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Ee("config: 'project.repos' must be an array");let u=l.map((k,x)=>{(!k||typeof k!="object")&&Ee(`config: project.repos[${x}] must be an object`);let h=k,T=Ae(h.host,`project.repos[${x}].host`);T!=="github"&&T!=="bitbucket"&&T!=="gitlab"&&Ee(`config: project.repos[${x}].host must be 'github', 'bitbucket' or 'gitlab'`);let R={name:Ae(h.name,`project.repos[${x}].name`),host:T,owner:Ae(h.owner,`project.repos[${x}].owner`),repoName:Ae(h.repoName,`project.repos[${x}].repoName`)},v=Ti(h.defaultBranch,`project.repos[${x}].defaultBranch`);v&&(R.defaultBranch=v);let P=Ti(h.mountAs,`project.repos[${x}].mountAs`);return P&&(R.mountAs=P),R}),p=i.contextRepo;(!p||typeof p!="object")&&Ee("config: 'project.contextRepo' is required");let d=p,f=Ti(d.host,"project.contextRepo.host")??"github";f!=="github"&&f!=="bitbucket"&&f!=="gitlab"&&Ee("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let m={host:f,owner:Ae(d.owner,"project.contextRepo.owner"),name:Ti(d.name,"project.contextRepo.name")??Dt(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:m}},b=Ti(i.youtrackProjectKey,"project.youtrackProjectKey");if(b&&(y.project.youtrackProjectKey=b),i.index!==void 0&&(typeof i.index!="boolean"&&Ee("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Ee("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites),i.llmProvider!==void 0){let k=Ae(i.llmProvider,"project.llmProvider");k==="codex"&&Ee(`config: 'project.llmProvider' "codex" is not yet supported (coming soon); use "claude".`),k!=="claude"&&Ee("config: 'project.llmProvider' must be 'claude'"),y.project.llmProvider=k}let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&Ee("config: 'secrets' must be an object");let k=w,x={};if(k.github){let h=k.github;x.github={token:Ae(h.token,"secrets.github.token")}}if(k.bitbucket){let h=k.bitbucket;x.bitbucket={email:Ae(h.email,"secrets.bitbucket.email"),apiToken:Ae(h.apiToken,"secrets.bitbucket.apiToken")}}if(k.gitlab){let h=k.gitlab;x.gitlab={token:Ae(h.token,"secrets.gitlab.token")}}if(k.youtrack){let h=k.youtrack;x.youtrack={url:Ae(h.url,"secrets.youtrack.url").replace(/\/$/,""),token:Ae(h.token,"secrets.youtrack.token")}}if(k.contextWrite){let h=k.contextWrite;x.contextWrite={token:Ae(h.token,"secrets.contextWrite.token")}}y.secrets=x}return y}async function aj(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function cj(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await ar(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 cr(e.bitbucket.email,e.bitbucket.apiToken,n);if(r){let i=await ts(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 lr(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await pr({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Pv(t){let e=!t.configPath||t.configPath==="-"?await aj():ij(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(d){Ee(`config: invalid JSON \u2014 ${d instanceof Error?d.message:String(d)}`)}let n=sj(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 cj(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 lo(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??Mn(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:d=>console.log(` ${d}`),warn:d=>console.warn(` ${d}`)}})}catch(d){Ee(`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 vr(o,i,a)}catch(d){if(d instanceof J&&d.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await se(o,i,s.id);else if(d instanceof J)Ee(`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(ie(p),Jt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ut(s.id)}`),Xr(s.id,_t(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url,void 0,s.llmProvider??it),{info:d=>console.log(d),warn:d=>console.warn(d)}),s.index)try{let{jobId:d}=await li(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${d}); runs once a SANDBOX claims it.`)}catch(d){console.warn(`could not enqueue index job: ${d instanceof Error?d.message:String(d)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}We();de();import{cancel as Av,intro as _v,isCancel as jv,log as xd,outro as lj,password as Nv}from"@clack/prompts";async function uj(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Ov(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await uj(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){_v("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),xd.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Nv({message:"Claude OAuth token"});jv(i)&&(Av("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Vi({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${qr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ze(t.profile);if(!e){_v(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),xd.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Nv({message:"Claude OAuth token"});jv(i)&&(Av("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=X(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},ie(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(xd.success("Claude OAuth token saved."),lj("It will be sealed into job bundles when a SANDBOX (re)connects."))}We();de();Fo();async function Lv(t){if(t.shared){let n=On();if(!n?.claude?.oauthToken){console.log(`No shared Claude token set (${qr()}).`);return}let{claude:o,...i}=n;Vi(i),console.log(`Shared Claude token removed from ${qr()}.`),Sd();return}let e=Ze(t.profile),r=X(e.projectId);if(!r?.claude?.oauthToken){console.log(`Project ${e.projectId} has no Claude token of its own.`),Sd();return}delete r.claude,ie(r),console.log(`Claude token removed for project ${e.projectId}.`),Sd(),console.log("Restart `codepipe up` (or the daemon) so runners get a re-sealed bundle.")}function Sd(){if(On()?.claude?.oauthToken){console.log("Jobs will now use the machine/farm-wide token (`codepipe logout --shared` clears that too).");return}let e=Zt();if(e){console.log(`Jobs will now run on this machine's Claude Code login${e.email?` (${e.email})`:""}.`);return}console.log("This machine has no Claude Code login either \u2014 sign in with `claude`, or set a token with `codepipe login`.")}ui();M();We();Bt();ki();Zr();wa();Be();de();import{cancel as dj,confirm as pj,intro as fj,isCancel as Mv,log as ze,outro as mj,select as Dv,text as Ar}from"@clack/prompts";function Uv(t){dj(t),process.exit(1)}function yo(t){return Mv(t)&&Uv("aborted"),t}function Ii(t){return Mv(t)&&Uv("aborted"),typeof t=="string"?t:""}async function hj(t,e){let r=yo(await Dv({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=Ii(await Ar({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=Ii(await Ar({message:"Context Repo name",placeholder:Dt(t),initialValue:Dt(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Bv(t={profile:void 0}){let e=Ze(t.profile);fj(`codepipe project add \u2192 ${e.hubUrl}`);let r=yo(await Ar({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:d=>ir.test(d.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=yo(await Ar({message:"project name (human-readable)",placeholder:"CodePartner",validate:d=>d.trim().length>0?void 0:"required"})).trim(),o=yo(await Dv({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=yo(await Ar({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=yo(await pj({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let d=Ii(await Ar({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:w=>!w||!w.trim()||rt(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!d)break;let f=rt(d);ze.message(`${f.host}: ${f.owner}/${f.repoName}`);let m=Ii(await Ar({message:"repo logical name (used inside Context Repo paths)",placeholder:f.repoName,initialValue:f.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),y=Ii(await Ar({message:"default branch (optional)",placeholder:"main"})).trim(),b={name:m,host:f.host,owner:f.owner,repoName:f.repoName};y&&(b.defaultBranch=y),a.push(b)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await hj(r,a),u=X(e.projectId);ze.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let p;try{p=await lo(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??Mn(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:d=>ze.message(d),warn:d=>ze.warn(d)}})}catch(d){ze.error(`Context Repo provisioning failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}c.contextRepo=p,ze.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let d=await vr(e.hubUrl,e.cliToken,c);ze.success(`project "${d.projectId}" \u2014 ${d.provisioningStatus}`),Xr(r,_t(c,s,u?.youtrack?.url),{info:f=>ze.message(f),warn:f=>ze.warn(f)}),d.contextRepo&&(ze.message(` context repo: ${d.contextRepo.owner}/${d.contextRepo.name} (${d.contextRepo.cloneUrl})`),ze.message(` branch: ${d.contextRepo.branch}`)),d.provisioningError&&ze.error(` error: ${d.provisioningError}`),mj("done")}catch(d){d instanceof J?(ze.error(`HUB \u2192 ${d.status} ${d.message}`),d.payload&&typeof d.payload=="object"&&ze.message(JSON.stringify(d.payload,null,2))):ze.error(d instanceof Error?d.message:String(d)),process.exit(1)}}co();We();Be();de();Ct();Si();import{existsSync as gj,rmSync as yj}from"node:fs";import{confirm as wj,intro as bj,isCancel as kj,log as _r,outro as vj,spinner as $j}from"@clack/prompts";function Ht(t){_r.error(t),process.exit(1)}var Fv=t=>t.trim().replace(/\/+$/,"");async function Gv(t){bj("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??Ne()?.spec.projectId??void 0;e||Ht("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=Pt(e);r||Ht(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Fv(r.hubUrl),o=r.projectId,i=Fv(t.hub);i.startsWith("http")||Ht("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Ht(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let w=$j();w.start(`reading project ${o} from ${n}\u2026`);try{l=await se(n,r.cliToken,o),w.stop(`read project ${o} (${l.name})`)}catch(k){throw w.stop("could not read the source project",1),k instanceof J&&Ht(`source HUB ${n} \u2192 ${k.status} ${k.message}. The source HUB must be reachable with a valid token to move a project.`),k}}l.contextRepo||Ht(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=X(o),p=(t.account??r.accountEmail??await ho()).trim().toLowerCase();if(_r.message(`move project '${o}'
1084
1098
  from : ${n} (profile ${e})
1085
1099
  to : ${i} (profile ${s}, project ${a}, account ${p})
1086
1100
  \u2022 the source registration on the old HUB is left intact (non-destructive)
1087
1101
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
1088
- `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let w=await W_({message:"Continue?",initialValue:!0});(Y_(w)||!w)&&Bt("aborted")}!c&&a===o&&Tr.warn(`source and destination share the same project id, so they share one secrets file (${Nt(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:f}=await lo(i,p),m={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:f,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};Tr.step(`registering project on ${i}\u2026`);let y;try{y=await gr(i,d,m)}catch(w){if(w instanceof J&&w.status===409){Tr.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{y=await se(i,d,a)}catch(k){throw k instanceof J&&Bt(`target HUB \u2192 ${k.status} ${k.message}`),k}}else if(w instanceof J&&w.status===403)Bt(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof J)Bt(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}Tr.success(`project ${y.projectId} ready on ${i} (${y.provisioningStatus})`),Yt({hubUrl:i,cliToken:d,projectId:a,accountEmail:f},s);let b={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete b.sandboxPins,ie(b),Tr.success(`profile '${s}' \u2192 ${Nt(a)}`),c){let w=Ct(s);K_(w)&&(H_(w),Tr.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}V_(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}M();Ge();import{existsSync as fd,rmSync as X_,statSync as J_}from"node:fs";import{join as $i,relative as Z_,resolve as Q_}from"node:path";import{cancel as ej,intro as Ev,isCancel as tj,log as xe,outro as Rv,text as rn}from"@clack/prompts";import{simpleGit as Tv}from"simple-git";rd();nd();ca();Le();Gn();ue();Et();function Qe(t){ej(t),process.exit(1)}function nn(t){return tj(t)&&Qe("aborted"),typeof t=="string"?t:""}async function Sv(t){try{let e=await Tv(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function rj(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function nj(t,e){let r=X(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(rj(r,e)){xe.message(`reusing existing ${e} credentials`);return}if(xe.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=nn(await rn({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=nn(await rn({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=nn(await rn({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}}ie(r),xe.success(`saved ${e} credentials`)}async function Iv(t){let e=Ve(t.profile);Ev(`codepipe repo add \u2192 project ${e.projectId}`);let r=je()??void 0,n;try{n=(await se(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){Qe(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await Sv(process.cwd());h?(o=process.cwd(),xe.message(`using the current directory (${h})`)):o=nn(await rn({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:T=>T.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(fd(o)&&J_(o).isDirectory()){i=Q_(o);let h=await Sv(i);h||Qe(`${i} is not a git repository (no origin remote)`);let T=Ze(h);T||Qe(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=T,s=h,xe.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=Ze(o);h||Qe(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,xe.message(`${a}: ${c}/${l}`)}let u=nn(await rn({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)&&Qe(`a repo named "${u}" is already registered`);let p;i&&(p=await gi(i,s));let d=p?Co(p).branches.integration:"",f=nn(await rn({message:"default branch (optional)",placeholder:d||"main",...d?{initialValue:d}:{}})).trim(),m=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=Z_(r.root,i);m=h===""?".":h}let y=nn(await rn({message:"mount_as (directory relative to the workspace root)",placeholder:m,initialValue:m})).trim()||m;n.some(h=>(h.mountAs??h.name)===y)&&Qe(`mount_as "${y}" is already used by another repo`),await nj(e,a);let b={name:u,host:a,owner:c,repoName:l,mountAs:y,...f?{defaultBranch:f}:{}};if(!i){let h=r?$i(r.root,y):Oe(e.projectId,u);if(fd($i(h,".git")))xe.message(`already cloned at ${h}`);else{xe.info(`cloning ${s} \u2192 ${h} \u2026`);try{await Tv().clone(s,h),xe.success(`cloned into ${h}`)}catch(T){Qe(`clone failed: ${T instanceof Error?T.message.trim():String(T)}
1089
- check that your ${a} credentials grant read access to ${c}/${l}`)}}}let w;try{w=await Hg(e.hubUrl,e.cliToken,e.projectId,b)}catch(h){h instanceof J&&Qe(`HUB \u2192 ${h.status} ${h.message}`),Qe(h instanceof Error?h.message:String(h))}let{updated:k,errors:x}=Ko(e.projectId,w.repos,r?.contextDir);for(let h of k)xe.message(`updated ${h}`);for(let h of x)xe.warn(`could not update ${h.path}: ${h.error}`);if(r?.contextDir){if(!p)try{let h=i??$i(r.root,y);p=await gi(h,s)}catch(h){xe.warn(`git-flow detection skipped: ${h instanceof Error?h.message:String(h)}`),p={defaultBranch:null,branches:[]}}try{await da({contextDir:r.contextDir,repoName:u,facts:p,log:h=>xe.message(h)})}catch(h){Qe(`"${u}" was added, but its git-flow choice was NOT saved: ${h instanceof Error?h.message.trim():String(h)}
1090
- re-run the command or set the git-flow manually in project.yaml`)}}xe.success(`added "${u}" \u2014 project now has ${w.repos.length} repo(s)`),Rv("done")}async function Cv(t){let e=Ve(t.profile);Ev(`codepipe repo remove \u2192 project ${e.projectId}`);let r=je()??void 0,n;try{let c=(await se(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 Wg(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof J&&(a.status===404&&Qe(`no repo named "${t.name}" in this project`),Qe(`HUB \u2192 ${a.status} ${a.message}`)),Qe(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=Ko(e.projectId,o.repos,r?.contextDir);for(let a of i)xe.message(`updated ${a}`);for(let a of s)xe.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")xe.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):Oe(e.projectId,t.name);if(fd($i(a,".git")))try{X_(a,{recursive:!0,force:!0}),xe.message(`deleted local clone ${a}`)}catch(c){xe.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else xe.message(`no local clone found to purge (${a})`)}xe.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Rv("done")}async function Pv(t){let e=Ve(t.profile),r;try{r=(await se(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}`)}}ua();Ge();ts();Le();import{existsSync as oj}from"node:fs";import{join as ij}from"node:path";import{simpleGit as sj}from"simple-git";Et();var aj=60;async function Av(t){let{cfg:e}=Tn(t.profile),r=En(e.projectId);if(!r)throw new Error(`no workspace for ${e.projectId} here \u2014 run this from the project folder (the one with .codepipe/)`);let n=new Set,o={info:a=>console.log(a),warn:a=>console.warn(a)},i=async()=>{let a=await js(e.hubUrl,e.cliToken,e.projectId);if(a.length===0){console.log("[pull] nothing ready yet");return}for(let c of a)await Vl(r.root,r.spec.repos,c,n,o);if(await cj(r.contextDir),r.contextDir)try{Mn(r.contextDir,r.root,{info:c=>console.log(`[pull] ${c}`),warn:c=>console.warn(`[pull] ${c}`)})}catch(c){console.warn(`[pull] skills materialize failed \u2014 ${c instanceof Error?c.message:String(c)}`)}};if(!t.watch){await i();return}try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}let s=Math.max(10,t.intervalSec??aj)*1e3;for(console.log(`[pull] watching \u2014 every ${Math.round(s/1e3)}s, Ctrl+C to stop`);;){await new Promise(a=>setTimeout(a,s));try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}}}async function cj(t){if(!(!t||!oj(ij(t,".git"))))try{await sj(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
1091
- `)[0]:String(e)}`)}}ga();import{existsSync as Lv,mkdirSync as lj,readFileSync as uj,writeFileSync as dj}from"node:fs";import{homedir as pj}from"node:os";import{dirname as fj,join as Mv}from"node:path";import*as fo from"node:readline";Le();is();ue();Et();ua();ga();var ka=Mv(pj(),".codepipe","history"),_v=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Dv=500,jv=40;async function Uv(t={}){let e=je();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=X(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)),No(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit."),console.log("");let n=fo.createInterface({input:process.stdin,output:process.stdout,completer:mj,history:Cj(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};Xm(i=>Ir(o,i)),o.daemon=Hs({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>Ir(o,i),warn:i=>Ir(o,i)},onEvent:i=>Ej(o,i),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos}});try{let i={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await fa(i,t.profile,{profile:t.profile});let s=process.argv[1];if(!s)throw new Error("cannot resolve the codepipe entry script for the worker process");let a=ma({entry:s,profile:t.profile,onLine:c=>Ir(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!gd&&po(o,`[worker] exited (code ${c??(l?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),o.workerChild=a,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(i){console.warn(`[worker] could not start the embedded worker (${i instanceof Error?i.message:String(i)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}hd(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await hj(o,s)){Ov(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,hd(o),n.prompt()}),n.on("close",()=>{Ov(o)})}function mj(t){let e=_v.filter(r=>r.startsWith(t));return[e.length?e:_v,t]}async function hj(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return gj(),!1;case"/status":return await yj(t),!1;case"/tasks":return await wj(t,n),!1;case"/task":return await bj(t,n),!1;case"/sync":return await kj(t),!1;case"/logs":return Rj(t,n),!1;case"/monitor":return Tj(t),!1;case"/approve":return await Nv(t,n,"approve"),!1;case"/merge":return await Nv(t,n,"merge"),!1;case"/login":return vj(t,n),!1;case"/secret":return $j(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function gj(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
1092
- `))}async function yj(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=Lv(Mv(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function wj(t,e){let r=Ij(e,"--phase");try{let n=await Fg(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){yd(n)}}async function bj(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Gg(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){yd(n)}}async function kj(t){let e=await hi(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 Nv(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await Kg(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){yd(o)}}function vj(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},ie(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 $j(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(`
1093
- `)}`:" (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}xj(t.secrets,n,i),ie(t.secrets),No(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}Sj(t.secrets,n),ie(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function xj(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 Sj(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 Ej(t,e){switch(e.kind){case"connected":t.connection="connecting",Ir(t,"[hub] connected");break;case"registered":t.connection="registered",Ir(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",po(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Ir(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",po(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":po(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?Ir(t,`[hub] action ${e.actionType} done`):po(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Ir(t,e){t.logBuffer.push(e),t.logBuffer.length>Dv&&t.logBuffer.shift(),t.follow&&po(t,e)}function Rj(t,e){let r=e[0];if(r==="follow"||r==="on"){md(t,!0);return}if(r==="off"){md(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Dv,Number(r)||jv)):jv,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 Tj(t){md(t,!t.follow)}function md(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function po(t,e){fo.cursorTo(process.stdout,0),fo.clearLine(process.stdout,0),process.stdout.write(e+`
1094
- `),t.unread+=1,hd(t),t.rl.prompt(!0)}function hd(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var gd=!1;function Ov(t){if(gd)return;gd=!0,Pj(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
1102
+ `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let w=await wj({message:"Continue?",initialValue:!0});(kj(w)||!w)&&Ht("aborted")}!c&&a===o&&_r.warn(`source and destination share the same project id, so they share one secrets file (${Ut(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:d,accountEmail:f}=await go(i,p),m={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:f,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};_r.step(`registering project on ${i}\u2026`);let y;try{y=await vr(i,d,m)}catch(w){if(w instanceof J&&w.status===409){_r.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{y=await se(i,d,a)}catch(k){throw k instanceof J&&Ht(`target HUB \u2192 ${k.status} ${k.message}`),k}}else if(w instanceof J&&w.status===403)Ht(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof J)Ht(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}_r.success(`project ${y.projectId} ready on ${i} (${y.provisioningStatus})`),Jt({hubUrl:i,cliToken:d,projectId:a,accountEmail:f},s);let b={...u??{},hubUrl:i,cliToken:d,projectId:a};if(delete b.sandboxPins,ie(b),_r.success(`profile '${s}' \u2192 ${Ut(a)}`),c){let w=Nt(s);gj(w)&&(yj(w),_r.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}vj(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}M();We();import{existsSync as Ed,rmSync as xj,statSync as Sj}from"node:fs";import{join as Ci,relative as Ej,resolve as Rj}from"node:path";import{cancel as Tj,intro as Hv,isCancel as Ij,log as xe,outro as Wv,text as dn}from"@clack/prompts";import{simpleGit as qv}from"simple-git";fd();md();wa();Be();Yn();de();Ct();function nt(t){Tj(t),process.exit(1)}function pn(t){return Ij(t)&&nt("aborted"),typeof t=="string"?t:""}async function Kv(t){try{let e=await qv(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function Cj(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function Pj(t,e){let r=X(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(Cj(r,e)){xe.message(`reusing existing ${e} credentials`);return}if(xe.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=pn(await dn({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=pn(await dn({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=pn(await dn({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}}ie(r),xe.success(`saved ${e} credentials`)}async function Yv(t){let e=Ze(t.profile);Hv(`codepipe repo add \u2192 project ${e.projectId}`);let r=Ne()??void 0,n;try{n=(await se(e.hubUrl,e.cliToken,e.projectId)).repos}catch(h){nt(`could not read project from HUB: ${h instanceof Error?h.message:String(h)}`)}let o=t.target?.trim();if(!o){let h=await Kv(process.cwd());h?(o=process.cwd(),xe.message(`using the current directory (${h})`)):o=pn(await dn({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:T=>T.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Ed(o)&&Sj(o).isDirectory()){i=Rj(o);let h=await Kv(i);h||nt(`${i} is not a git repository (no origin remote)`);let T=rt(h);T||nt(`origin ${h} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=T,s=h,xe.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let h=rt(o);h||nt(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=h,s=o,xe.message(`${a}: ${c}/${l}`)}let u=pn(await dn({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)&&nt(`a repo named "${u}" is already registered`);let p;i&&(p=await xi(i,s));let d=p?jo(p).branches.integration:"",f=pn(await dn({message:"default branch (optional)",placeholder:d||"main",...d?{initialValue:d}:{}})).trim(),m=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let h=Ej(r.root,i);m=h===""?".":h}let y=pn(await dn({message:"mount_as (directory relative to the workspace root)",placeholder:m,initialValue:m})).trim()||m;n.some(h=>(h.mountAs??h.name)===y)&&nt(`mount_as "${y}" is already used by another repo`),await Pj(e,a);let b={name:u,host:a,owner:c,repoName:l,mountAs:y,...f?{defaultBranch:f}:{}};if(!i){let h=r?Ci(r.root,y):Ue(e.projectId,u);if(Ed(Ci(h,".git")))xe.message(`already cloned at ${h}`);else{xe.info(`cloning ${s} \u2192 ${h} \u2026`);try{await qv().clone(s,h),xe.success(`cloned into ${h}`)}catch(T){nt(`clone failed: ${T instanceof Error?T.message.trim():String(T)}
1103
+ check that your ${a} credentials grant read access to ${c}/${l}`)}}}let w;try{w=await uy(e.hubUrl,e.cliToken,e.projectId,b)}catch(h){h instanceof J&&nt(`HUB \u2192 ${h.status} ${h.message}`),nt(h instanceof Error?h.message:String(h))}let{updated:k,errors:x}=await Xo(e.projectId,w.repos,r?.contextDir);for(let h of k)xe.message(`updated ${h}`);for(let h of x)xe.warn(`could not update ${h.path}: ${h.error}`);if(r?.contextDir){if(!p)try{let h=i??Ci(r.root,y);p=await xi(h,s)}catch(h){xe.warn(`git-flow detection skipped: ${h instanceof Error?h.message:String(h)}`),p={defaultBranch:null,branches:[]}}try{await va({contextDir:r.contextDir,repoName:u,facts:p,log:h=>xe.message(h)})}catch(h){nt(`"${u}" was added, but its git-flow choice was NOT saved: ${h instanceof Error?h.message.trim():String(h)}
1104
+ re-run the command or set the git-flow manually in project.yaml`)}}xe.success(`added "${u}" \u2014 project now has ${w.repos.length} repo(s)`),Wv("done")}async function Vv(t){let e=Ze(t.profile);Hv(`codepipe repo remove \u2192 project ${e.projectId}`);let r=Ne()??void 0,n;try{let c=(await se(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 dy(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof J&&(a.status===404&&nt(`no repo named "${t.name}" in this project`),nt(`HUB \u2192 ${a.status} ${a.message}`)),nt(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=await Xo(e.projectId,o.repos,r?.contextDir);for(let a of i)xe.message(`updated ${a}`);for(let a of s)xe.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")xe.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?Ci(r.root,n):Ue(e.projectId,t.name);if(Ed(Ci(a,".git")))try{xj(a,{recursive:!0,force:!0}),xe.message(`deleted local clone ${a}`)}catch(c){xe.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else xe.message(`no local clone found to purge (${a})`)}xe.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Wv("done")}async function zv(t){let e=Ze(t.profile),r;try{r=(await se(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}`)}}ka();We();ps();Be();import{existsSync as Aj}from"node:fs";import{join as _j}from"node:path";import{simpleGit as jj}from"simple-git";Ct();var Nj=60;async function Xv(t){let{cfg:e}=Nn(t.profile),r=_n(e.projectId);if(!r)throw new Error(`no workspace for ${e.projectId} here \u2014 run this from the project folder (the one with .codepipe/)`);let n=new Set,o={info:a=>console.log(a),warn:a=>console.warn(a)},i=async()=>{let a=await Ks(e.hubUrl,e.cliToken,e.projectId);if(a.length===0){console.log("[pull] nothing ready yet");return}for(let c of a)await iu(r.root,r.spec.repos,c,n,o);if(await Oj(r.contextDir),r.contextDir)try{Gn(r.contextDir,r.root,{info:c=>console.log(`[pull] ${c}`),warn:c=>console.warn(`[pull] ${c}`)})}catch(c){console.warn(`[pull] skills materialize failed \u2014 ${c instanceof Error?c.message:String(c)}`)}};if(!t.watch){await i();return}try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}let s=Math.max(10,t.intervalSec??Nj)*1e3;for(console.log(`[pull] watching \u2014 every ${Math.round(s/1e3)}s, Ctrl+C to stop`);;){await new Promise(a=>setTimeout(a,s));try{await i()}catch(a){console.warn(`[pull] ${a instanceof Error?a.message:String(a)}`)}}}async function Oj(t){if(!(!t||!Aj(_j(t,".git"))))try{await jj(t).pull(["--ff-only"])}catch(e){console.warn(`[pull] context repo not updated \u2014 ${e instanceof Error?e.message.split(`
1105
+ `)[0]:String(e)}`)}}Ea();import{existsSync as t$,mkdirSync as Lj,readFileSync as Mj,writeFileSync as Dj}from"node:fs";import{homedir as Uj}from"node:os";import{dirname as Bj,join as r$}from"node:path";import*as bo from"node:readline";Be();ys();de();Ct();ka();Ea();var Ia=r$(Uj(),".codepipe","history"),Jv=["/help","/status","/tasks","/task","/sync","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],n$=500,Zv=40;async function o$(t={}){let e=Ne();e||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let r=X(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)),Bo(r),console.log(`connected to ${r.hubUrl} as project ${e.spec.projectId}`),console.log("the CLI daemon and an embedded agent worker run in this session; /logs and /monitor show their output."),console.log("type /help to list commands. Ctrl+D or /quit to exit."),console.log("");let n=bo.createInterface({input:process.stdin,output:process.stdout,completer:Fj,history:r0(),removeHistoryDuplicates:!0}),o={ws:e,secrets:r,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[],workerChild:null,workerExited:!1};yh(i=>jr(o,i)),o.daemon=ea({hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId},{log:{info:i=>jr(o,i),warn:i=>jr(o,i)},onEvent:i=>Zj(o,i),workspace:{root:e.root,contextDir:e.contextDir,repos:e.spec.repos}});try{let i={hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:e.spec.projectId};await $a(i,t.profile,{profile:t.profile});let s=process.argv[1];if(!s)throw new Error("cannot resolve the codepipe entry script for the worker process");let a=xa({entry:s,profile:t.profile,onLine:c=>jr(o,`[worker] ${c}`)});a.on("exit",(c,l)=>{o.workerExited=!0,!Id&&wo(o,`[worker] exited (code ${c??(l?1:0)}) \u2014 agent jobs will NOT run; /quit and restart codepipe to bring it back`)}),o.workerChild=a,console.log("embedded agent worker started \u2014 agent jobs run on this machine.")}catch(i){console.warn(`[worker] could not start the embedded worker (${i instanceof Error?i.message:String(i)}). REPL commands still work; run \`codepipe up --reregister\` if the registration was removed.`)}Td(o),n.prompt(),n.on("line",async i=>{let s=i.trim();if(s.length>0)try{if(await Gj(o,s)){e$(o);return}}catch(a){console.error(a instanceof Error?a.message:String(a))}o.unread=0,Td(o),n.prompt()}),n.on("close",()=>{e$(o)})}function Fj(t){let e=Jv.filter(r=>r.startsWith(t));return[e.length?e:Jv,t]}async function Gj(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return Kj(),!1;case"/status":return await Hj(t),!1;case"/tasks":return await Wj(t,n),!1;case"/task":return await qj(t,n),!1;case"/sync":return await Yj(t),!1;case"/logs":return Qj(t,n),!1;case"/monitor":return e0(t),!1;case"/approve":return await Qv(t,n,"approve"),!1;case"/merge":return await Qv(t,n,"merge"),!1;case"/login":return Vj(t,n),!1;case"/secret":return zj(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Kj(){console.log(["/help show this list","/status connection, project, embedded worker, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon/worker logs / toggle live / clear buffer","/monitor toggle live daemon/worker log streaming (alias /logs follow)","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and the worker, exit"].join(`
1106
+ `))}async function Hj(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=t$(r$(t.ws.root,n.mountAs,".git"));console.log(` ${n.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function Wj(t,e){let r=t0(e,"--phase");try{let n=await ay(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){Cd(n)}}async function qj(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await cy(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){Cd(n)}}async function Yj(t){let e=await $i(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 Qv(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await ly(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Cd(o)}}function Vj(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},ie(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 zj(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(`
1107
+ `)}`:" (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}Xj(t.secrets,n,i),ie(t.secrets),Bo(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}Jj(t.secrets,n),ie(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function Xj(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 Jj(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 Zj(t,e){switch(e.kind){case"connected":t.connection="connecting",jr(t,"[hub] connected");break;case"registered":t.connection="registered",jr(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",wo(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",jr(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",wo(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":wo(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?jr(t,`[hub] action ${e.actionType} done`):wo(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function jr(t,e){t.logBuffer.push(e),t.logBuffer.length>n$&&t.logBuffer.shift(),t.follow&&wo(t,e)}function Qj(t,e){let r=e[0];if(r==="follow"||r==="on"){Rd(t,!0);return}if(r==="off"){Rd(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(n$,Number(r)||Zv)):Zv,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 e0(t){Rd(t,!t.follow)}function Rd(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function wo(t,e){bo.cursorTo(process.stdout,0),bo.clearLine(process.stdout,0),process.stdout.write(e+`
1108
+ `),t.unread+=1,Td(t),t.rl.prompt(!0)}function Td(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Id=!1;function e$(t){if(Id)return;Id=!0,n0(t.rl),t.daemon.stop();let e=t.workerChild;if(!e||t.workerExited){console.log(`
1095
1109
  bye.`),setTimeout(()=>process.exit(0),150);return}console.log(`
1096
- 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 Ij(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function yd(t){t instanceof J?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Cj(){if(!Lv(ka))return[];try{return uj(ka,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Pj(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{lj(fj(ka),{recursive:!0}),dj(ka,r.slice().reverse().join(`
1110
+ 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 t0(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Cd(t){t instanceof J?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function r0(){if(!t$(Ia))return[];try{return Mj(Ia,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function n0(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{Lj(Bj(Ia),{recursive:!0}),Dj(Ia,r.slice().reverse().join(`
1097
1111
  `)+`
1098
- `)}catch{}}no();M();Ye();no();Ge();Le();yi();import{hostname as Aj}from"node:os";import{cancel as _j,confirm as Bv,intro as jj,isCancel as Kv,log as mo,multiselect as Nj,outro as Fv,password as Oj,select as wd,text as bd}from"@clack/prompts";function xi(t){_j(t),process.exit(1)}function ho(t){return Kv(t)&&xi("aborted"),t}function va(t){return Kv(t)&&xi("aborted"),typeof t=="string"?t:""}function $a(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Gv(t,e){try{let{secret:r}=await _s(t,e);return r}catch(r){throw r instanceof J&&r.status===404&&xi("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 Lj(t,e){if(ho(await wd({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 Hl(t,e);if(o.length>0)return ho(await Nj({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}));mo.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){mo.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return va(await bd({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 kd(t){jj("codepipe worker \u2014 set up this machine as a runner");let e=Ke(t.profile);e&&(mo.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),ho(await Bv({message:"re-register this worker?",initialValue:!1}))||xi("keeping the existing registration"));let r=Rt(t.profile)??Rt(),n=va(await bd({message:"HUB URL",placeholder:vt,initialValue:ee("HUB_URL")??r?.hubUrl??vt,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=ho(await wd({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 Gv(n,a),mo.success("account-issued registration token minted");else if(i==="login"){let d=await co();a=(await lo(n,d)).cliToken,s=await Gv(n,a),mo.success("account-issued registration token minted")}else s=va(await Oj({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||xi("a registration token is required");let c=await Lj(n,a),l=va(await bd({message:"worker name",initialValue:Aj(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=ho(await wd({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 zr({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),mo.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!ho(await Bv({message:"start the claim-loop now?",initialValue:!0}))){Fv("registered. start later with `codepipe worker`.");return}Fv("starting the claim-loop\u2026"),await pi(t.profile?{profile:t.profile}:{})}function Dj(){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 ee("PROFILE")}var ye=Dj();lf(ye);var Ue=new Mj;Ue.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(et).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{$a()?await Uv({profile:ye}):await ha({profile:ye})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ue.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await dv({configPath:t.config,skipVerify:t.skipVerify===!0}):await Qk({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await vf({...t,profile:ye})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await ev({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ue.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Uy({profile:ye})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ue.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await Ik({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.command("logout").description("Remove the Claude token (fall back to this machine's Claude Code login)").option("--shared","Clear the machine/farm-wide token in ~/.codepipe/shared.json").action(async t=>{try{await yv({profile:ye,shared:t.shared})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await gv({profile:ye,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Zb({profile:ye})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ue.command("pull").description("Fetch finished task branches into your local clones (no checkout switch)").option("--profile <name>","Config profile").option("--watch","Keep pulling instead of exiting after one pass").option("--interval <sec>","Watch interval in seconds (default 60, minimum 10)",t=>parseInt(t,10)).action(async t=>{if(t.interval!==void 0&&!Number.isFinite(t.interval))throw new Error("--interval expects a number of seconds");await Av({profile:t.profile,...t.watch?{watch:!0}:{},...Number.isFinite(t.interval)?{intervalSec:t.interval}:{}})});Ue.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).option("--debug [categories]","Write local debug logs (comma-separated categories; default: agent-request \u2014 the full prompt and context each agent job receives, under ~/.codepipe/debug/)").action(async t=>{try{await ha({profile:ye,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Hv=Ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Hv.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??ee("HUB_URL")??Rt(ye)?.hubUrl??vt,r=t.token??ee("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&$a()){await kd({profile:ye});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=ee("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??ee("WORKER_NAME"),i=t.llm??ee("WORKER_LLM");await zr({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ye?{profile:ye}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Hv.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Ke(ye)&&$a()){await kd({profile:ye});return}await pi(ye?{profile:ye}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Wv=Ue.command("project").description("Manage CodePipe projects");Wv.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await vv({profile:ye})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Wv.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 xv({...t,cliProfile:ye})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var vd=Ue.command("repo").description("Manage the project's git repositories");vd.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 Iv({profile:ye,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});vd.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 Cv({profile:ye,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});vd.command("list").description("List the project's repos").action(async()=>{try{await Pv({profile:ye})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var qv=Ue.command("model").description("Project map (model/ in the Context Repo)");qv.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 Zl({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});qv.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 Ql({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ue.parseAsync();
1112
+ `)}catch{}}co();M();Je();co();We();Be();Si();import{hostname as o0}from"node:os";import{cancel as i0,confirm as i$,intro as s0,isCancel as c$,log as ko,multiselect as a0,outro as s$,password as c0,select as Pd,text as Ad}from"@clack/prompts";function Pi(t){i0(t),process.exit(1)}function vo(t){return c$(t)&&Pi("aborted"),t}function Ca(t){return c$(t)&&Pi("aborted"),typeof t=="string"?t:""}function Pa(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function a$(t,e){try{let{secret:r}=await Gs(t,e);return r}catch(r){throw r instanceof J&&r.status===404&&Pi("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 l0(t,e){if(vo(await Pd({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 tu(t,e);if(o.length>0)return vo(await a0({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}));ko.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){ko.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return Ca(await Ad({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 _d(t){s0("codepipe worker \u2014 set up this machine as a runner");let e=Ve(t.profile);e&&(ko.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),vo(await i$({message:"re-register this worker?",initialValue:!1}))||Pi("keeping the existing registration"));let r=Pt(t.profile)??Pt(),n=Ca(await Ad({message:"HUB URL",placeholder:Et,initialValue:ee("HUB_URL")??r?.hubUrl??Et,validate:d=>d.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=vo(await Pd({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 a$(n,a),ko.success("account-issued registration token minted");else if(i==="login"){let d=await ho();a=(await go(n,d)).cliToken,s=await a$(n,a),ko.success("account-issued registration token minted")}else s=Ca(await c0({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Pi("a registration token is required");let c=await l0(n,a),l=Ca(await Ad({message:"worker name",initialValue:o0(),validate:d=>d.trim().length>0?void 0:"required"})).trim(),u=vo(await Pd({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 nn({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),ko.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!vo(await i$({message:"start the claim-loop now?",initialValue:!0}))){s$("registered. start later with `codepipe worker`.");return}s$("starting the claim-loop\u2026"),await bi(t.profile?{profile:t.profile}:{})}function d0(){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 ee("PROFILE")}var ye=d0();vf(ye);var Ge=new u0;Ge.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ot).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{Pa()?await o$({profile:ye}):await Sa({profile:ye})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ge.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 Pv({configPath:t.config,skipVerify:t.skipVerify===!0}):await wv({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ge.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 jf({...t,profile:ye})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ge.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 bv({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Ge.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await iw({profile:ye})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ge.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 Vk({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ge.command("logout").description("Remove the Claude token (fall back to this machine's Claude Code login)").option("--shared","Clear the machine/farm-wide token in ~/.codepipe/shared.json").action(async t=>{try{await Lv({profile:ye,shared:t.shared})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ge.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 Ov({profile:ye,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ge.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await wk({profile:ye})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Ge.command("pull").description("Fetch finished task branches into your local clones (no checkout switch)").option("--profile <name>","Config profile").option("--watch","Keep pulling instead of exiting after one pass").option("--interval <sec>","Watch interval in seconds (default 60, minimum 10)",t=>parseInt(t,10)).action(async t=>{if(t.interval!==void 0&&!Number.isFinite(t.interval))throw new Error("--interval expects a number of seconds");await Xv({profile:t.profile,...t.watch?{watch:!0}:{},...Number.isFinite(t.interval)?{intervalSec:t.interval}:{}})});Ge.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).option("--debug [categories]","Write local debug logs (comma-separated categories; default: agent-request \u2014 the full prompt and context each agent job receives, under ~/.codepipe/debug/)").action(async t=>{try{await Sa({profile:ye,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var l$=Ge.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");l$.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??ee("HUB_URL")??Pt(ye)?.hubUrl??Et,r=t.token??ee("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Pa()){await _d({profile:ye});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=ee("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??ee("WORKER_NAME"),i=t.llm??ee("WORKER_LLM");await nn({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...ye?{profile:ye}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});l$.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Ve(ye)&&Pa()){await _d({profile:ye});return}await bi(ye?{profile:ye}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var u$=Ge.command("project").description("Manage CodePipe projects");u$.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Bv({profile:ye})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});u$.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 Gv({...t,cliProfile:ye})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var jd=Ge.command("repo").description("Manage the project's git repositories");jd.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 Yv({profile:ye,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});jd.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 Vv({profile:ye,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});jd.command("list").description("List the project's repos").action(async()=>{try{await zv({profile:ye})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var d$=Ge.command("model").description("Project map (model/ in the Context Repo)");d$.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 lu({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});d$.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 uu({repo:t.repo})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ge.parseAsync();